Get the full current URL in PHP (and the proxy trap)
"What is the full URL of the current page?" PHP does not give you one variable for it; you assemble it from $_SERVER values. The official manual documents each piece, plus the proxy caveat that breaks naive code. Here is the correct assembly.
The pieces, per the manual
$_SERVER['HTTP_HOST']: the host name from the request's Host header.$_SERVER['REQUEST_URI']: the URI that was accessed, including the query string.$_SERVER['HTTPS']: set to a non-empty value if the script was queried through HTTPS.
Assemble it
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
? 'https' : 'http';
$url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
REQUEST_URI already includes the path and the ?query part, so no separate query handling is needed.
The proxy trap
The manual's warning matters in production: behind a proxy or load balancer, $_SERVER['HTTPS'] may not report the truth. The client can connect to the load balancer over HTTPS while the balancer talks plain HTTP to your server, so your code builds http:// URLs for an https:// site. If that matches your setup, check the forwarded headers your proxy sets (commonly HTTP_X_FORWARDED_PROTO) before trusting the scheme.
Related variables worth knowing
$_SERVER['QUERY_STRING']: just the query string, without the path.$_SERVER['PHP_SELF']: the executing script's path, without the query string.
Common mistakes
- Hardcoding
http://, then mixed-content warnings after moving to HTTPS. - Trusting the scheme behind a load balancer without checking forwarded headers.
- Rebuilding the query string by hand when
REQUEST_URIalready carries it.
Related: PHP cURL POST example for calling other servers, and prepared statements for what goes into the database.
