简体   繁体   中英

File uploading through curl in php

I am trying to upload a file through curl on another server. I have created a script for this, but I am not able to get the $_FILES parameter. It's empty.

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

What version of PHP are you using? In PHP 5.5 the curl option CURLOPT_SAFE_UPLOAD was introduced which startet defaulting to true as of PHP 5.6.0. When it is true file uploads using @/path/to/file are disabled. So, if you are using PHP 5.6 or newer you have to set it to false to allow the upload:

curl_setopt($request, CURLOPT_SAFE_UPLOAD, false);

But the @/path/to/file format for uploads is outdated and deprecated as of PHP 5.5.0, you should use the CurlFile class for this now:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM