skip to Main Content

This is my php code

<?php

    /* some php code - top */

    /* curl request logic start */

    $ch = curl_init("https://api.abc.com/xyz");
    $response = curl_exec($ch);`
    if (curl_errno($ch))
    {
        $error_msg = curl_error($ch);
    }
    curl_close($ch);

    if (isset($error_msg))
    {
        echo 'Curl error: ' . $error_msg;
    }
    else
    {
        echo $response;
    }

    /* curl request logic end */

    /* some php code - bottom */
?>

My problem is , if the server for "https://api.abc.com/xyz" is shut down/is not reachable, the entire php script execution freezes.

What I want is that even if the api "https://api.abc.com/xyz" is down, the php code indicated by /* some php code - top */ and /* some php code - bottom */ should get executed and the page should not hang/freeze completely.

Any advice would be much appreciated….!

Thank You

I have tried curl error handling, but it does not seem to work.

3

Answers


  1. You can set a timeout to curl connection and reponse request with:

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //connect timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 6); //timeout wait response in seconds
    
    Login or Signup to reply.
  2. You need to set the return value as a string.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    Login or Signup to reply.
  3. <?php
    
    /* some php code - top */
    
    /* curl request logic start */
    
    $ch = curl_init("https://api.abc.com/xyz");
    
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //connect timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 6); //timeout wait response in seconds
    
    
    $response = curl_exec($ch);
    $statuscode=curl_getinfo($ch,CURLINFO_HTTP_CODE);
     
    /* according to status code you can code here for instance not equal to 200 */
    if ( $statuscode != 200 )
    {
        $error_msg = curl_error($ch);
    }
    curl_close($ch);
    
    if (isset($error_msg))
    {
        echo 'Curl error: ' . $error_msg;
    }
    else
    {
        echo $response;
    }
    
    /* curl request logic end */
    
    /* some php code - bottom */
    

    ?>

    Hope this solve your error

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search