How to get the URL of the Current Page using PHP Server Variables

0saves

There are times when you might want the URL of the current page. The URL is the one which is shown in the address bar of the browser. This might be the case when you want the user to notify that at which page he or she is or there might be a situation when you want your visitors to submit a blog post to social bookmarking sites or twitter directly from your webpage, there are loads of reasons for which you might use this script.

In this post I am writing and explaining the code to retrieve the URL of the page.

A function named getURL is defined which can be used whenever you want to get the URL of the page.

PHP Function

<?php
function getURL()
{
 $url = 'http';
 if ($_SERVER["HTTPS"] == "on")
 {
 $url .= "s";
 }
 $url .= "://";
 if($_SERVER["SERVER_PORT"] != "80")
 {
 //$_SERVER["SERVER_NAME"] --> The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
 //$_SERVER["SERVER_PORT"] --> The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
 //$_SERVER["REQUEST_URI"] --> The URI which was given in order to access this page; for instance, '/index.html'.

 $url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 }
 else
 {
 $url .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $url;
}
?>

You can now get the current page URL using the line:

<?php
 echo getURL();
?>

Reference : http://php.net, http://www.webcheatsheet.com

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Related posts:

  1. PHP : Array Functions Tutorial – Part 3
  2. PHP : Array Functions Tutorial – Part 2
  3. When you should consider a Virtual private server or dedicated server for your business
  4. Function : Converts GMT time to a localized value
  5. Function : Converts a local Unix timestamp to GMT
  6. 11 Most Important String Functions in PHP a programmer should know
  7. Open Source Invoicing Software ? BambooInvoice
  8. What are class, methods, objects and instance in PHP – Object Oriented Concepts
  9. PHP Page Counter for website using a flat file and file handlings without database
  10. What is LAMP server and How to install it

3 Comments + Add Comment

Leave a comment


+ four = six

CommentLuv badge