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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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://www.kadimi.com/en/some-title-123
echo get_current_url(true);   # same as above
echo get_current_url(false);  # http://www.kadimi.com:80/en/some-title-123

Leave a Reply