开发者

php paths that work on both local (mac) and remote server

I'm testing a website on my local machine and I'm wondering what would be the best way to write paths to make sure they work when I upload the site to its final location.

In general I'm a bit confused about paths, and in many cases I have to 'tweak' each path until it works, so wouldn't want to be forced to do the same on a production site!

I'm not clear when to use $_SERVER['DOCUMENT_ROOT']. For example, I 开发者_运维百科have a directory that I want to scan, which is just under the root. So why can't I just use "/dirname"?

$dir = $_SERVER['DOCUMENT_ROOT'] . '/uploads'; //this works
// $dir = "/uploads"; //this doesn't work

if (is_dir($dir)) {
  //do something..
}


I'm not clear when to use $_SERVER['DOCUMENT_ROOT']. For example, I have a directory that I want to scan, which is just under the root. So why can't I just use "/dirname"?

When you work with paths in the php file the root (/) is the root of the filesystem, not the root you get when you visit your website.

So $dir = "/uploads"; gives you the filesystem root.

To minify your problems I would declare a variable in a configuration file that specifies the root of your php application, and use that path+whatever more is needed.


As adamse mentioned, the reason you can't use the '/path' is because it points to the root of the filesystem.

However, instead of declaring a variable that defines the root, I recommend using dirname(__FILE__) to retrieve the full path to the directory that the calling file is in.

From there, append relative path information to the file you want and you end up with a complete path, fully dynamically.

For example, if you want to include the 'header.php' file in the directory above the file that you wish to include it in use: include(dirname(__FILE__) . '/../header.php');

The beauty of that is that PHP will always automatically convert the forward slash to the directory separator required for the host OS.


I would define a variable/constant that describes the absolute filesystem path to the application. Something like this:

$appDir = rtrim(str_replace('\\', '/', realpath(dirname(__FILE__))), '/');

Then you have this base path you can address your application’s files from:

include $appDir.'/library/foo/bar.php';

Or you even change your include path to that directory:

set_include_path($appDir);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜