Advertisement
Guest User

Check HTTP Response

a guest
Nov 8th, 2011
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. <?php
  2. $is_ok = http_response($url); // returns true only if http response code < 400
  3. ?>
  4.  
  5. The second argument is optional, and it allows you to check for a specific response code
  6.  
  7. <?php
  8. http_response($url,'400'); // returns true if http status is 400
  9. ?>
  10.  
  11. The third allows you to specify how long you are willing to wait for a response.
  12.  
  13. <?php
  14. http_response($url,'200',3); // returns true if the response takes less than 3 seconds and the response code is 200
  15. ?>
  16.  
  17. <?php
  18. function http_response($url, $status = null, $wait = 3)
  19. {
  20. $time = microtime(true);
  21. $expire = $time + $wait;
  22.  
  23. // we fork the process so we don't have to wait for a timeout
  24. $pid = pcntl_fork();
  25. if ($pid == -1) {
  26. die('could not fork');
  27. } else if ($pid) {
  28. // we are the parent
  29. $ch = curl_init();
  30. curl_setopt($ch, CURLOPT_URL, $url);
  31. curl_setopt($ch, CURLOPT_HEADER, TRUE);
  32. curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
  33. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  34. $head = curl_exec($ch);
  35. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  36. curl_close($ch);
  37.  
  38. if(!$head)
  39. {
  40. return FALSE;
  41. }
  42.  
  43. if($status === null)
  44. {
  45. if($httpCode < 400)
  46. {
  47. return TRUE;
  48. }
  49. else
  50. {
  51. return FALSE;
  52. }
  53. }
  54. elseif($status == $httpCode)
  55. {
  56. return TRUE;
  57. }
  58.  
  59. return FALSE;
  60. pcntl_wait($status); //Protect against Zombie children
  61. } else {
  62. // we are the child
  63. while(microtime(true) < $expire)
  64. {
  65. sleep(0.5);
  66. }
  67. return FALSE;
  68. }
  69. }
  70. ?>
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement