如何在Symfony2控制器中获取用户IP地址?

时间:2012-01-27 06:31:58

标签: symfony ip-address

我需要在表单提交后在数据库中存储评论用户的IP地址。

是否有任何symfony2函数可以获取IP?或者以其他方式获得IP?

5 个答案:

答案 0 :(得分:142)

您可以使用请求服务获取客户端IP:

$this->container->get('request')->getClientIp();

答案 1 :(得分:45)

在Symfony 之前2.3 $this->container->get('request')->getClientIp()仅在主请求控制器内部工作。在子请求控制器中,这始终返回127.0.0.1。如果您的项目使用Symfony 2.2的子请求,则防弹解决方案是创建kernel.request侦听器并从其中保存主请求中的IP。

在Symfony 2.3 中,这是固定的,因此对于内部子请求,真实IP被推送到代理列表,请参阅https://github.com/symfony/symfony/commit/2f3b33a630727cbc9cf21262817240a72a8dae0c 因此,您需要将127.0.0.1添加到trusted_proxies配置参数以从Symfony 2.3+中的子请求中的Request中获取客户端IP,但出于安全原因,您不应该在共享主机上执行此操作。

此外,如果在Symfony 2.3.20之前使用内置HTTP缓存(127.0.0.1中的trusted_proxies),则AppCache必须明确添加到web/app.php。此缓存尝试看起来像真正的反向代理并修改主请求的某些标头。已修复https://github.com/symfony/symfony/commit/902efb8a84e8f0acf6a63e09afa08e3dcdd80fb9

由于Symfony 2.4 以及 3.x ,访问当前请求的首选方式是使用request_stack服务

$this->container->get('request_stack')->getCurrentRequest()->getClientIp();

或将请求注入控制器,请参阅http://symfony.com/doc/current/book/controller.html#the-request-as-a-controller-argument

public function indexAction(Request $request)
{
    $ip = $request->getClientIp();
}

但是在子请求中使用时排除127.0.0.1的问题仍然适用,但现在您可以尝试使用

明确引用主请求
$this->container->get('request_stack')->getMasterRequest()->getClientIp();

答案 2 :(得分:17)

仅供参考,截至Symfony 2.0 Request::getClientIp $proxy parameterdeprecated。它将在Symfony 2.3中删除

您可以使用

$container->get('request')->server->get("REMOTE_ADDR");

或@meze回答

$container->get('request')->getClientIp();

答案 3 :(得分:7)

对于Symfony 2.6+,请使用以下代码(在您的控制器中:

      $this->container->get('request_stack')->getCurrentRequest()->getClientIp();

答案 4 :(得分:1)

还有另一种将当前客户端IP注入任何服务或方法调用的方法:

acme.currentIP:
    class: some\service\className
    arguments:
        - "@=service('request_stack').getCurrentRequest().getClientIp()"
相关问题