Andrey
Andrey

Reputation: 859

Get parent folder of current file 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!

Upvotes: 26

Views: 50735

Answers (4)

Alfonso de la Osa
Alfonso de la Osa

Reputation: 1574

The simpliest way is:

basename(__DIR__);

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

Upvotes: 56

contrid
contrid

Reputation: 980

$folder = basename(dirname(__FILE__));

Upvotes: 4

Luke Pittman
Luke Pittman

Reputation: 843

dirname() used with basename() would work ... also this if you want to get them all:

$folders = explode ('/', $_SERVER['PHP_SELF']);

Now $folders would contain an array of all of the folder names.

Cheers.

Upvotes: 4

DaveRandom
DaveRandom

Reputation: 88647

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

$parent = basename(dirname($_SERVER['PHP_SELF']));

Upvotes: 38

Related Questions