
This Get URL of Current Page With PHP code snippet page will describe the methods involved in obtaining the current page url with php. There are many times when it comes in handy to be able to get the current URL via PHP. There are also various components on the URL that you may want to get, I will outline for you the techniques involved in getting the most popular URL components, and also show you how to combine them all to get the full url with php.
Get The Protocol (HTTP vs HTTPS)
1 |
echo $current_page_protocol =(isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"]=="on") ? "https://" : "http://"; |
This would echo http:// or https://, whichever is set for the current page.
Get Server Name
1 |
echo $_SERVER["SERVER_NAME"]; |
This would echo the server name, subdomains would be included if there are any. For this it would echo www.clevelandwebdeveloper.com.
Get URI
1 |
echo $_SERVER["REQUEST_URI"]; |
This would echo everything after your server name. If your URL was www.mysite.com/some/page, it would echo ‘/some/page’.
Get URI Without Querystring
1 |
echo $uri_no_querystring=strtok($_SERVER["REQUEST_URI"],'?'); |
If your URL was www.mysite.com/some/page?id=23, the previous snippet would echo ‘/some/page?id=23’. This snippet would echo ‘/some/page’.
Putting it all together to Get URL of Current Page With PHP
1 2 |
$current_page_protocol =(isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"]=="on") ? "https://" : "http://"; echo $current_page_protocol . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]; |
If you wanted the full URL without the querystring, substitute $_SERVER[“REQUEST_URI”] with strtok($_SERVER[“REQUEST_URI”],’?’)