包含在php中的相对路径

时间:2014-07-09 10:17:50

标签: php security directory

我有一个在整个网站中使用的公共包含文件,它位于主目录中。 现在在include中使用相对路径我有两个选择:

使用文档根目录转到root,然后使用路径包含我的文件

<?php
include $_SERVER['DOCUMENT_ROOT']."/lib/sample.lib.php";
?>

OR

使用chdir将脚本的工作目录更改为主目录,然后包含我的文件。

<?php 
$what_was = getcwd(); 
chdir("/path/to/roo/directory/"); 
include("/lib/sample.lib.php"); 
chdir($what_was); 
?>

我想问一下上述哪种方法在性能和安全性方面都很好?

1 个答案:

答案 0 :(得分:3)

我认为没有。

始终使用 __ FILE __ 常量和 dirname()功能的某种组合。

例如:

<?php
  $root_dir = dirname(dirname(__FILE__)); // assuming the root dir is 1 directories behind the executed file.
  include($root_dir . "/lib/sample.lib.php");
?>

<强>参考文献: