简体   繁体   English

如何包含另一个php文件?

[英]how to include another php file?

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: 的common.php:

<link rel='stylesheet' type='text/css' href='../css/main.css'/>";

Anyone know whats wrong? 谁知道什么是错的? Thanks 谢谢

PHP's include is server-side, so you need to use the server side path. PHP的include是服务器端,因此您需要使用服务器端路径。 It is better to use dirname(__FILE__) instead of $_SERVER['SSCRIPT_NAME'] , but $_SERVER['SERVER_NAME'] is absolutely wrong. 最好使用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. 请注意,有些人可能会建议使用include "./common.php"或类似内容。 This could work, but will most likely fail when the script invoking include is actually being included by another script in another directory. 可能有效,但是当脚本调用include实际上被另一个目录中的另一个脚本包含时,很可能会失败 Using dirname(__FILE__)."/common.php" will eliminate this problem. 使用dirname(__FILE__)."/common.php"将消除此问题。

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. 如果您的包含文件夹与您的php页面位于同一文件夹中,那么它应该可以工作,如果不是添加您的域名。 SERVER_NAME is not needed in this instance. 在此实例中不需要SERVER_NAME。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM