How to Get Current URL in PHP: Simple Guide
To get the current URL in PHP, combine
$_SERVER['HTTP_HOST'] and $_SERVER['REQUEST_URI']. Use "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] to build the full URL including the path and query string.Syntax
Use the following parts to build the current URL:
$_SERVER['HTTP_HOST']: The domain name (like example.com).$_SERVER['REQUEST_URI']: The path and query string (like /page.php?id=5).- Optionally, add
https://orhttp://depending on the protocol.
php
$currentUrl = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Example
This example shows how to print the full current URL including the protocol, domain, path, and query string.
php
<?php $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://"; $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $currentUrl; ?>
Output
http://localhost/example.php?id=10
Common Pitfalls
Common mistakes include:
- Not checking if HTTPS is used, so the URL always starts with
http://. - Using
$_SERVER['PHP_SELF']instead of$_SERVER['REQUEST_URI'], which misses query strings. - Assuming
$_SERVER['HTTP_HOST']is always set, which might not be true in some CLI or unusual server setups.
php
<?php // Wrong: misses query string // echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; // Right: includes query string and protocol $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://"; echo $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>
Quick Reference
Summary tips to get current URL in PHP:
- Use
$_SERVER['HTTP_HOST']for domain. - Use
$_SERVER['REQUEST_URI']for path and query. - Check
$_SERVER['HTTPS']to decide protocol. - Combine all parts to get full URL.
Key Takeaways
Combine protocol, host, and request URI to get the full current URL in PHP.
Check if HTTPS is on to use the correct protocol prefix.
Use $_SERVER['REQUEST_URI'] to include path and query string, not $_SERVER['PHP_SELF'].
Be aware that server variables may not be set in all environments.
Always test your code on your server to confirm the URL is correct.