Getting The Current URI In PHP

The $_SERVER superglobal array contains lots of information about the current page location. You can print this off in full using the following line of code.

echo '<pre>'.print_r($_SERVER, true).'</pre>';

Although this array doesn't have the full URI we can piece together the current URI using bits of the $_SERVER array. The following function does this and returns a full URI.

function currentUri(){
 $uri = 'http';
 if(isset($_SERVER['HTTPS'])){
  if($_SERVER['HTTPS'] == 'on'){
   $uri .= 's';
  };
 };
 $uri .= '://';
 if($_SERVER['SERVER_PORT'] != '80'){
  $uri .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
 }else{
  $uri .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
 };
 return $uri;
}

You can use this function like this:

echo currentUri();

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
9 + 11 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.