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

时间:2015-01-12 08:46:28

标签: php curl

我已经在这3天了,但我似乎无法解决它,用户将输入网址,系统会将其上传到远程服务器上..这是我到目前为止所做的事情< / p>

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

3 个答案:

答案 0 :(得分:0)

以这种方式做到这一点。

  1. 首先从用户提供的网址下载该文件。
  2. http://1234.4321.67.11/upload.php
  3. 上传该图片
  4. 在服务器上成功上传后删除该文件。
  5. 这可以帮助您使用cURL在服务器上上传图片:https://stackoverflow.com/a/15177543/1817160

    这可能有助于您了解如何从网址下载图片: Copy Image from Remote Server Over HTTP

答案 1 :(得分:0)

使用以下功能使用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

答案 2 :(得分:0)

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