dirname() and __FILE__ to find parent and current folder of a path or php script

PHP Add comments

__FILE__ is a magic constant along with __LINE__ and some more which i have not yet used.

dirname() is a function which returns the directory name of a path.

as we combine these two we get something interesting… at least for me.

my problem was to find the current directory of the executing php script. i was not comfortable using dirname($_SERVER['PHP_SELF']) because i got only the folder name and not the complete path…

and then i was gazing the pages online to find what could be the alternat… then it is all this __FILE__ and dirname functions which gives the complete parent folder path which i was in need of many times.

to get current director’s full abs path we can use the following
and the parent directory full abs path we can use the following
and it can go further…

$dir = str_replace ( “\”,/, dirname ( _FILE_ ) )
// for Windows based systems

another use of __FILE__ is for debugging purpose while using queries.

i have many queries executed for a page and if there was an error at any point then i have to waste time to find at which place it is unless you append some text like this to find the location (mysql_error().”while this query”)…

so i tried using similar to this to get the line number of the error occured.

mysql_query($query) or showError('status.php',mysql_error(),__LINE__,__FILE__);

if an error occured i will set the error in a session in the showError function and then i will redirect to a status page where it displays the error, line number and the filename where the error occured. and then clear the err string session to make it ready for the next error status…

the following urls are good resources for dirname and __FILE__
php.net manual for function dirname

PHP Magic Constants

Leave a Reply

Entries RSS