2017-05-25 70 views
1

当curl_error为true并且如果仍然失败,请在错误日志中输入时,我想保持此代码循环(两次/三次)。在获取错误和登录时重复CURL代码php

$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); 

请给出您的建议,谢谢。

+0

你想运行此卷曲的2-3倍?你可以使用PHP的循环https://www.w3schools.com/php/php_looping_for.asp –

+0

我知道循环在PHP中,但我的问题是“循环时发生错误,如果仍然失败陷入错误文件” –

回答

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')); 
} 
+0

@wasimbeg什么这样做只要具有'$ success = true'就会打断循环;如果第一次迭代是“$ success = false”,那么它最多循环两次。如果'$ success'在3次尝试后保持为假,它将退出循环,并且您可以记录错误 - 一次。如果这不是你想要的,请澄清问题编辑的评论。 – mickmackusa

+0

谢谢米克,这正是我想要的! –