PASSWORD RESET

Your destination for complete Tech news

PHP

How to get the current URL in PHP?

256 0
< 1 min read

To get the current URL in PHP, you can use the $_SERVER['REQUEST_URI'] variable. This variable contains the path of the current request, including the query string (if any).

For example:

$current_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// $current_url will be something like 'http://example.com/path/to/page?query=value'

You can also use the $_SERVER['PHP_SELF'] variable to get the path of the current script, or the $_SERVER['SCRIPT_NAME'] variable to get the path of the current script, including the script name.

For example:

$current_path = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$current_script = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];

// $current_path will be something like '/path/to/page.php'
// $current_script will be something like '/path/to/page.php'

Note that these variables are not reliable if the website is running behind a reverse proxy. In that case, you may need to use other variables, such as $_SERVER['HTTP_X_FORWARDED_HOST'] or $_SERVER['HTTP_X_FORWARDED_PROTO'], to reconstruct the correct URL.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.