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

pathphp

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..
}

Best Solution

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.

Related Question