Home > Backend Development > PHP Tutorial > How Can I Retrieve the Base URL in PHP for Local Development?

How Can I Retrieve the Base URL in PHP for Local Development?

DDD
Release: 2024-12-05 00:24:10
Original
290 people have browsed it

How Can I Retrieve the Base URL in PHP for Local Development?

Getting the Base URL with PHP

When working on local development environments, retrieving the base URL can be a common task. In XAMPP on Windows Vista, the base URL typically takes the form of http://127.0.0.1/test_website/. This article demonstrates how to retrieve this base URL using PHP.

Using the $_SERVER Variable

One effective method is to utilize the $_SERVER predefined variable, which provides information about the current request. To get the base URL, you can use the following code:

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

Supporting HTTPS

If you plan to support HTTPS, you can use 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();
Copy after login

Apache Configuration

To ensure that you can safely use the SERVER_NAME key, it's recommended to configure Apache properly. Add the following lines to your Apache Virtual Host configuration:

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

Caution when Using HTTP_HOST

If you rely on the HTTP_HOST key, which contains user input, you must carefully sanitize it. Remove any invalid characters that are not allowed in domain names. Refer to PHP's parse_url function for guidance.

The above is the detailed content of How Can I Retrieve the Base URL in PHP for Local Development?. 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