Home  >  Article  >  Backend Development  >  php output address before jump

php output address before jump

WBOY
WBOYOriginal
2023-05-06 20:27:06709browse

In front-end development, we often need to jump to other pages. Before jumping, sometimes we need to get the address of the current page. So in PHP, how to output the address of the current page?

For this problem, there are two ways to achieve it.

Method 1: Use the $_SERVER['HTTP_REFERER'] variable

$_SERVER['HTTP_REFERER'] This variable can get the previous URL address of the current page. It is sent by the browser in an HTTP request header. Normally it will contain the full URL of the page the current request is for, but sometimes it can be empty.

The code for this method is as follows:

$current_url = $_SERVER['HTTP_REFERER'];
echo '当前页面的地址是:' . $current_url;

It should be noted when using this method that the value of $_SERVER['HTTP_REFERER'] may be tampered with or cleared by the browser, so this method Not very reliable.

Method 2: Use the $_SERVER['REQUEST_URI'] variable

$_SERVER['REQUEST_URI'] This variable can obtain the URI (Uniform Resource Identifier) ​​address of the current request. It represents the path of the currently requested page relative to the domain name, including the query string. Using this variable ensures that we get the address of the current page, not the address of the previous page.

The code of this method is as follows:

$current_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo '当前页面的地址是:' . $current_url;

It should be noted when using this method that $_SERVER['REQUEST_URI'] contains the query string. If you do not need the query string, you can use PHP's parse_url function is used to obtain the pure path part. The code is as follows:

$current_url = 'http://' . $_SERVER['HTTP_HOST'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
echo '当前页面的地址是:' . $current_url;

Summary

The above are the two methods of outputting the current page address in PHP. While both methods have their pros and cons, using the $_SERVER['REQUEST_URI'] variable is generally more reliable. No matter which method you use, you need to pay attention to security issues and avoid problems such as XSS (cross-site scripting) attacks.

The above is the detailed content of php output address before jump. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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