9854-888-021 New York, NY
Posted on / by admin / in featured, PHP, Software

Path variables in PHP

Many of you develop php applications for multiple server environment. Webserver environment may be different, have different directory structure, so you have to use paths very carefully. For example in file upload script, you manually write absolute path of image directory, the application may not work on other server. To avoid this you should use inbuilt php path variables. I am posting summary of all php related path variables.

Operation: Extract file name from path
Function: string basename ( string $path  [, string $suffix  ] )
Example:
$path = /opt/lampp/htdocs/demo/test.php;
echo basename($path);
Output: test.php

Operation: Get web server root path
Variable: $HTTP_SERVER_VARS[“DOCUMENT_ROOT“]
Example:
echo $HTTP_SERVER_VARS[“DOCUMENT_ROOT“];
Output: /opt/lampp/htdocs

Operation: Get current script full path (including document root path)
Code: $HTTP_SERVER_VARS[“SCRIPT_FILENAME“]
Example:
echo $HTTP_SERVER_VARS[“SCRIPT_FILENAME“];
Output: /opt/lampp/htdocs/test.php

Operation: Get current script name (relative to root)
Variable: $HTTP_SERVER_VARS[“PHP_SELF“]
Example:
echo $HTTP_SERVER_VARS[“PHP_SELF“];
Output: test.php

Operation: Get current script name (relative to root)
Variable: $HTTP_SERVER_VARS[“PHP_SELF“]
Example:
echo $HTTP_SERVER_VARS[“PHP_SELF“];
Output: test.php

Operation: Convert relative path to absolute path
Function: string realpath ( string $path  )
Example:
echo realpath(‘../images’);
Output: /opt/lampp/htdocs/images

Operation: Get all file details
Function: mixed pathinfo ( string $path  [, int $options= PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME  ] )
Example:
$info = pathinfo($_SERVER[‘PHP_SELF’]);
print_r($info);
Output:
Array
(
[dirname] => /abhi
[basename] => EmptyPHP.php
[extension] => php
[filename] => EmptyPHP
)

Tags:

Leave a Reply