仅包含一个 php 文件到另一个 php 文件的 var


Include only var from one php file to another

url.php中有一个变量。我想在多个其他文件中访问它。我试图在所有这些文件中包含url.php。但有一个问题。

<?php
 include 'url.php';   //include url.php
 echo "My id is : $myid";
?>
<!DOCTYPE html>
<html>
<head>
<!-- AddThis Smart Layers END -->
</head>
//somecontent
<body>

url.php有html代码,包括按钮,div等。当我包含url.php时,所有这些都包括在内。

如何仅包含 php 变量并从 url.php 跳过其他 html 代码。

网址.php看起来像这样:

<?php
$myid=$_POST['myid'];
echo "myID is : <br>";
echo $myid;
?>
<html>
   <head>
    <html xmlns:fb="http://ogp.me/ns/fb#">
     </head>
  //some othe html stuff
</html>
You can put some condition there like isset().
<?php
 if(isset($_POST['myid']))
  {
   $myid=$_POST['myid'];
   echo "myID is : <br>";
   echo $myid;
  }
 else{
?>
 <html>
  <head>
   <html xmlns:fb="http://ogp.me/ns/fb#">
  </head>
    //some othe html stuff
 </html>
 <?php } ?>

另一种解决方案是您可以将变量保存在会话中,稍后您也可以在其他页面中检索该值。

网址.php

<?php
$myid=$_POST['myid'];
session_start();
$_SESSION['my_id']=$myid;
?>

您可以像这样使用变量。useMyId.php''

<?
session_start();
$var=$_SESSION['my_id'];
echo "Here is the variable".$var;
?>
你不能

这样做。唯一的方法是删除 HTML 并将其包含在其他地方。对 include 的调用是打开文件,然后对内容运行eval。如果它包含您网站的重要 UI 部分,您应该重新考虑您的设计模式。

您可以在

包含url.php之前在每个 PHP 文件中声明一个变量。
喜欢这个:
$uservar = 1;

然后在您的 URL 中.php将 HTML 块放在 if 语句中


if($usevar != 1){
HTML-BlOCK }