我正在开发一个非常小且简单的应用程序,它有一个返回
png
响应的路由,并且在调用 png URL 时还在数据库中创建一条新记录。
我不知道为什么我会看到这种奇怪的行为(检查跟踪)。
跟踪:注释掉代码时
->header('Content-Type', 'image/png')
它只按预期插入一行,但 png 以二进制数据形式返回,这在删除它时也是预期的。
问题: 通过一个 url 调用,它会立即在表中插入两行。
预期行为: 通过一个 url 调用,它应该只在表中插入一行。
控制器:
<?php
namespace App\Http\Controllers;
use App\Models\EmailTrackerHistory;
use Illuminate\Http\Request;
use App\Models\EmailTracker;
class EmailTrackerController extends Controller
{
public function getPixel(Request $request)
{
$trackerId = $request->get('tracker');
$filename = 'ma-logo.png';
$model = EmailTracker::find($trackerId);
if ($model->empty_pixel == true) {
$filename = 'pixel.png';
}
$img = public_path($filename);
$history = new EmailTrackerHistory();
$history->email_tracker_id = $trackerId;
$history->open_time = now(); // Use Laravel's now() to get the current date and time
$history->opener_ip = $request->ip();
$history->opener_user_agent = $request->userAgent();
if ($history->save()) {
$content = file_get_contents($img);
return response($content)
->header('Content-Type', 'image/png')
->header('Content-Disposition', 'inline; filename="' . $filename . '"')
->header('Content-Transfer-Encoding', 'binary')
->header('Expires', '0')
->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
->header('Pragma', 'public')
->header('Content-Length', strlen($content));
}
abort(500); // If save fails, return a server error response
}
}
型号(默认):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class EmailTrackerHistory extends Model
{
use HasFactory;
}
路由器:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmailTrackerController;
Route::get('/logo.png', [EmailTrackerController::class, 'getPixel'])->name('getPixel');
这可能是由于浏览器获取图标的行为造成的
尝试更改路线中的
logo.png
您也可以这样做,但这不是永久的解决方案
$Entry = EmailTrackerHistory::where('email_tracker_id', $trackerId)
->where('open_time', '>', now()->subMinutes(1))
->first();
if (!$existingEntry) {
$history = new etc...
}