PHP uses curl to upload files in batches (interface request)


    function apiUpload()
    {
    
    
        $file      = storage_path('');  //文件夹绝对路径

        $handler   = opendir($file);//当前目录中的文件夹下的文件夹
        $name_list = [];
        while (($filename = readdir($handler)) !== false) {
    
    
            if ($filename != "." && $filename != ".." && $filename != ".svn") {
    
    
                $name_list[] = $filename;
            }
        }
        if (empty($name_list)) {
    
    
            exit('目录为空');
        }

       $url = '';  //请求api地址
       $i = 0;
        foreach ($name_list as $name) {
    
    
            $full_file = $file . '/' . $name;
            $post_data = [
                'label' => new \CURLFile($full_file),  //必须是绝对路径
            ];
            dump($full_file);
            $rt = $this->curl_post($url, $post_data);
            dump(json_decode($rt));
            $i ++;
            if( $i % 10 === 0){
    
    
                sleep(1);
            }
        }
    }

    function curl_post($url,$post_data)
    {
    
    
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        return  $output;
    }

Guess you like

Origin blog.csdn.net/qq_39004843/article/details/113441641