将客户端IP存储在数据库中

时间:2015-08-13 16:19:43

标签: php laravel-5

我想在我的数据库中保存客户端的IP地址。继承我的代码:

// app/Error.php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class Error extends Model {

    protected $fillable = array( 'code', 'user', 'error', 'client', 'call');

    public static function log( $code="unset", $message, $call="unset" ) {

        $kyu = "foobar";

        $uri = "unset";
        $ip = "unset";
        $agent = "unset";
        if ( isset( $_SERVER ) ) {
            if ( array_key_exists( 'REQUEST_URI', $_SERVER ) ) {
                $uri = $_SERVER['REQUEST_URI'];
            }
            if ( array_key_exists( 'REMOTE_ADDR', $_SERVER ) ) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
            if ( array_key_exists( 'HTTP_USER_AGENT', $_SERVER ) ) {
                $agent = $_SERVER['HTTP_USER_AGENT'];
            }
        }
        $callOnUri = $call . ' on: ' . $uri;

        // create database entry
        $user = Error::create([
            'code' => $code,
            'user' => $kyu,
            'ip' => $ip,  // this field is nullable in the migration
            'client' => $agent,
            'error' => $message,
            'call' => $callOnUri // get the call out of the request
        ]);
    }
}

当我调用此代码时,$ client和$ uri被正确保存,但$ ip始终为:NULL。 我在浏览器上检查了以下代码,在同一请求和浏览器上我显示了IP,但在数据库中仍为NULL

public function postRegister()
{
    $validator = $this->registrar->validator(\Input::all());

    $returnVal = $this->registrar->create( \Input::all(  ) );

    if ( is_bool($returnVal) ) {
        // foobar
    } else {
        Error::log( '1234', "Failure in the registration process.", __FUNCTION__ );
        return response()->json(["Error" => $returnVal], "server" => $_SERVER); // dump of the $_SERVER
    }
}

如何正确保存数据库中的客户端IP(REMOTE_ADDR)?

1 个答案:

答案 0 :(得分:1)

您需要在 $ fillable 中添加 ip

protected $fillable = array( 'code', 'user', 'error', 'ip', 'client', 'call');