I am trying to transfer the file to the server using CURL

The request is formed as follows:

$postdata = array( 'FileToLoad' => "@".$this->file."; filename=\"$this->filename\";", 'fileId' => $this->fileId); 

$this->file contains the full path to the file on the server /var/www/site/data/www/site.ru/tmp/file.pdf

I send it like this:

 if( $curl = curl_init() ) { curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER,true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); curl_setopt($curl,CURLOPT_ENCODING, ''); curl_setopt($curl, CURLOPT_COOKIE, ".ASPXAUTH=$this->token;"); $out = curl_exec($curl); curl_close($curl); } 

The request is successful, but the data gets into $ _POST, and I really want to see them in $ _FILES. Where am I wrong?

  • What version of PHP? File upload syntax @ is deprecated in PHP5.5 and disabled by default in 5.6. Instead, use the CURLFile class syntax. And why are you trying to reset CURLOPT_ENCODING? - Fine
  • @ Small, version 5.6. I would appreciate a working reference to the class. CURLOPT_ENCODING is used to parse the response from the server, which compresses the response in gzip - Ordman

2 answers 2

As found in the comments, we are talking about PHP 5.6. Starting with this version, loading files with syntax via @ is disabled by default. Now files need to be uploaded through the CURLFile class, something like this:

 $postdata = array( 'FileToLoad' => new CURLFile($this->file, null /*или mime-type*/, $this->filename), 'fileId' => $this->fileId, ); 

The code of the request itself remains the same.

Apparently, it is easy to fix. But for the sake of completeness, I’ll add that for the old code it is possible to switch back the file transfer using the @ syntax with the CURLOPT_SAFE_UPLOAD option

    To support older PHP versions

     if (!function_exists('curl_file_create')) { function curl_file_create($filename, $mimetype = '', $postname = '') { if(file_exists($filename)) return "@$filename;filename=" . ($postname ?: basename($filename)) . ($mimetype ? ";type=$mimetype" : ''); else exit('Error! File '.$filename.' not found!'); } } 

    And call:

     curl_file_create($file)