curl 停止脚本执行

发布于 2024-08-19 20:37:19 字数 1434 浏览 8 评论 0原文

我的脚本使用curl通过smugsmug网站上传图像.net/display/API/show+1.2.2?method=smugmug.images.upload" rel="nofollow noreferrer">smugsmug api。 我循环浏览一个文件夹并上传其中的每个图像。但在上传 3-4 次后,curl_exec 将失败,停止一切并阻止其他图像上传。

$upload_array = array(
    "method" => "smugmug.images.upload",
    "SessionID" => $session_id,
    "AlbumID" => $alb_id,
    "FileName" => zerofill($n, 3) . ".jpg",
    "Data" => base64_encode($data),
    "ByteCount" => strlen($data),
    "MD5Sum" => $data_md5);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $upload_array);
curl_setopt(
    $ch, CURLOPT_URL, 
    "https://upload.smugmug.com/services/api/rest/1.2.2/");
$upload_result = curl_exec($ch); //fails here
curl_close($ch);

更新: 所以我添加了登录到我的脚本中。当它失败时,日志记录会在 fwrite($fh, "begin curl\n"); 之后

fwrite($fh, "begin curl\n");
$upload_result = curl_exec($ch);
fwrite($fh, "curl executed\n");
fwrite($fh, "curl info: ".print_r(curl_getinfo($ch,true))."\n");
fwrite($fh, "xml dump: $upload_result \n");
fwrite($fh, "curl error: ".curl_error($ch)."\n");

停止

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60*60);

my script uses curl to upload images to smugsmug site via smugsmug api.
i loop through a folder and upload every image in there. but after 3-4 uploads, curl_exec would fail, stopped everything and prevent other images from uploading.

$upload_array = array(
    "method" => "smugmug.images.upload",
    "SessionID" => $session_id,
    "AlbumID" => $alb_id,
    "FileName" => zerofill($n, 3) . ".jpg",
    "Data" => base64_encode($data),
    "ByteCount" => strlen($data),
    "MD5Sum" => $data_md5);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $upload_array);
curl_setopt(
    $ch, CURLOPT_URL, 
    "https://upload.smugmug.com/services/api/rest/1.2.2/");
$upload_result = curl_exec($ch); //fails here
curl_close($ch);

updated:
so i added logging into my script. when it does fail, the logging stops after fwrite($fh, "begin curl\n");

fwrite($fh, "begin curl\n");
$upload_result = curl_exec($ch);
fwrite($fh, "curl executed\n");
fwrite($fh, "curl info: ".print_r(curl_getinfo($ch,true))."\n");
fwrite($fh, "xml dump: $upload_result \n");
fwrite($fh, "curl error: ".curl_error($ch)."\n");

i also

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60*60);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

百变从容 2024-08-26 20:37:19

不确定问题是什么...失败时的响应是什么?系统和apache日志说什么?

现在,如果我是你,我不会在循环中使用 curl_init()curl_close() 。相反,我会在循环之前初始化,并在循环之后关闭 - 然后在循环内部,我将使用curl_set_opt来设置url和不同的参数,然后调用curl_exec() 。甚至可能是所有这些句柄超出了某种系统限制或其他原因。如果您需要/想要使用多个连接,您可以使用curl_multi或编写一些管理函数/类来管理多个句柄。

Not sure what the issue is... What is in the response when it fails? What do the system and apache logs say?

Now if i were you i wouldnt use curl_init() and curl_close() in the loop. instead i would init before the loop, and close after the loop - then within the loop itsef i would use curl_set_opt to set the url and differing parameters and just call curl_exec(). It may even be its a matter of all these handles exceeding some kind of system limit or something. If you need/want to use multiple connections you could use curl_multi or write some management functions/class to manage multiple handles.

诗化ㄋ丶相逢 2024-08-26 20:37:19

我们可能需要更多信息才能提供帮助,但这听起来可能是超时问题。

打开错误报告或检查错误日志以查看是否出现任何问题。

尝试使用 CURLOPT_TIMEOUT 设置较长的 cURL 超时

同时检查脚本超时是否足够或使用 set_time_limit() 增加

We may need more info before we can help, but it sounds like it could be a timeout issue.

Turn on error reporting or check your error logs to see if anything is being raised.

Try setting a long cURL timeout with CURLOPT_TIMEOUT

Also check that your script timeout is sufficient or increase with set_time_limit()

情话墙 2024-08-26 20:37:19

1- 强制 Curl 告诉您更多有关其功能的信息

curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HEADER, true);

2- 如果您未处于安全模式,请通过将其放在脚本的开头来确保 PHP 显示错误:

<?php
ini_set('display_errors', '1');
error_reporting(E_ALL);

3- 您还可以尝试在以下位置运行脚本CLI 模式。

4-最后,如果您未处于安全模式,您可以尝试使用 exec() 直接运行curl 二进制文件。

<?php

$curl_str = "curl -k -o /my/path/curl_output.log -d 'var1=".$value1."&var2=".$value2."& etc...' https://upload.smugmug.com/services/api/rest/1.2.2/";
$r = exec($curl_str);

1- Force Curl to tell you a bit more about what it does

curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HEADER, true);

2- If you are not in safe mode, make sure PHP displays errors by putting this at the beginning of your script:

<?php
ini_set('display_errors', '1');
error_reporting(E_ALL);

3- You can also try to run your script in CLI mode.

4- Finally, still if you are not in safe mode, you can try to directly run the curl binary using exec().

<?php

$curl_str = "curl -k -o /my/path/curl_output.log -d 'var1=".$value1."&var2=".$value2."& etc...' https://upload.smugmug.com/services/api/rest/1.2.2/";
$r = exec($curl_str);
孤千羽 2024-08-26 20:37:19

当处理多个高延迟请求(例如上传图像)时,CURL 包含“多”(针对多个资源)选项。

看:
http://www.php.net/manual/en/ function.curl-multi-exec.php
以及此处描述的整个“多重”功能库:
http://php.net/manual/en/book.curl.php

有关库的多资源部分的完整示例,请参阅:
http://www .developertutorials.com/blog/php/parallel-web-scraping-in-php-curl-multi-functions-375/

CURL includes the 'multi' (for multiple-resources) options for when one is dealing with multiple high-latency requests (such as uploading images).

See:
http://www.php.net/manual/en/function.curl-multi-exec.php
and the entire library of 'multi' functions described here:
http://php.net/manual/en/book.curl.php

For a complete example of the multiple resource section of the library, see:
http://www.developertutorials.com/blog/php/parallel-web-scraping-in-php-curl-multi-functions-375/

薄情伤 2024-08-26 20:37:19

您可以尝试直接输出 curl_error() 是否有效:

$upload_result = curl_exec($ch); //fails here

$error = curl_error($ch);    
if ($error) echo "CURL Error: $error";

curl_close($ch);

如果不行如果没有帮助,请检查您的 phpinfo(); 以查看错误报告是否已全局关闭(查找 display_errors 设置)。

You could try whether outputting curl_error() directly works:

$upload_result = curl_exec($ch); //fails here

$error = curl_error($ch);    
if ($error) echo "CURL Error: $error";

curl_close($ch);

If that doesn't help, check your phpinfo(); to see whether error reporting is turned off globally (look for the display_errors setting).

思念满溢 2024-08-26 20:37:19

我在下面使用这个 ajax 来调用 ajax.php 文件中的函数

$.ajax({
            url:'ajax.php?action=save_parcel',
            data: new FormData($(this)[0]),
            cache: false,
            contentType: false,
            processData: false,
            method: 'POST',
            type: 'POST',
            success:function(resp){
             if(resp){
             resp = JSON.parse(resp)
        
        if(resp == 1){
            //var nw = window.open('print_pdets.php? 
        ids='+resp.ids,"_blank","height=700,width=900")
            alert_toast('Data successfully saved',"success");
            setTimeout(function(){
              location.href = 'index.php?page=parcel_list';
            },2000)

        }
        }
            }
        })

下面是 ajax.php -> action=save_parcel' 从上面调用
ajax:

<?php
ob_start();
date_default_timezone_set("Africa/Nairobi");

$action = $_GET['action'];
include 'admin_class.php';
$crud = new Action();

if($action == 'save_parcel'){
    $save = $crud->save_parcel();
    if($save)
        echo $save;
}
ob_end_flush();
?>

然后从上面调用 admin.php(save_parcel) 函数:

function save_parcel(){   
extract($_POST);
        
                $login_name=$_SESSION['login_name'];
                $agent_id=$_SESSION['login_id'];
                $data .= ", reference_number='$ref' ";
                $data .= ", created_by='$login_name' ";
                $data .= ", agent_id='$agent_id' ";
                if($save[] = $this->db->query("INSERT INTO parcels set 
                  $data"))
                    $ids[]= $this->db->insert_id;
                $message ="Dear" ." ".$recipient_name.",". "Your parcel reference No:"." ".$ref. " "."has been sent from"." ".Branch_name." "."We will notify you when your parcel arrives in"." ".To_branch.". "."Thank you for using K-Prestige shuttle. You may reach us anytime on 0733xxx/0722XXXX";
                
                
            $url = "http://localhost:8130/api/1/webconnection/1";

            //Initiate cURL.
            $ch = curl_init($url);
            
            //The JSON data.
             $jsonData = array( 
                                    'secret' => '123', 
                                    'message' => $message, 
                                    'recipients' => array(array( 
                                            'type' => 'address', 
                                            'value' => '07358688'
                                    ))
                            );
                    
            //Encode the array into JSON.
            $jsonDataEncoded = json_encode($jsonData);
            

            //Tell cURL that we want to send a POST request.
            curl_setopt($ch, CURLOPT_POST, 1);

            //Attach our encoded JSON string to the POST fields.
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

            //Set the content type to application/json
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: 
            application/json')); 

            //Execute the request
            $result = curl_exec($ch);
              if(curl_errno($ch))
                {
                    echo 'error:' . curl_error($ch);
                }

                curl_close($ch);
}

注释:
上面是发送一条短信,效果很好,但是应用程序
光标保持无限循环旋转而不是转到
location.href = 'index.php?page=parcel_list' 如上所示。

I am using this ajax here below to call a function inside ajax.php file

$.ajax({
            url:'ajax.php?action=save_parcel',
            data: new FormData($(this)[0]),
            cache: false,
            contentType: false,
            processData: false,
            method: 'POST',
            type: 'POST',
            success:function(resp){
             if(resp){
             resp = JSON.parse(resp)
        
        if(resp == 1){
            //var nw = window.open('print_pdets.php? 
        ids='+resp.ids,"_blank","height=700,width=900")
            alert_toast('Data successfully saved',"success");
            setTimeout(function(){
              location.href = 'index.php?page=parcel_list';
            },2000)

        }
        }
            }
        })

Below is the ajax.php -> action=save_parcel' being called from above
ajax:

<?php
ob_start();
date_default_timezone_set("Africa/Nairobi");

$action = $_GET['action'];
include 'admin_class.php';
$crud = new Action();

if($action == 'save_parcel'){
    $save = $crud->save_parcel();
    if($save)
        echo $save;
}
ob_end_flush();
?>

Then from above, calls admin.php(save_parcel)function:

function save_parcel(){   
extract($_POST);
        
                $login_name=$_SESSION['login_name'];
                $agent_id=$_SESSION['login_id'];
                $data .= ", reference_number='$ref' ";
                $data .= ", created_by='$login_name' ";
                $data .= ", agent_id='$agent_id' ";
                if($save[] = $this->db->query("INSERT INTO parcels set 
                  $data"))
                    $ids[]= $this->db->insert_id;
                $message ="Dear" ." ".$recipient_name.",". "Your parcel reference No:"." ".$ref. " "."has been sent from"." ".Branch_name." "."We will notify you when your parcel arrives in"." ".To_branch.". "."Thank you for using K-Prestige shuttle. You may reach us anytime on 0733xxx/0722XXXX";
                
                
            $url = "http://localhost:8130/api/1/webconnection/1";

            //Initiate cURL.
            $ch = curl_init($url);
            
            //The JSON data.
             $jsonData = array( 
                                    'secret' => '123', 
                                    'message' => $message, 
                                    'recipients' => array(array( 
                                            'type' => 'address', 
                                            'value' => '07358688'
                                    ))
                            );
                    
            //Encode the array into JSON.
            $jsonDataEncoded = json_encode($jsonData);
            

            //Tell cURL that we want to send a POST request.
            curl_setopt($ch, CURLOPT_POST, 1);

            //Attach our encoded JSON string to the POST fields.
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

            //Set the content type to application/json
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: 
            application/json')); 

            //Execute the request
            $result = curl_exec($ch);
              if(curl_errno($ch))
                {
                    echo 'error:' . curl_error($ch);
                }

                curl_close($ch);
}

Notes:
Above is sending an sms message which it does fine but the application
cursor keeps rotating in an indefinite loop instead of going to
location.href = 'index.php?page=parcel_list' as indicated above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文