【问题标题】:File uploading through curl in phpphp中通过curl上传文件
【发布时间】:2016-03-19 20:56:43
【问题描述】:

我正在尝试通过 curl 在另一台服务器上上传文件。我为此创建了一个脚本,但我无法获得$_FILES 参数。是空的。

$request = curl_init('http://localhost/pushUploadedFile.php');
$file_path = $path.$name;
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
     $request,
     CURLOPT_POSTFIELDS,
     array(
      'file' => '@' . $file_path,
      'test' => 'rahul'
));
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);exit();

pushUploadedFile.php:

print_r($_FILES['file']);

【问题讨论】:

    标签: php php-curl


    【解决方案1】:
    $file_name_with_full_path = realpath('./sample.jpeg');
    $post = array('extra_info' => '123456','file_contents'=>'@'.$file_name_with_full_path);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$target_url);
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $result=curl_exec ($ch);
    curl_close ($ch);
    

    【讨论】:

      【解决方案2】:

      您使用的是什么版本的 PHP?在 PHP 5.5 中引入了 curl 选项 CURLOPT_SAFE_UPLOAD,从 PHP 5.6.0 开始默认为 true。当它是true 时,使用@/path/to/file 的文件上传被禁用。因此,如果您使用的是 PHP 5.6 或更高版本,则必须将其设置为 false 以允许上传:

      curl_setopt($request, CURLOPT_SAFE_UPLOAD, false);
      

      但自 PHP 5.5.0 起,用于上传的 @/path/to/file 格式已过时且已弃用,您现在应该为此使用 CurlFile 类:

      $request = curl_init();
      $file_path = $path.$name;
      curl_setopt($request, CURLOPT_URL, 'http://localhost/pushUploadedFile.php');
      curl_setopt($request, CURLOPT_POST, true);
      curl_setopt(
           $request,
           CURLOPT_POSTFIELDS,
           array(
            'file' => new CurlFile( $file_path ),
            'test' => 'rahul'
      ));
      curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
      echo curl_exec($request);
      

      【讨论】:

        【解决方案3】:
                $target_url ="http://www.localwork.com/pushUploadedFile.php";     
                $file_full_path = $path.$img_name;            
                $file_name_with_full_path = new CurlFile($file_full_path, 'image/png', $name);
        
                $post = array('path' => $path,'file_contents'=>$file_name_with_full_path);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL,$target_url);
                curl_setopt($ch, CURLOPT_POST,1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
                $result=curl_exec ($ch);
                curl_close ($ch);
        

        【讨论】:

          猜你喜欢
          • 2016-02-22
          • 2017-10-25
          • 2011-08-04
          • 1970-01-01
          • 2019-05-29
          • 2012-11-24
          • 2020-01-05
          • 1970-01-01
          • 2020-02-10
          相关资源
          最近更新 更多