Get current URL in PHP

Here is a function for getting the URL of the page being processed in PHP, the function accepts one optional parameter $ignore_port_80 (boolean) to tell it whether it should ignore the port part of the url if the port used is 80:

# Function
function get_current_url($ignore_port_80 = true) {
  $is_https = $_SERVER['HTTPS'] === 'on';
  $show_port = $_SERVER['SERVER_PORT'] !== '80' || !$ignore_port_80;

  $url = ''
    . 'http'
    . ($is_https ? 's' : '')
    . '://'
    . $_SERVER['SERVER_NAME']
    . ($show_port ? (':'.$_SERVER['SERVER_PORT']) : '')
    . $_SERVER['REQUEST_URI'];
  return $url;
}

# Examples
echo get_current_url();       # http://kadimi.com/en/some-title-123
echo get_current_url(true);   # same as above
echo get_current_url(false);  # http://kadimi.com:80/en/some-title-123

Leave a Reply

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