Get Current URL

The PHP super global $_SERVER contains all the information you need to access various information about the URL and can even carry variables. Often you need to get the full URL of the page you are on and this requires piecing together several of the $_SERVER variables to get the whole URL.

Sometimes, you might want to get the current page URL that is shown in the browser URL window. For example if you want to let your visitors submit a blog post to Digg you need to get that same exact URL. There are plenty of other reasons as well. Here is how you can do that.
Add the following function to a page:
<?php
function currentPageURL()
{
$pageURL = $_SERVER[‘HTTPS’] == ‘on’ ? ‘https://’ : ‘http://’;
$pageURL .= $_SERVER[‘SERVER_PORT’] != ’80’ ? $_SERVER[“SERVER_NAME”].”:”.$_SERVER[“SERVER_PORT”].$_SERVER[“REQUEST_URI”] : $_SERVER[‘SERVER_NAME’] . $_SERVER[‘REQUEST_URI’];
return $pageURL;
}
?>

OR

<?php
function currentPageURL()
{
$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;
}
?>


You can now get the current page URL using this:
<?php
echo currentPageURL();
?>

OR

<?php
function getCurrentAddress()
{
/* check for https */
$protocol = $_SERVER[‘HTTPS’] == ‘on’ ? ‘https’ : ‘http’;
/* return the full address */
return $protocol.’://’.$_SERVER[‘HTTP_HOST’].$_SERVER[‘REQUEST_URI’];
}
/* How to Use */
echo getCurrentAddress();
?>
For current page name use the below code of lines:
<?php function currentPName()
{
return substr($_SERVER[“SCRIPT_NAME”],strrpos($_SERVER[“SCRIPT_NAME”],”/”)+1); }
echo “The current page name is “.currentPName();
?>

Like to share it

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *