简体   繁体   中英

Jquery >> PHP >> cURL and browser refresh

I have a problem with one website i wrote a few weeks ago. my website communicates with another website_2 via API hosted on website_2

the curl operation is requested via Query POST to a PHP file. if for some reason the operation took a longer time (which i can't determine the reason for) and the user hits refresh.. the command sent to the API is done yet my server doesn't get any result so can't log or do anything with that result.. is there a way to preserve the integrity of such transaction? below is my code and i still get FAILED no matter what the result was on website_2

 function doCommit($url_)
 {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url_);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Opera/9.23 (Windows NT 5.1; U; en)');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_TIMEOUT,5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
    $commit = curl_exec($ch);
    curl_close($ch);
    if(!curl_exec($ch))
    {
    $ERROR="<Transaction>
          <Result>Failed</Result>
          <Reason>Operation Timed Out</Reason>
        </Transaction>";
    $oXML = new SimpleXMLElement($ERROR);
    return $oXML;
    }
    else{
    $oXML = new SimpleXMLElement($commit);
    return $oXML;
    }
    // return $oXML->Reason;
}

You can use curl parameters to solve your problem setting a "request timeout":

CURLOPT_TIMEOUT - Sets The number of seconds to wait before a curl individual function timeouts.

CURLOPT_CONNECTTIMEOUT - Sets the maximum time before curl connection timeouts.

...and then you could return a text if curl_exec fails:

if(curl_exec($curl) === false)
{
    echo 'ERROR: ' . curl_error($curl);
}

Solved it by the following code

function doCommit($url_)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url_);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Opera/9.23 (Windows NT 5.1; U; en)');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_TIMEOUT,2);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,2);
    $commit = curl_exec($ch);
    curl_close($ch);
    if(curl_errno($ch) == 0)
    {
    $oXML = new SimpleXMLElement($commit);
    return $oXML;
    }
    else{
    $ERROR="<Transaction>
          <Result>Failed</Result>
          <Reason>Operation Timed Out</Reason>
        </Transaction>";
    $oXML = new SimpleXMLElement($ERROR);
    return $oXML;
    }
    // return $oXML->Reason;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM