Getting The Current URI In PHP

15th April 2008

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.

  1. echo ''.print_r($_SERVER, true).'';

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.

  1. function currentUri(){
  2. $uri = 'http';
  3. if(isset($_SERVER['HTTPS'])){
  4. if($_SERVER['HTTPS'] == 'on'){
  5. $uri .= 's';
  6. };
  7. };
  8. $uri .= '://';
  9. if($_SERVER['SERVER_PORT'] != '80'){
  10. $uri .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
  11. }else{
  12. $uri .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
  13. };
  14. return $uri;
  15. }

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.