Wednesday, April 28, 2010

How to get HTTP response code of HTTP request in PHP

Here the function to get the HTTP response code of a HTTP request. This function can easily be used to detect what is the status of a page that you are requesting (such as 404 - Not Found, 301 - Permenently Moved). Here is a complete reference for HTTP response codes.

  1. function getResponseCode($url) {
  2.     $ch= curl_init();
  3.  
  4.     curl_setopt($ch, CURLOPT_URL, $url);
  5.     curl_setopt($ch, CURLOPT_HEADER, 1);
  6.     curl_setopt($ch, CURLOPT_NOBODY, 1);
  7.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  8.     curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  9.  
  10.     curl_exec($ch);
  11.  
  12.     $details = curl_getinfo($ch);
  13.  
  14.     curl_close($ch);
  15.     return $details['http_code'];
  16. }

1 comment:

All rights reserved for all the posts. Please inform us on idhanu@gmail.com if you are publishing post in this without modifying. Code snippets are free to use, if not explicitly mentioned.