Home >Backend Development >PHP Tutorial >How Can I Programmatically Get the Base URL in PHP?

How Can I Programmatically Get the Base URL in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 14:55:11270browse

How Can I Programmatically Get the Base URL in PHP?

Getting the Base URL in PHP

In your development environment, where you are using a local URL such as http://127.0.0.1/test_website/, it can be useful to programmatically obtain the base URL for various functions. However, commonly used methods like dirname(__FILE__) and basename(__FILE__) will not produce the desired output.

Solution 1:

To accurately obtain the base URL, you can utilize the following code:

<?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>

This approach uses the $_SERVER predefined variable to access the server name and request URI, effectively constructing the base URL.

Solution 2 (for Supporting HTTPS):

If you need to support HTTPS as well, consider using the following function:

function url(){
  return sprintf(
    "%s://%s%s",
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME'],
    $_SERVER['REQUEST_URI']
  );
}

Caution:

When relying on the SERVER_NAME key, ensure that your Apache configuration is set up correctly. If not, you should explicitly specify the server name in your virtual host configuration:

<VirtualHost *>
    ServerName example.com
    UseCanonicalName on
</VirtualHost>

Additional Note:

Using the HTTP_HOST key requires additional cleanup to ensure valid characters for a domain. Consider using the PHP builtin parse_url function for this purpose.

The above is the detailed content of How Can I Programmatically Get the Base URL in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn