使用 curl 将 url 文件上传到远程服务器


Uploading url file to remote server using curl

我已经在这个上面呆了 3 天了,但我似乎无法解决它,用户将输入 url,系统会将其上传到远程服务器.. 这就是我到目前为止所做的

$POST_DATA = array(
    'file' => '@'.  'http://images.visitcanberra.com.au/images/canberra_hero_image.jpg',
    'extension' => 'txt',
    'filename' => 'test',
    'directory' => 'uploads/'
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://1234.4321.67.11/upload.php');
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $POST_DATA);
$response = curl_exec($curl);
curl_close ($curl);
好吧,

以这种方式进行。

  1. 首先从用户提供的 url 下载该文件。
  2. 将该图像上传到 http://1234.4321.67.11/upload.php
  3. 并在成功上传到服务器后删除该文件。

这可能有助于您使用cURL 在服务器上上传图像:https://stackoverflow.com/a/15177543/1817160

这可能有助于您了解如何从网址下载图像:通过 HTTP 从远程服务器复制图像

使用以下函数使用 curl 上传远程图像。通过将图像 url 和路径传递到文件夹以保存图像来调用它。

function grab_image($url,$saveto){
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
        $raw=curl_exec($ch);
        curl_close ($ch);
        if(file_exists($saveto)){
            unlink($saveto);
        }
        $fp = fopen($saveto,'x');
        fwrite($fp, $raw);
        fclose($fp);
    }

并确保在 PHP 中.ini allow_url_fopen启用

$file_name_with_full_path = realpath('./upload/example.png');
$curl_handle = curl_init("https://example.com");
curl_setopt($curl_handle, CURLOPT_POST, 1);
$args['file'] = new CurlFile($file_name_with_full_path, 'image/png');
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $args); 
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
$returned_data = curl_exec($curl_handle);
curl_close ($curl_handle);
echo $returned_data;