PHP Get Current URL Full Path

In PHP Get Current URL, I have explained how get current page URL with parameters in PHP. To Get Current URL of the Page, we can use $_SERVER environment variables.


Below is the list of useful environment variables for getting current Page URL.



$_SERVER['HTTP_HOST'] => Host name from the current request.
$_SERVER['HTTP'] => Set to a non-empty value if the protocol is HTTP
$_SERVER['HTTPS'] => Set to a non-empty value if the protocol is HTTPS
$_SERVER["SERVER_PORT"] => Server port. Default is: 80
$_SERVER['REQUEST_URI'] => The URI to access this page;
For example, '/index.php'.


1). We can get protocol schema


$schema = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";


2). If the server is running on standard port(80,443), full URL path becomes:


$schema.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
//EX: http://www.hayageek.com/test.php


3). If the server is running on non standard port, full URL Becomes


$schema.$_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];

//EX: http://www.hayageek.com:8080/test.php
Note: In PHP, We can not read URL path after hash(#) tag. Because browser does not send the hash data to server. You can get #tag data only with JavaScript.


Combing all, below is the function for getting current web page URL in PHP



function getCurrentURL()
{
$currentURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
$currentURL .= $_SERVER["SERVER_NAME"];

if($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443")
{
$currentURL .= ":".$_SERVER["SERVER_PORT"];
}

$currentURL .= $_SERVER["REQUEST_URI"];
return $currentURL;
}
Usage:


echo getCurrentURL();


Source Help - http://hayageek.com

1 Comments

  1. Nice post. I learn something totally new and challenging
    on blogs I stumbleupon everyday. It will always be exciting to read
    articles from other writers and practice a little something from their
    sites.

    ReplyDelete

Post a Comment

Post a Comment

Previous Post Next Post