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?
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.
PHP_URL_PATH (int) Outputs the path of the URL parsed. PHP_URL_QUERY (int) Outputs the query string of the URL parsed.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With