Help us understand the problem. What is going on with this article?

Request::ip()でIPアドレスの取得

More than 3 years have passed since last update.

環境

  • Laravel 5.2-5.3

サンプルは5.3のapp/Http/Controllers/Auth/RegisterController.php

普通に使うと

\Request::ip()で取得できるはずだけどリバースプロキシ環境下だったりすると上手く取得できない。

class RegisterController extends Controller
{
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'ip' => \Request::ip(),
        ]);
    }
}

プライベートIPしか取得できない時は以下を試す

修正版

class RegisterController extends Controller
{
    protected function create(array $data)
    {
        \Request::setTrustedProxies(['10.0.0.0/8']);

        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'ip' => \Request::ip(),
        ]);
    }
}

['10.0.0.0/8']は各自の環境に合わせて書き換え。

LaravelではなくSymfonyの範疇。
https://github.com/symfony/http-foundation/blob/master/Request.php
setTrustedProxiesまでは分かったけどどう書けばいいんだろうと調べたら答えはドキュメントにあった。
http://symfony.com/doc/current/components/http_foundation/trusting_proxies.html

http://symfony.com/doc/current/cookbook/request/load_balancer_reverse_proxy.html

まぁ今更IP取得することとかほとんどないけど。
重要ではないのでLaravel側では設定とかはない。
一応Symfony側で対応策はあるってことで問題ない。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away