netizen0911
netizen0911

Reputation: 461

PHP: How to get the last directory paths and echo them

I have my .htaccess and index.php files located inside "localhost/poppers/f/". I have all url request from "/f/" directory processed by index.php. What I want to get and echo is just the whole path after the "f" directory regardless of how many trailing slash it contains.

Example: localhost/poppers/f/abcdef/123456/xyz/456

Output I want is: abcdef/123456/xyz/456 (regardless of the number of the following directories)

What I'm trying to use is: dirname(dirname($_SERVER['REQUEST_URI'])), but doesn't seem to work.

Upvotes: 1

Views: 162

Answers (2)

anubhava
anubhava

Reputation: 786091

You can add an environment variable in your rewrite rule and access it inside the PHP code:

Keep your /poppers/f/.htaccess like this:

RewriteEngine On
RewriteBase /poppers/f/

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+) index.php [L,E=URIPART:$1]

This will route every request to index.php and set relative path from /poppers/f/ as an env variable URIPART.

Now inside your index.php just get this value as:

$_SERVER["REDIRECT_URIPART"]

which will show value: abcdef/123456/xyz/456

Upvotes: 1

dynamic
dynamic

Reputation: 48141

$string = "localhost/poppers/f/abcdef/123456/xyz/456";
$parts = explode('/', $string);

At this point you can simply remove the first two parts and implode() the rest...

echo implode( array_slice($parts,3), '/' );

Upvotes: 1

Related Questions