Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - parse current URL

Tags:

php

parsing

I need to parse the current url so that, in either of these cases:

http://mydomain.com/abc/
http://www.mydomain.com/abc/

I can get the return value of "abc" (or whatever text is in that position). How can I do that?

like image 785
sol Avatar asked Apr 08 '11 17:04

sol


People also ask

How can I get full URL in PHP?

The necessary superglobal variables such as $_SERVER['HTTPS'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PORT'] are used to get full URL in PHP. The variable HTTPS can easily retrieve the protocol in the URL of a webpage. If it returns a value “on”, then the protocol is HTTPS.

What is Php_url_path?

PHP_URL_PATH (int) Outputs the path of the URL parsed. PHP_URL_QUERY (int) Outputs the query string of the URL parsed.

How do I get a full URL?

Append the HTTP_HOST(The host to which we have requested, e.g. www.google.com, www.yourdomain.com, etc…) name of the server. Append the REQUEST_URI(The resource which we have requested, e.g. /index. php, etc…) to the URL string.


1 Answers

You can use parse_url();

$url = 'http://www.mydomain.com/abc/';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);

which would give you

Array
(
    [scheme] => http
    [host] => www.mydomain.com
    [path] => /abc/
)
/abc/

Update: to get current page url and then parse it:

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

print_r(parse_url(curPageURL()));

echo parse_url($url, PHP_URL_PATH);

source for curPageURL function

like image 69
KJYe.Name Avatar answered Sep 30 '22 12:09

KJYe.Name