Getting The Current URI In PHP

15th April 2008 - 1 minute read time

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.