简体   繁体   English

从表单中获取ip地址

[英]Get the ip address from the form

I have a form to add a comment, everything works fine, except for getting the ip who sent the comment我有一个添加评论的表单,一切正常,除了获取发送评论的 ip

Here is my controller这是我的控制器

public function sendComment(Request $request)
    {
        $articleComment = new ArticleComment;

        $articleComment->name = $request->get('name');
        $articleComment->email = $request->get('email');
        $articleComment->text = $request->get('text');
        $article = Article::find($request->get('article_id'));
        $articleComment->user_ip = $request->ip();
        $article->article_comments()->save($articleComment);

        return back();
    }

To get ip, I use $request->ip() but in the end this value comes to my field "user_ip": "::1"为了获得 ip,我使用$request->ip()但最终这个值来到我的字段"user_ip": "::1"

Maybe this is because I am testing everything on a local server, or what is the problem?也许这是因为我正在本地服务器上测试所有内容,或者有什么问题?

Your code is correct if you want to store the IP address from the Request object.如果您想存储来自请求对象的 IP 地址,您的代码是正确的。

You are getting ::1 as this the IPv6 address for your local machine.你得到::1作为本地机器的 IPv6 地址。 The request is coming from your own computer to the laravel app on your own computer therefore the IP is reported a localhost.请求来自您自己的计算机到您自己计算机上的 laravel 应用程序,因此 IP 被报告为本地主机。

If you were running the Laravel app from the internet and sending the request that way, your own public facing IP would be stored properly with your existing code.如果您从 Internet 运行 Laravel 应用程序并以这种方式发送请求,您自己的面向公众的 IP 将与您现有的代码一起正确存储。 This could be stored in IPv4 or IPv6 format depending on what your internet service provider is using.这可以以 IPv4 或 IPv6 格式存储,具体取决于您的 Internet 服务提供商使用的内容。

It is suggested that to support storing both IPv6 (new style) IP addresses and IPv4 (old style) your database field should have a length of 45 characters.建议支持存储 IPv6(新式)IP 地址和 IPv4(旧式),您的数据库字段的长度应为 45 个字符。

first check your Illuminate\\Http\\request.php file in line 296(public function ip() it's most be just return $this->getClientIp(); anything else is false, if is trye and didnot work, you have tow other ways to get the request ip:首先在第296(public function ip()行检查您的Illuminate\\Http\\request.php文件296(public function ip()它最重要的是 return $this->getClientIp();其他任何东西都是假的,如果是 trye 并且没有用,你有其他方法获取请求ip:

1: 1:

public function index(Request $request){
        return $request->getClientIp();
    }

2: 2:

public function index(Request $request){
        return $request->server->get('REMOTE_ADDR');
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM