Acquire the Base URL with PHP
Navigating your website's URL structure is a critical aspect of PHP development. One common requirement is obtaining the base URL, which identifies the root directory of your website.
Solution:
To retrieve the base URL in PHP, utilize the following code:
echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
This approach amalgamates the current domain name ($_SERVER['SERVER_NAME']) with the requested path ($_SERVER['REQUEST_URI']) to provide the full base URL.
HTTPS Compatibility:
If your website utilizes HTTPS, employ the following function:
function url(){ return sprintf( "%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI'] ); } echo url(); #=> http://127.0.0.1/foo
Apache Configuration:
To ensure accurate results, verify that your Apache server is configured appropriately:
<VirtualHost *> ServerName example.com UseCanonicalName on </VirtualHost>
Considerations:
When relying on the HTTP_HOST key, which contains user input, be vigilant about sanitizing and removing any invalid characters that could compromise the URL's integrity. Utilize the parse_url function for guidance.
The above is the detailed content of How Can I Get My Website's Base URL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!