Sửa lỗi CURL dùng Cookie không có tác dụng

Hiện tượng gặp phải là thiết lập CURLOPT_COOKIEFILE, CURLOPT_COOKIEJAR xong rồi nhưng không lấy được cookie nếu gọi curl nhiều lần trong một phiên. Vấn đề này bị trên PHP 8.2, phiên bản php thấp hơn không thấy bị

Ví dụ code bên dưới

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
....

curl_close($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
....

curl_close($ch);

Tại lệnh thứ 2 không có cookie truyền đi từ lệnh 1. Xử lý bằng cách unset biến $ch sau khi close. Ví dụ

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
....

curl_close($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
....

curl_close($ch);
unset($ch);

Đây là giải pháp mình xử lý được, nếu bạn có cách khác hãy thảo luận bên dưới

Bình luận (0)