我想在我的数据库中保存客户端的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)正确保存在数据库中?
需要在$fillable中添加ip。
protected $fillable = array( 'code', 'user', 'error', 'ip', 'client', 'call');