【问题标题】:Wait for curl to finish before continuing?等待 curl 完成后再继续?
【发布时间】:2017-06-14 07:15:07
【问题描述】:

我正在使用脚本通过 curl 将日期发送到网上商店。 在同一个脚本中,执行此脚本时会发送一封邮件。 邮件通常在 curl 完成之前发送,因此缺少关键参数。 如何更改脚本以便在 curl 执行后发送邮件?

// Some more curl code here

        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

        // execute post
        $result = curl_exec($ch);

        $data = json_decode($result);

        // close connection
        curl_close($ch);

        // send mail
        require('assets/phpmailer/class.phpmailer.php');

        $mail = new phpmailer();
        $mail->IsHTML(true);

// Some more mail code here

【问题讨论】:

  • 一种选择可能是将 curl 代码包装在一个函数中并从中返回 $data 。然后你可以在发送邮件之前检查 $data 是否存在。
  • “邮件通常在 curl 完成之前发送” -- 它不会发生。 curl_exec() 在请求完成时(收到响应时)返回。也许请求没有成功完成(因为您设置的超时)。您应该检查curl_exec() 返回的值并决定下一步该做什么。
  • 你可以得到这样的 CURL 响应:$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if($httpcode==200) { }.. 在这个 if() {} 里面,你有你的邮件。
  • 我认为您需要添加此 cURL 选项:CURLOPT_RETURNTRANSFER。这会将传输作为 curl_exec() 的返回值的字符串返回,而不是直接输出。

标签: php curl


【解决方案1】:

你应该检查一下 curl 的响应

if (curl_errno($ch)) {
    // this would be your first hint that something went wrong
    die('Couldn\'t send request: ' . curl_error($ch));
} else {
    // check the HTTP status code of the request
    $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($resultStatus != 200) {
        die('Request failed: HTTP status code: ' . $resultStatus);
    }
    else{
        //send the mail
    }
}

【讨论】:

    【解决方案2】:

    尝试返回传输参数为true等待响应:

        // Some more curl code here
    
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        // execute post
        $result = curl_exec($ch);
    
        $data = json_decode($result);
    
        // close connection
        curl_close($ch);
    
        // send mail
        require('assets/phpmailer/class.phpmailer.php');
    
        $mail = new phpmailer();
        $mail->IsHTML(true);
    
        // Some more mail code here
    

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 2019-11-01
      • 2021-05-06
      • 2021-05-21
      • 2015-10-03
      • 2013-11-25
      • 2014-02-03
      • 1970-01-01
      相关资源
      最近更新 更多