1. <?php
  2. /**
  3. * Loads cookies for routine automation with a timeout.
  4. *
  5. * @param string $url The URL to load cookies from.
  6. * @param int $timeout Timeout in seconds.
  7. * @return array|false An associative array of cookies, or false on failure.
  8. */
  9. function loadCookiesWithTimeout(string $url, int $timeout): array|false
  10. {
  11. $cookies = [];
  12. $socket = @fsockopen($url, 0, $errno, $errstr, $timeout);
  13. if ($socket === false) {
  14. error_log("Failed to connect to $url: $errstr ($errno)");
  15. return false;
  16. }
  17. // Send the HTTP request to get cookies
  18. $request = "GET $url HTTP/1.1\r\n";
  19. $request .= "Host: $url\r\n";
  20. $request .= "Connection: close\r\n";
  21. $request .= "\r\n";
  22. fwrite($socket, $request);
  23. // Read the response, looking for the Set-Cookie header
  24. $response = '';
  25. while (!feof($socket)) {
  26. $response .= fread($socket, 4096);
  27. }
  28. fclose($socket);
  29. // Extract cookies from the response
  30. if ($response) {
  31. preg_match_all('/Set-Cookie:\s*(.+)\r\n/', $response, $matches);
  32. if (is_array($matches[1])) {
  33. foreach ($matches[1] as $cookie) {
  34. preg_match('/^Set-Cookie:\s*(.*?)=(.+)/', $cookie, $cookie_parts);
  35. if (isset($cookie_parts[1]) && isset($cookie_parts[2])) {
  36. $name = trim($cookie_parts[1]);
  37. $value = trim($cookie_parts[2]);
  38. $cookies[$name] = $value;
  39. }
  40. }
  41. }
  42. }
  43. return $cookies;
  44. }
  45. // Example usage:
  46. // $cookies = loadCookiesWithTimeout('https://example.com', 10);
  47. // if ($cookies !== false) {
  48. // print_r($cookies);
  49. // } else {
  50. // echo "Failed to load cookies.\n";
  51. // }
  52. ?>

Add your comment