【问题标题】:Using outside variables inside an included file (PHP)在包含的文件中使用外部变量 (PHP)
【发布时间】:2012-11-06 16:44:41
【问题描述】:

我的目标是让多个站点运行相同的文件,但有一组变量来确定要访问哪个数据库:

<?php 

$siteDB = "this";
$domainName = "thisdomain";
$twitterName = "thistwitter";
$facebookName = "thisfacebook";

include 'http://www.mysite.com/site_files/index.php'; 

?>

当我尝试访问 site_files/index.php 中的变量时,它们返回 NULL。我也尝试使用$GLOBALS['siteDB'],但没有运气,这并不让我感到惊讶。

我知道有几个与此类似的问题,但我也想问一下这是否是最好的方法。我应该使用某种类型的配置文件还是会话变量?


我的网站文件整理如下:

www.mysite.com/site1

www.mysite.com/site2

www.mysite.com/site3

www.mysite.com/site4


这些站点的文件位于:

www.mysite.com/site_files


当文件更新时,因为所有站点都访问同一个文件,所以它们都会更新。上面的文件将位于:

www.mysite.com/siteX/index.php

【问题讨论】:

  • 是您服务器本地目录中的site_files/index.php,还是您确实包含了一些外部脚本?
  • 然后简单地将其包含在相对/绝对路径include "site_files/index.php"
  • 我没有问题,包括来自 site_files 目录的index.php,我需要访问包含文件之外的变量。例如,如果我在site_files/index.php 中输入echo $domainName,它将返回“thisdomain”。

标签: php variables include


【解决方案1】:

制作一个配置文件,并将其包含在您的其他文件中。

配置文件示例:

$config = array('site' => "this",
 'domain' =>  "thisdomain",
  'twitter' => "thistwitter",
 'facebook' => 'thisfacebook'
);

【讨论】:

  • 如何确定使用哪个配置文件?每个站点都有自己的配置文件,站点文件的 index.php 将被所有站点访问。
【解决方案2】:

我认为是 $GLOBALS['siteDB'] 而不是 $GLOBAL['siteDB']

【讨论】:

  • 是的,你是对的,我改变了它。在我的代码中是 $GLOBALS['siteDB']。
【解决方案3】:

我最终通过使用绝对 URL 开始工作。

代替:

<?php 

$siteDB = "this";
$domainName = "thisdomain";
$twitterName = "thistwitter";
$facebookName = "thisfacebook";

include 'http://www.mysite.com/site_files/index.php'; 

?>


我被建议使用:
<?php 

include $_SERVER['DOCUMENT_ROOT'].'/site1/config.php'; 
include $_SERVER['DOCUMENT_ROOT'].'/site_files/index.php'; 

?>

其中/site1/config.php 包含:

$siteDB = "this";
$domainName = "thisdomain";
$twitterName = "thistwitter";
$facebookName = "thisfacebook";

【讨论】:

    【解决方案4】:

    由于没有一个答案能解释实际问题是什么,尽管问题已经解决,但我会尝试一下。

    使用时:

    include 'http://www.mysite.com/site_files/index.php'; 
    

    您的服务器向地址 www.mysite.com/site_files/index.php 发出 http 请求,就像您请求页面时浏览器所做的一样。

    mysite.com 上的服务器将简单地解析其 php 并返回结果。此结果将包含在您的脚本中,但它不会(可能...)包含 php 代码,而是由 /site_files/index.php 生成的 html 字符串。

    如果您想将变量传递给您请求的 url,您可以使用:

    include 'http://www.mysite.com/site_files/index.php?var1=some_value;etc=value';
    

    但这可能不是您想要的,因为如果所有文件都驻留在同一个文件系统上,这会使您的设置不必要地复杂化。

    底线,如果你想包含一个 php 脚本,不要从网络服务器请求它,而是从文件系统请求它。

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 2014-10-17
      • 2015-10-17
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      相关资源
      最近更新 更多