How to get the absolute server path name of an executing script in PHP

One of the most important requirement before you can use any file reading PHP functions such as fopen, file_get_contents, readfile, etc is the absolute server path name.Some of these functions won’t work if you do not use the absolute server path name to the file that needs to be read or open.

An example of an absolute server path name is that it is relative to the root directory of a Linux/Unix based server like: /home/www/php-developer.org/wp-content/uploads/scripts/PHP-Server-Array-Variables.php

To get the absolute server path name, do the following:

1.) Open a text editor and copy/paste the code below:

<?php
echo $_SERVER['SCRIPT_FILENAME'];
?>

2.) Save it as serverpath.php

3.) Upload it to the path you wish you determine. Supposing I want to determine the absolute server path name of my website root directory (or the homepage www.php-developer.org), so I will upload serverpath.php to the root directory. If you want to determine the absolute server path to the folder in your website, then upload the script inside that folder.

4.) Now execute the script in the browser. For example if I upload the serverpath.php to the root directory of my website, I will execute it as follows(enter the URL in the browser and then press enter):

http://www.php-developer.org/serverpath.php

Supposing I upload it inside a folder named as “folderx”, so I will enter the URL in the browser address bar:

http://www.php-developer.org/folderx/serverpath.php

5.) The absolute server path name will then be shown to you which you can use then in your scripts (e.g in a readfile function).

Bear in mind that this can be a security risk, so delete the script after you have determine the path.



Related posts: