在获取错误时重复CURL代码并登录php

时间:2017-05-25 01:15:55

标签: php curl while-loop

当curl_error为true时,我希望将此代码保持在循环中(两次/三次),如果仍然失败,请在错误日志中输入。

$ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

$response = curl_exec($ch);

/* if there is an error show error */
if (curl_error($ch) && curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
    $success = false;
    return view('frontend.user.rss', compact('project_detail_all','active_project_detail','rss_detail','success'));
}
curl_close($ch);

请提出你的建议,谢谢。

1 个答案:

答案 0 :(得分:2)

我没有做太多curl但这似乎是一种合乎逻辑的方式......

$i=0;
do{
    $ch = curl_init($api_url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

    $response = curl_exec($ch);

    /* if there is an error show error */
    if(curl_error($ch) && curl_getinfo($ch, CURLINFO_HTTP_CODE)!=200){
        $success=false;
    }else{
        $success=true;
        break;
    }
    curl_close($ch);
    ++$i;
}while($i<3);

if($success){
    // return what you want / $response
}else{
    // log the failure, return what you want
    // return view('frontend.user.rss', compact('project_detail_all','active_project_detail','rss_detail','success'));
}