Was helping a friend fix his php script today. He was not too sure about what “dirname(__FILE__)” did.
dirname() is a PHP function which returns the directory name of a file. For example if file abc.txt was in “/tmp/abc.txt” then the dirname() function would return “/tmp” .
$file = “/tmp/abc.txt”;
$path = dirname($file); // $path will now contain /tmp
What does dirname(__FILE__) and basename(dirname(__FILE__)) do then?
The __FILE__ constantÂ represents the running script. It will return the full path and file name of the running script. For example, theÂ __FILE__ constantÂ on my server would return “/var/www/html/index.php” for my index.php file which is in the “/var/www/html/” directory.
The basename() command is normally used in conjunction with the dirname() function to strip the parent directory from a full file name. For example “/var/www/html/abc.txt” when passed through basename() would return abc.txt. basename() also works on directories. So, basename() on “/var/www/html” would return “html” since in Linux directories are files.
Imagine __FILE__ represents /var/www/html/index.php
echo dirname(__FILE__); // returns /var/www/html
echo basename(__FILE__); //returns index.php
echo basename(dirname(__FILE__)); //returns html