Hot Koehls
  • Email
  • Feedburner
  • Linkedin
  • Twitter
  • Home
  • About
  • Archives
  • Contact
  • Software
    • S3imple Backup
    • Twitter Feed Archiver
    • FileTime
    • Flickr API Demo
Search
Home» For techies » Get HTTP status code of cURL call in PHP

Get HTTP status code of cURL call in PHP

Posted by Frank - September 10, 2009 - For techies
7

With all the fancy cURL-based API’s out there these days (Facebook and Twitter immediately come to mind), using cURL to directly access and manipulate data is becoming quite common. However like all programming, there’s always the chance for an error to occur, and thus these calls must be immediately followed by error checks to ensure everything went as planned.

Most decent API’s will return their own custom errors when an internal problem occurs, but that does not account for issues dealing directly with the connection. So before your application goes looking for API-based errors, they should first check the returned HTTP status code to ensure the connection itself went well.

For example, Twitter-specific error messages are always paired with a “400 Bad Request” status. The message is of course helpful, but it’s far easier (as you’ll see) to find the status code from the response headers and then code for the exceptions as necessary, using the error text for logging and future debugging.

Anyway, the HTTP status code, also called the “response code,” is a number that corresponds with the result of an HTTP request. Your browser gets these codes every time you access a webpage, and cURL calls are no different. The following codes are the most common (excerpted from the Wikipedia entry on the subject)…

  • 200 OK
    Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action.
  • 301 Moved Permanently
    This and all future requests should be directed to the given URI.
  • 400 Bad Request
    The request contains bad syntax or cannot be fulfilled.
  • 401 Unauthorized
    Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.
  • 403 Forbidden
    The request was a legal request, but the server is refusing to respond to it. Unlike a 401 Unauthorized response, authenticating will make no difference.
  • 404 Not Found
    The requested resource could not be found but may be available again in the future. Subsequent requests by the client are permissible.
  • 500 Internal Server Error
    A generic error message, given when no more specific message is suitable.

So now that we know what we’re looking for, how do we go about actually getting them? Fortunately, PHP’s cURL support makes performing these checks pretty easy, they just don’t make the process plain. We need a function called curl_getinfo(). It returns an array full of useful information, but we only need to know the status number. Fortunately, we can set the arguments so that we only get this number back, like so…

// must set $url first. Duh...
$http = curl_init($url);
// do your curl thing here
$result = curl_exec($http);
$http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);
curl_close($http);
echo $http_status;

curl_getinfo() returns data for the last curl request, so you must execute the cURL call first, then call curl_getinfo(). The key is the second argument; the predefined constant CURLINFO_HTTP_CODE tells the function to forego all the extra data, and just return the HTTP code as a string.

Echoing out the variable $http_status gets us the status code number, typically one of those outlined above.

browsers, php, software development, Twitter

7 comments on “Get HTTP status code of cURL call in PHP”

  1. Jenn says:
    March 16, 2010 at 3:21 pm

    Great post, Thank.
    If you need you can use this: http tool to check and verify http status code when you sending different HTTP request to the URL.

  2. Mark says:
    May 25, 2011 at 4:07 pm

    Thank you for the post. Exactly what I needed.

  3. Steffan says:
    July 10, 2011 at 8:18 am

    Exactly what I needed. Thanks.

  4. Sel says:
    June 27, 2012 at 9:18 am

    It would be good to close curl connection (curl_close($http)) after using it.
    It my case the url i was pointing to was redirecting me and it’s content was displayed.
    So add the curl_close($http) at the end of the script to fix in advance possible problems.

  5. Frank says:
    June 27, 2012 at 10:56 pm

    Sel, it’s only a sample snippet, and wasn’t intended to be copy/pasted directly into a code base. The lack of detail around the use of cURL functions means that some prior experience is required.

    That being said, I’ve added the close for the sake of closing the loop.

  6. Tarei says:
    January 8, 2013 at 4:49 pm

    This is also a helpful way to get the error code information without CURL : http://stackoverflow.com/questions/9724924/php-get-http-header-response-code-without-curl

  7. OTHER FUNCTION says:
    March 26, 2013 at 8:30 am

    function get_link_status($url, $timeout = 10)
    {
    $ch = curl_init();
    // set cURL options
    $opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
    CURLOPT_URL => $url, // set URL
    CURLOPT_NOBODY => true, // do a HEAD request only
    CURLOPT_TIMEOUT => $timeout); // set timeout
    curl_setopt_array($ch, $opts);
    curl_exec($ch); // do it!
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); // find HTTP status
    curl_close($ch); // close handle
    echo $status; //or return $status;
    }

    get_link_status(‘http://site.com’);

Cancel Reply

Categories

  • For entrepreneurs
  • For everyone
  • For techies

Latest Tweets

  • The PA Report - LucasArts' eulogy reminds us of the inhuman cost of game development http://t.co/vVjHkmr9YD
    April 9, 2013 - 2:46 pm
  • Pictures from a developer's life http://t.co/s75fBPTu4v
    April 5, 2013 - 11:44 am
  • Chuck+Norris http://t.co/awBqZ8gncS
    March 7, 2013 - 10:46 pm
  • Google Hacks http://t.co/ZIU2CHcoem
    March 3, 2013 - 1:08 am

Recent Comments

  • ChazzMatt on Write code like they do in Hollywood
  • ChazzMatt on Turn off AVG e-mail signature
  • Rohitash on Automating SSH or SFTP in scripts
  • kgiFozzkjk on MySQL founder Michael Widenius concerned about sale to Oracle
  • purusjap on Jeff Atwood still wrong about PHP

Recent Posts

  • Display line numbers in WebSVN file detail view
  • It’s dangerous to go alone
  • Create Self-Signed Wildcard SSL Certificate
  • What comes after the yottabyte?
  • Write code like they do in Hollywood
(c) 2012 Frank Koehl. All Rights Reserved.
  • Contact Us
  • Sitemap