Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent folder of current file PHP

Tags:

php

I've done quite a bit of searching for this, so I'm sorry if this is a dupe.
Anyway, I need to get the name of the folder the current file is in. For example, I want to convert something like example.com/folder/subfolder/file.php to subfolder.
My current code is dirname($_SERVER['PHP_SELF']), but that returns /folder/subfolder instead of subfolder. Thank you!

like image 220
Andrey Avatar asked Jun 22 '12 21:06

Andrey


People also ask

What is __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.

How can I get previous directory in PHP?

If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it.

What is dirname (__ DIR __?

__DIR__ : The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__) . This directory name does not have a trailing slash unless it is the root directory.


2 Answers

The simpliest way is:

basename(__DIR__); 

https://www.php.net/manual/en/language.constants.magic.php

like image 90
Alfonso de la Osa Avatar answered Sep 20 '22 13:09

Alfonso de la Osa


You need to combine your existing code using dirname() with a call to basename():

$parent = basename(dirname($_SERVER['PHP_SELF'])); 
like image 26
DaveRandom Avatar answered Sep 20 '22 13:09

DaveRandom