Programming Tips - PHP: Get my URL in php

Date: 2016nov26 Update: 2026jan24 Language: php Q. PHP: Get my URL in php A. Glue together some environment variables like this:
# Helper function function safeAccess(array &$myarray, string $key): string { if (!isset($myarray[$key])) return ''; return $myarray[$key]; } function getMyUrl(): string { $scheme = getScheme(); # See another davekb page $host = safeAccess($_SERVER, 'HTTP_HOST'); $uri = safeAccess($_SERVER, 'REQUEST_URI'); if (!str_starts_with($uri, '/')) $uri = '/' . $uri; # Ensure leading slash return "$scheme://$host$uri"; } # If you want the URL without the query string function getMyUrlNoQs(): string { $url = getMyUrl(); return substr($url, 0, strrpos($url, '?')); } # How to get just the Query String function getQs(): string { return safeAccess($_SERVER, 'QUERY_STRING'); }
# Example use: <?php print "My URL is " . getMyUrl() . "<br>\n" ?>
Here is the code for getScheme() in php: https://www.davekb.com/browse_programming_tips:php_get_scheme:txt