What does dirname(__FILE__) and basename(dirname(__FILE__)) do?

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” .

Example Usage;

<?php

$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.

Example Usage;

Imagine __FILE__ represents /var/www/html/index.php

<?php

echo dirname(__FILE__); // returns /var/www/html

echo basename(__FILE__); //returns index.php

echo basename(dirname(__FILE__)); //returns html

?>

3 Responses to “What does dirname(__FILE__) and basename(dirname(__FILE__)) do?”

Author comments are in a darker gray color for you to easily identify the posts author in the comments

  1. ehthisham says:

    /var/www/dec/file.php
    dirname() will give /var/www/dec
    then how to get ‘/var/www’ can i use dirname again

  2. Sanni says:

    Good article. I like it.

  3. Vikram says:

    dirname(dirname(_FILE_))

Leave a Reply

© 2008-2009 The Danesh Project
Powered by Wordpress and made by Guerrilla. Best viewed in Mozilla Firefox