php 如何包含另一个php文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14699973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to include another php file?
提问by omega
I have a php file, and I want to include another php file that have css link tags and javascript source tags, but when I try to include them, it doesn't get added to the page.
我有一个 php 文件,我想包含另一个具有 css 链接标签和 javascript 源标签的 php 文件,但是当我尝试包含它们时,它没有被添加到页面中。
my php page:
我的 php 页面:
<?php
$root = $_SERVER['SERVER_NAME'] . '/mysite';
$theme = $root . '/includes/php/common.php';
echo $theme;
include($theme);
?>
common.php:
常见的.php:
<link rel='stylesheet' type='text/css' href='../css/main.css'/>";
Anyone know whats wrong? Thanks
有谁知道怎么了?谢谢
回答by Alvin Wong
PHP's includeis server-side, so you need to use the server side path. It is better to use dirname(__FILE__)instead of $_SERVER['SSCRIPT_NAME'], but $_SERVER['SERVER_NAME']is absolutely wrong.
PHPinclude是服务器端的,因此您需要使用服务器端路径。最好使用dirname(__FILE__)而不是$_SERVER['SSCRIPT_NAME'],但$_SERVER['SERVER_NAME']绝对是错误的。
Try:
尝试:
include dirname(__FILE__)."/common.php";
Or if the file you want to include is not on the same directory, change the path. For example for a parent directory, use dirname(__FILE__)."/../common.php".
或者,如果要包含的文件不在同一目录中,请更改路径。例如,对于父目录,请使用dirname(__FILE__)."/../common.php".
Note that some might suggest using include "./common.php"or similar. This couldwork, but will most likely failwhen the script invoking includeis actually being included by another script in another directory. Using dirname(__FILE__)."/common.php"will eliminate this problem.
请注意,有些人可能会建议使用include "./common.php"或类似。这可以工作,但当脚本调用实际上被另一个目录中的另一个脚本包含时,很可能会失败include。使用dirname(__FILE__)."/common.php"将消除这个问题。
回答by C1D
Change your code to this:
将您的代码更改为:
<?php
$theme = 'includes/php/common.php';
echo $theme;
include($theme);
?>
If your includes folder is in the same folder as your php page then it should work, if not add you domain name instead. SERVER_NAME is not needed in this instance.
如果您的包含文件夹与您的 php 页面位于同一文件夹中,那么它应该可以工作,如果没有添加您的域名。在此实例中不需要 SERVER_NAME。

