Home  >  Article  >  Backend Development  >  How to Obtain a Client\'s IP Address in Laravel 5 ?

How to Obtain a Client\'s IP Address in Laravel 5 ?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-20 08:37:02867browse

How to Obtain a Client's IP Address in Laravel 5 ?

Obtain the Client's IP Address in Laravel 5

In PHP, obtaining a client's IP address is straightforward using $_SERVER["REMOTE_ADDR"]. However, in Laravel, this technique returns the server IP rather than the visitor's IP.

Solution:

To accurately acquire the client IP address in Laravel, use:

<code class="php">Request::ip();</code>

This function relies on Symfony's getClientIps method, which determines the client IP based on the following:

  1. Trusted Proxies:

    • If the IP is not a trusted proxy, the client IP is returned.
  2. Forwarded Headers:

    • If the Forwarded header is present and trusted, the for parameter is parsed for the client IP.
  3. Client IP Headers:

    • If the Client-IP header is present and trusted, an array of IPs is extracted and the first valid IP is returned.

Fallback:

If none of the above headers are available or trusted, the IP obtained from $_SERVER["REMOTE_ADDR"] is used.

Example:

<code class="php">$clientIp = Request::ip();</code>

This will provide the visitor's IP address, allowing you to implement IP-based functionality within your Laravel application.

The above is the detailed content of How to Obtain a Client\'s IP Address in Laravel 5 ?. 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