通过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']);

您使用的是什么版本的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);

但是上传的@/path/to/file格式已经过时,并且从PHP 5.5.0开始就不推荐使用了,现在应该使用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);
$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);
        $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);