Home > Backend Development > PHP Tutorial > How Can I Efficiently Obtain the Base URL in PHP?

How Can I Efficiently Obtain the Base URL in PHP?

DDD
Release: 2024-12-01 17:09:11
Original
231 people have browsed it

How Can I Efficiently Obtain the Base URL in PHP?

Obtaining the Base URL with PHP

In web development environments like PHP, obtaining the base URL can be essential for various purposes. This article explores how to achieve this task effectively.

To retrieve the base URL, the recommended approach is to utilize the $_SERVER predefined variable. By combining the SERVER_NAME and REQUEST_URI keys, this method provides a reliable and accurate way to construct the base URL. Here's an example implementation:

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

This straightforward code concatenates the protocol (http://), server name (127.0.0.1), and request URI (/test_website/) to produce the base URL: http://127.0.0.1/test_website/.

For situations where HTTPS is involved, a modified function called url() can be employed:

function url(){
  return sprintf(
    "%s://%s%s",
    isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME'],
    $_SERVER['REQUEST_URI']
  );
}
echo url();
#=> http://127.0.0.1/foo
Copy after login

To ensure reliable usage of the SERVER_NAME key, it's vital to configure Apache appropriately. The following configuration snippet exemplifies this setup:

<VirtualHost *>
    ServerName example.com
    UseCanonicalName on
</VirtualHost>
Copy after login

Additionally, if relying on the HTTP_HOST key, caution should be taken to sanitize user input before usage. The PHP parse_url function offers a comprehensive example of handling such data.

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

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template