etsnyman
etsnyman

Reputation: 275

PHP: Get path after domain from current URL

I am a complete beginner to PHP, so please keep that in mind.

I am attempting to get JUST the path from the current URL, which is variable. For instance, if the current URL is http://example.com/blog/2014/blogpost.html then I would like to get /blog/2014 or something very similar.

This is the PHP code I have so far:

$full_url = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$path_info =  parse_url($full_url,PHP_URL_PATH);
echo $path_info;

However, this does not work, and I can't seem to Google a suitable solution.

Does anyone have any pointers?

Thanks in advance!

Upvotes: 3

Views: 10149

Answers (3)

danmullen
danmullen

Reputation: 2510

The following should give you "/blog/2014/" from your example:

$path_info = substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], $_SERVER['SCRIPT_FILENAME']));

Upvotes: 0

Ryan Willis
Ryan Willis

Reputation: 624

You can use strrpos to get the last index of / and pull the part of the URI before that with:

$req_uri = $_SERVER['REQUEST_URI'];
$path = substr($req_uri,0,strrpos($req_uri,'/'));

This will give you exactly what you wanted (/blog/2014)

Upvotes: 7

Peyman.H
Peyman.H

Reputation: 1952

you can do this:

$url = "http://example.com/blog/2014/blogpost.html" ;
$parts = explode('/' , $url );
// then use any part of $parts by using $parts[i]

Upvotes: -1

Related Questions