PHP, Curl. Файл куки создается, но не наполняется
Есть код:
function sendCurl($url, $post = false, $referer = "") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_COOKIESESSION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__ . "/cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, __DIR__ . "/cookie.txt");
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36");
if ($post) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: */*', 'Connection: Keep-Alive', 'Origin: origin', 'Referer: '.$referer));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$data = curl_exec ($ch);
if (curl_error($ch))
return curl_error($ch);
if (curl_getinfo($ch)["http_code"] == 200)
return $data;
}
При попытке отправить запрос на некоторые (не на все) сайты файл cookie.txt не наполняется данными. Почему так может быть? Что я делаю не так?
cookie.txt:
# Netscape HTTP Cookie File
# https://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
Суть задачи - получить куки с сайта по аналогии с тем как их получает пользователь при переходе на сайт.
Ответы (1 шт):
Автор решения: Jean-Claude
→ Ссылка
Возможно потому куки в файл не записываются, потому что те некоторые сайты вовсе и не дают их тебе. Другая причина - у процесса не хватает прав на запись в файл.
Return в функции должен быть всегда, в твоем случае ретурны в двух условиях, но ведь они оба могут не выполниться, например, если вернется код 201 или 404.
Этот код работает:
function sendCurl($url, $post = false, $referer = "") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__ . "/cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, __DIR__ . "/cookie.txt");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($post) {
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
if ($referer) {
curl_setopt($ch, CURLOPT_REFERER, $referer);
}
$response = curl_exec($ch);
if (curl_error($ch)) {
return curl_error($ch);
}
//if (curl_getinfo($ch)["http_code"] == 200)
return $response;
}
sendCurl('https://php.net/', false, 'http://google.ru');
//полученные куки
//# Netscape HTTP Cookie File
//# https://curl.haxx.se/docs/http-cookies.html
//# This file was generated by libcurl! Edit at your own risk.
//
//.php.net TRUE / FALSE 1665218717 LAST_NEWS 1633682715
//.php.net TRUE / FALSE 1634287517 COUNTRY NA%2C5.153.191.181
echo sendCurl('https://httpbin.org/post', true);
//получено
//{ "args": {}, "data": "1", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Content-Length": "1", "Content-Type": "application/json", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36", "X-Amzn-Trace-Id": "Root=1-616005ef-60332e754318df001e64e069" }, "json": 1, "origin": "5.153.191.181", "url": "https://httpbin.org/post" }