Home > Backend Development > PHP Tutorial > How Can I Retrieve the Base URL in PHP on XAMPP?

How Can I Retrieve the Base URL in PHP on XAMPP?

Barbara Streisand
Release: 2024-11-28 20:42:10
Original
457 people have browsed it

How Can I Retrieve the Base URL in PHP on XAMPP?

Retrieve Base URL with PHP

Despite using XAMMP on Windows Vista with a development URL of http://127.0.0.1/test_website/, you're encountering difficulties accessing it using PHP methods such as dirname(__FILE__) and basename(__FILE__).

To obtain the base URL in PHP, you can utilize this versatile method:

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

This code combines the server name and the requested URI to produce the complete base URL. Additionally, you may include support for HTTPS:

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

However, it's crucial to ensure proper Apache configuration to guarantee the reliability of the SERVER_NAME key. A sample configuration is provided below:

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

Finally, remember that using the HTTP_HOST key necessitates careful input handling, removing any invalid characters to ensure a valid domain. The PHP function parse_url can assist in these validation processes.

The above is the detailed content of How Can I Retrieve the Base URL in PHP on XAMPP?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template