在 php 中通过 curl 上传文件

File uploading through curl in php

我正在尝试通过 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']);
$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);

您使用的 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 class:

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