Home > Backend Development > PHP Tutorial > How Can I Get My Website's Base URL Using PHP?

How Can I Get My Website's Base URL Using PHP?

DDD
Release: 2024-12-03 13:40:14
Original
529 people have browsed it

How Can I Get My Website's Base URL Using PHP?

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'];
Copy after login

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
Copy after login

Apache Configuration:

To ensure accurate results, verify that your Apache server is configured appropriately:

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

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!

source:php.cn
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