TL;DR
Use a custom function leveraging PHP's $_SERVER superglobal to build the full URL including protocol detection, host, port handling, and query string.
Gebruik een aangepaste functie die gebruikmaakt van PHP's $_SERVER superglobal om de volledige URL samen te stellen, inclusief protocoldetectie, host, poortafhandeling en querystring.
Utiliza una función personalizada que aprovecha la superglobal $_SERVER de PHP para construir la URL completa, incluyendo detección de protocolo, host, manejo de puerto y cadena de consulta.
The problem
Sometimes you need to retrieve the complete URL of the current page in PHP. This might be for canonical URLs, redirects, logging, or sharing functionality. A standard URL has this format:
protocol://username:password@host:port/path?query#fragment
Note that credentials and fragments are typically excluded from PHP URL retrieval for security and technical reasons — the fragment (hash) is never sent to the server.
The solution
Here's a reliable function that handles HTTPS detection, non-standard ports, and the full request URI:
function get_current_url()
{
$url = false;
if (isset($_SERVER['SERVER_ADDR'])) {
// Detect HTTPS
$is_https = isset($_SERVER['HTTPS']) && 'on' == $_SERVER['HTTPS'];
$protocol = 'http' . ($is_https ? 's' : '');
// Get host (prefer HTTP_HOST for virtual hosts)
$host = isset($_SERVER['HTTP_HOST'])
? $_SERVER['HTTP_HOST']
: $_SERVER['SERVER_ADDR'];
// Get port
$port = $_SERVER['SERVER_PORT'];
// Get path and query string
$path_query = $_SERVER['REQUEST_URI'];
// Build the URL
$url = sprintf('%s://%s%s%s',
$protocol,
$host,
$is_https
? (443 != $port ? ':' . $port : '')
: (80 != $port ? ':' . $port : ''),
$path_query
);
}
return $url;
}
Key features
- HTTPS detection: Automatically detects if the request is over HTTPS
- Non-standard ports: Only includes port number when it's not the default (80 for HTTP, 443 for HTTPS)
- Query string included: Uses
REQUEST_URIwhich contains both path and query string - Graceful fallback: Returns
falseif not running as a web request (e.g., CLI)
Usage example
// Get the current URL
$current_url = get_current_url();
if ($current_url) {
echo "Current URL: " . $current_url;
// Output: https://example.com:8443/page?foo=bar
} else {
echo "Not running as web request";
}
Considerations
When using this in production, be aware of a few edge cases:
- Reverse proxies: If you're behind a load balancer or reverse proxy, you may need to check
X-Forwarded-ProtoandX-Forwarded-Hostheaders - Port in HTTP_HOST: Some servers include the port in
HTTP_HOST, which could lead to duplication - Security: Never trust
HTTP_HOSTfor security-critical operations without validation
Need help with PHP development? Let's talk.
Het probleem
Soms moet je de volledige URL van de huidige pagina ophalen in PHP. Dit kan nodig zijn voor canonieke URLs, redirects, logging of deelfunctionaliteit. Een standaard URL heeft dit formaat:
protocol://username:password@host:port/path?query#fragment
Merk op dat credentials en fragments doorgaans worden uitgesloten van PHP URL-ophaling om veiligheids- en technische redenen — het fragment (hash) wordt nooit naar de server gestuurd.
De oplossing
Hier is een betrouwbare functie die HTTPS-detectie, niet-standaard poorten en de volledige request URI afhandelt:
function get_current_url()
{
$url = false;
if (isset($_SERVER['SERVER_ADDR'])) {
// Detecteer HTTPS
$is_https = isset($_SERVER['HTTPS']) && 'on' == $_SERVER['HTTPS'];
$protocol = 'http' . ($is_https ? 's' : '');
// Haal host op (verkies HTTP_HOST voor virtuele hosts)
$host = isset($_SERVER['HTTP_HOST'])
? $_SERVER['HTTP_HOST']
: $_SERVER['SERVER_ADDR'];
// Haal poort op
$port = $_SERVER['SERVER_PORT'];
// Haal pad en querystring op
$path_query = $_SERVER['REQUEST_URI'];
// Bouw de URL
$url = sprintf('%s://%s%s%s',
$protocol,
$host,
$is_https
? (443 != $port ? ':' . $port : '')
: (80 != $port ? ':' . $port : ''),
$path_query
);
}
return $url;
}
Belangrijkste kenmerken
- HTTPS-detectie: Detecteert automatisch of de aanvraag via HTTPS is
- Niet-standaard poorten: Voegt alleen poortnummer toe wanneer het niet de standaard is (80 voor HTTP, 443 voor HTTPS)
- Querystring inbegrepen: Gebruikt
REQUEST_URIdat zowel pad als querystring bevat - Veilige fallback: Retourneert
falseals het niet als webaanvraag wordt uitgevoerd (bijv. CLI)
Gebruiksvoorbeeld
// Haal de huidige URL op
$current_url = get_current_url();
if ($current_url) {
echo "Huidige URL: " . $current_url;
// Output: https://example.com:8443/page?foo=bar
} else {
echo "Wordt niet als webaanvraag uitgevoerd";
}
Overwegingen
Bij gebruik in productie moet je rekening houden met een paar edge cases:
- Reverse proxies: Als je achter een load balancer of reverse proxy zit, moet je mogelijk de
X-Forwarded-ProtoenX-Forwarded-Hostheaders controleren - Poort in HTTP_HOST: Sommige servers bevatten de poort in
HTTP_HOST, wat tot duplicatie kan leiden - Beveiliging: Vertrouw
HTTP_HOSTnooit voor beveiligingskritische bewerkingen zonder validatie
Hulp nodig bij PHP-ontwikkeling? Laten we praten.
El problema
A veces necesitas obtener la URL completa de la página actual en PHP. Esto puede ser necesario para URLs canónicas, redirecciones, registro o funcionalidad para compartir. Una URL estándar tiene este formato:
protocol://username:password@host:port/path?query#fragment
Ten en cuenta que las credenciales y fragmentos normalmente se excluyen de la obtención de URLs en PHP por razones de seguridad y técnicas — el fragmento (hash) nunca se envía al servidor.
La solución
Aquí hay una función confiable que maneja la detección de HTTPS, puertos no estándar y la URI de solicitud completa:
function get_current_url()
{
$url = false;
if (isset($_SERVER['SERVER_ADDR'])) {
// Detectar HTTPS
$is_https = isset($_SERVER['HTTPS']) && 'on' == $_SERVER['HTTPS'];
$protocol = 'http' . ($is_https ? 's' : '');
// Obtener host (preferir HTTP_HOST para hosts virtuales)
$host = isset($_SERVER['HTTP_HOST'])
? $_SERVER['HTTP_HOST']
: $_SERVER['SERVER_ADDR'];
// Obtener puerto
$port = $_SERVER['SERVER_PORT'];
// Obtener ruta y cadena de consulta
$path_query = $_SERVER['REQUEST_URI'];
// Construir la URL
$url = sprintf('%s://%s%s%s',
$protocol,
$host,
$is_https
? (443 != $port ? ':' . $port : '')
: (80 != $port ? ':' . $port : ''),
$path_query
);
}
return $url;
}
Características principales
- Detección de HTTPS: Detecta automáticamente si la solicitud es a través de HTTPS
- Puertos no estándar: Solo incluye el número de puerto cuando no es el predeterminado (80 para HTTP, 443 para HTTPS)
- Cadena de consulta incluida: Utiliza
REQUEST_URIque contiene tanto la ruta como la cadena de consulta - Respaldo elegante: Devuelve
falsesi no se ejecuta como una solicitud web (por ejemplo, CLI)
Ejemplo de uso
// Obtener la URL actual
$current_url = get_current_url();
if ($current_url) {
echo "URL actual: " . $current_url;
// Salida: https://example.com:8443/page?foo=bar
} else {
echo "No se está ejecutando como solicitud web";
}
Consideraciones
Al usar esto en producción, ten en cuenta algunos casos especiales:
- Proxies inversos: Si estás detrás de un balanceador de carga o proxy inverso, es posible que necesites verificar los encabezados
X-Forwarded-ProtoyX-Forwarded-Host - Puerto en HTTP_HOST: Algunos servidores incluyen el puerto en
HTTP_HOST, lo que podría llevar a duplicación - Seguridad: Nunca confíes en
HTTP_HOSTpara operaciones críticas de seguridad sin validación
¿Necesitas ayuda con desarrollo PHP? Hablemos.