简体   繁体   English

PHP IP地址在循环中被截断

[英]PHP IP address truncated in loop

I have a MySQL table that contains IP addresses: Table IP addresses 我有一个包含IP地址的MySQL表: 表IP地址

(IP,Bloccato,DataCreazione,IDOperatoreCreazione,DataModifica,IDOperatoreModifica) When I loop the addresses in PHP, they'll be truncate: 当我在PHP中循环地址时,它们将被截断:

string(3) "192"

string(3) "192"

string(3) "192"

string(2) "80"

My code: 我的代码:

public function getListaIndirizzi(Request $request) {

    // Paginazione
    if (!$request) {
        $validator = Validator::make($request->all(), [
                    "indirizzo1" => "ip",
                    "indirizzo2" => "ip"
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withInput()->withErrors($validator);
        }

        $indirizzi = IP::whereBetween("IP", [$request->get("indirizzo1"), $request->get("indirizzo2")])->paginate(10);
    } else {
        $indirizzi = IP::paginate(10);
    }

    for($i =0; $i < count($indirizzi); $i++) {
        LogController::debug((string)($indirizzi[$i]["IP"]));
    }
    die;

    return view("lista_indirizzi", ["indirizzi" => $indirizzi]);
}

I use Laravel framework 我使用Laravel框架

That's my Model, how can I specify that IP field is string not integer? 这是我的模型,如何指定IP字段是字符串而不是整数?

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Ip extends Model {

    //
    protected $table = "ip";

    protected $primaryKey = "IP";
    public $timestamps = false;

    protected $fillable = [
        "IP", "Bloccato"
    ];

    protected $hidden = [
        'DataCreazione', 'IDOperatoreCreazione', 'DataModifica', 'IDOperatoreModifica'
    ];

}

I resolve my problem with this code on my Model: 我在我的模型上使用此代码解决了我的问题:

public function getIPAttribute($value) {
        return (string) $value;
}

I think the source of your issue is somewhere in the model. 我认为你的问题的根源在于模型中的某个地方。

It looks quite like the type of the field in the model is integer, not string. 它看起来很像模型中字段的类型是整数,而不是字符串。 So Laravel (or its ORM) will convert the string to an integer right after fetching from the database and before you work with it. 因此,Laravel(或其ORM)将在从数据库中获取之后以及使用它之前将字符串转换为整数。

PoC: 的PoC:

<?php
$ip = "192.168.1.1";
echo (int)$ip; // prints "192"

Even when you do debug: 即使你做调试:

LogController::debug((string)($indirizzi[$i]["IP"]));

Evaluates to (string)(192) because $indirizzi[$i]["IP"] already is integer "192". 求值为(string)(192)因为$indirizzi[$i]["IP"]已经是整数“192”。

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

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