<?php
/**
* Loads cookies for routine automation with a timeout.
*
* @param string $url The URL to load cookies from.
* @param int $timeout Timeout in seconds.
* @return array|false An associative array of cookies, or false on failure.
*/
function loadCookiesWithTimeout(string $url, int $timeout): array|false
{
$cookies = [];
$socket = @fsockopen($url, 0, $errno, $errstr, $timeout);
if ($socket === false) {
error_log("Failed to connect to $url: $errstr ($errno)");
return false;
}
// Send the HTTP request to get cookies
$request = "GET $url HTTP/1.1\r\n";
$request .= "Host: $url\r\n";
$request .= "Connection: close\r\n";
$request .= "\r\n";
fwrite($socket, $request);
// Read the response, looking for the Set-Cookie header
$response = '';
while (!feof($socket)) {
$response .= fread($socket, 4096);
}
fclose($socket);
// Extract cookies from the response
if ($response) {
preg_match_all('/Set-Cookie:\s*(.+)\r\n/', $response, $matches);
if (is_array($matches[1])) {
foreach ($matches[1] as $cookie) {
preg_match('/^Set-Cookie:\s*(.*?)=(.+)/', $cookie, $cookie_parts);
if (isset($cookie_parts[1]) && isset($cookie_parts[2])) {
$name = trim($cookie_parts[1]);
$value = trim($cookie_parts[2]);
$cookies[$name] = $value;
}
}
}
}
return $cookies;
}
// Example usage:
// $cookies = loadCookiesWithTimeout('https://example.com', 10);
// if ($cookies !== false) {
// print_r($cookies);
// } else {
// echo "Failed to load cookies.\n";
// }
?>
Add your comment