Paths and Directories in PHP


There are a few inbuilt PHP functions you can use to find out file paths. This is useful for finding the exact location (relative or absolute) of your scripts or pages. Here's a few example. Before you try these out, create a new PHP page and save it as fileDir.php.

Get the Absolute Path of a File


$absolute_path = realpath("fileDir.php");

print "Absolute path is: " . $absolute_path;


To get the exact path of file, then, you can use realpath(). In between the round brackets of the function, type the name of the file.

Get the Directory, but not the file name


$dir = dirname("folder/myphp/fileDir.php");

print "directory is: " . $dir . "<BR>";


To get the names of the folders, you can use the dirname( ) function. This will strip off the name of the file and return the rest of the text between the round brackets of the function.

Get the Filename only


$bas = basename("folder/myphp/fileDir.php");

print "File Name is: " . $bas . "<BR>";


If you only need to get at the name of the file, then use the basename( ) function. When you type a longer file path in between the round brackets of the function, it will strip off the rest and leave the name of the file.


Final Note

Careful when allowing users to upload files from external sources. This could be used to attack your site. There are a few security implications when working with files. For a more in-depth discussion on this, and other security issues, see this page:

If the above page is down, we highly recommend a Google search on PHP security issues.