4 回答

TA貢獻1993條經驗 獲得超6個贊
嘗試使用以獲取ip;Request::ip()
$ip = Request::ip();
對于拉拉維爾 5.4 +:
$ip = $request->ip();
// or
$ip = request()->ip();
我認為你可以使用中間件和redis來計算這個計數,這將減輕數據庫的壓力。

TA貢獻1874條經驗 獲得超12個贊
在這種情況下,一個好的解決方案是創建一個跟蹤所有用戶的。我們可以將任何類型的業務邏輯放在 .middlewaremiddleware
<?php
namespace App\Http\Middleware;
use Closure;
class TrackUser
{
public function handle($request, Closure $next)
{
/* You can store your user data with model, db or whatever...
Here I use a repository that contains all my model queries. */
$repository = resolve('App\Repositories\TrackUserRepository');
$repository->addUser([
'ip' => request()->ip(),
'date' => now(),
]);
return $next($request);
}
}
然后添加到 :middleware
App\Kernel.php
如果您希望它是在每個請求上運行的全局中間件,請將其添加到。
$middleware
如果您希望它僅在每個 -route 上運行,請將其添加到。
$middlewareGroups
web
如果要指定何時應用中間件,請將其添加到。
$routeMiddleware
routes/web.php
您還應該考慮在“ ”-語句中移動任何邏輯,這樣可以最大程度地降低用戶因“跟蹤”代碼引起的任何錯誤而停止的風險。middleware
try
catch
try {
$repository = resolve('App\Repositories\TrackUserRepository');
$repository->addUser([
'ip' => request()->ip(),
'date' => now(),
]);
} catch (\Exception $e) {
// Do nothing or maybe log error
}
return $next($request);

TA貢獻1784條經驗 獲得超2個贊
最好使用組合并有更準確的結果,許多用戶可能具有相同的IP,但通常具有不同的用戶代理:user_agentip
request()->userAgent();
request()->ip();
或者,如果您使用的是中間件(不是),Laravel 會為每個客戶端啟動一個會話。您可以更改會話驅動程序,并使用 代替默認的 .webapidatabasefile
通過這種方式,Laravel將在表格中為每個客戶存儲一條記錄,其中包含您需要的所有信息,甚至更多:sessions
Schema::create('sessions', function ($table) {
$table->string('id')->unique();
$table->unsignedInteger('user_id')->nullable();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->text('payload');
$table->integer('last_activity');
});
如您所見,有 、 和 。將用于來賓用戶,并且對經過身份驗證的用戶具有價值。ip_addressuser_agentlast_activityuser_idnull
請參閱 Laravel 文檔以將會話驅動程序配置為使用 。database

TA貢獻1843條經驗 獲得超7個贊
您將如何獲得IP地址。
為 IP 地址及其訪問時間戳創建一個新表。
檢查IP是否不存在或(1天),將IP的時間戳編輯為time()(表示現在)并增加您的視圖,其他人什么都不做!time()-saved_timestamp > 60*60*24
此外,您可以通過以下方式獲得IP$_SERVER['REMOTE_ADDR']
這里提到了獲取IP的更多方法。https://stackoverflow.com/a/54325153/2667307
已查看返回127.0.0.1
請嘗試:-
request()->server('SERVER_ADDR');
或者您可以使用
$_SERVER['SERVER_ADDR'];
或
$_SERVER['REMOTE_ADDR']
- 4 回答
- 0 關注
- 207 瀏覽
添加回答
舉報