Tuesday, January 22, 2013

How can I get the folder name with PHP?


<?php

$foldername = end(explode('/', str_replace('//','/',dirname(__FILE__))));

echo $foldername;

?>

Output:
hah_this_is_my_folder

If your file path is this: /home/seval/project/hah_this_is_my_folder/index.php
Then the foldername will be hah_this_is_my_folder, so the output is that.

You can use it in whereever you want. For an example, you can use it for wordpress plugins, because sometimes users can change the plugin folder names, so you can get new plugin foldername with this code.

You know getting URL address of a file or getting DIR address of a file name is very simple in PHP.

You can also use pathinfo function to get the foldername. Here is an example:

<?php

$fullpath = dirname(__FILE__); //get the full path with this way
echo $fullpath . '<br />';

$x = pathinfo($fullpath); //get the foldername with $x["basename"]
var_dump($x);
echo '<br />' . $x['basename'] . '<br />';

$y = pathinfo($x['dirname']); //get name of parent folder of your folder
var_dump($y);
echo '<br />' . $y['basename'] . '<br />';

?>

Output:

/home/seval/workspace/test/this_is_my_folder_bitch
array(3) { ["dirname"]=> string(26) "/home/seval/workspace/test" ["basename"]=> string(23) "this_is_my_folder_bitch" ["filename"]=> string(23) "this_is_my_folder_bitch" }
this_is_my_folder_bitch
array(3) { ["dirname"]=> string(21) "/home/seval/workspace" ["basename"]=> string(4) "test" ["filename"]=> string(4) "test" }
test



***

5 comments:

mickey said...

No need to re-invent the wheel:

http://php.net/manual/en/function.pathinfo.php

Call it twice.

Seval U. said...

But still you cannot get the folder name with pathinfo function. You should again use a implode function right?

mickey said...

$s = "/home/seval/project/hah_this_is_my_folder/index.php";

$x = pathinfo($s);
$y = pathinfo($x['dirname']);

printf ("%s\n", $y['basename']);

Seval U. said...

Ok I got it. I added your suggestion into the post. I test it in my localhost, yes it is another way to get the foldername. Thanks for your comment.

mickey said...

NP. I'd rather stick to existing functions, since they do error checks and compatibility better than hand rolled ones. In this case first thing that comes to mind is directory separator on windows is different and your example will not work.

BTW, I like how you changed the folder name in the second example you posted.

Related Posts Plugin for WordPress, Blogger...