Search code examples
phphttpcurlerror-handlingerror-code

How can I reproduce an HTTP 408 timeout error for testing?


As part of the registration for my Drupal 7 site I require the user to enter a valid phone number. Rather than doing only simple validation, I use the Numverify.com API to verify the format of the number on a per country basis and obtain extra information. This is done via a curl request which returns a json object.

The other day the API was unreachable for several hours and due to my lack of foresight, users were unable to register until I circumvented the API request.

To prevent this in the future, I need to be able to properly handle error codes such as 408. Would anybody be able to tell me how I can replicate a timeout request, locally or otherwise, for testing purposes please?


Solution

  • Thanks to @hanshenrik I managed to combine his answer with my own research.

    To get a 408 (or any other response) for testing and handling purposes using curl, I made a PHP file containing http_response_code(408); then from my index.php file, I initiated curl:

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "timeout.php");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($curl);
    $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    
    echo $httpcode;
    

    The important line is the curl_get_info section that will return the http response code from the previous page.I can then handle this code appropriately in my index.php file.

    I don't really know if this is the most efficient way to do this, so if anyone can improve my answer, please feel free.

    In the meantime, I hope this helps someone else out there!