Home >Backend Development >PHP Tutorial >How Can I Securely Verify the Origin of Requests in PHP Instead of Relying on the Unreliable HTTP_REFERER?

How Can I Securely Verify the Origin of Requests in PHP Instead of Relying on the Unreliable HTTP_REFERER?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-21 19:21:11383browse

How Can I Securely Verify the Origin of Requests in PHP Instead of Relying on the Unreliable HTTP_REFERER?

Determining Referer in PHP: Reliable and Secure Methods

In PHP, the HTTP_REFERER server variable can indicate the page that sent or called the current page. However, due to its unreliability, a more secure approach is needed. This article discusses a better way to verify the origin of requests and ensure that they come from within your site.

Why HTTP_REFERER is Not Reliable

The HTTP_REFERER is sent by the client's browser and can be easily forged or absent. This makes it unreliable for security purposes.

Verifying Request Origin

Instead of relying on the HTTP_REFERER, consider using the following method:

  • Cookies: Cookies are sent with AJAX requests, allowing you to verify that the user has interacted with your site. By setting and checking cookies, you can authenticate users or track their browsing history on your website.

Example Code:

// Set a cookie to track user activity
setcookie("visited_my_site", true);

// Check if the cookie has been set, indicating a previous visit to your site
if (isset($_COOKIE["visited_my_site"])) {
  // Request is coming from your site.
}

Conclusion

While the HTTP_REFERER can provide some information, its unreliability makes it unsuitable for security purposes. By using cookies, you can reliably verify the origin of requests and ensure they come from within your site. This approach offers a more secure solution for authenticating users and preventing unauthorized access.

The above is the detailed content of How Can I Securely Verify the Origin of Requests in PHP Instead of Relying on the Unreliable HTTP_REFERER?. 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