File is empty when POST file with CURLOPT_POSTFIELDS

I am trying to upload a file using a RESTful web service as follows:

$filename = "pathtofile/testfile.txt"; $handle = fopen($filename, "r"); $filecontents = fread($handle, filesize($filename)); fclose($handle); $data = array('name' => 'testfile.txt', 'file' => $filecontents); $client = curl_init($url); curl_setopt($client, CURLOPT_POST, true); curl_setopt($client, CURLOPT_POSTFIELDS, $data); curl_setopt($client, CURLOPT_RETURNTRANSFER, 1); curl_close($client); 

But I keep the gettig file empty as the answer for this request.

I also tried sending the file path, for example:

 $data = array('name' => 'testfile.txt', 'file' => 'pathtofile/testfile.txt'); curl_setopt($client, CURLOPT_POSTFIELDS, $data); 

Or: just send the contents of the file just like this:

 curl_setopt($client, CURLOPT_POSTFIELDS, $filecontents); 

But the same answer: the file is empty .

Note that: the file exists and is not empty, and I'm just trying to download the file without additional fields.

I saw this post , but the same problem, any ideas?

+4
source share
1 answer

Try the following:

 $data = array ('myfile' => '@'.$filename); 

This will populate $_FILE ['myfile'] for the host.

Edit: to actually put the contents of the file as the body, you can do this directly:

 //Get the file data $body = file_get_contents ($filename); $len = strlen ($body); //Open a direct connection to the server on port 80 $socket = fsockopen ('hostname.example.com', 80); //Write the HTTP request headers fwrite ($socket, "POST /path/to/url HTTP/1.1\r\n"); fwrite ($socket, "Host: hostname.example.com\r\n"); fwrite ($socket, "Connection: Close\r\n"); fwrite ($socket, "Content-Length: " . $len . "\r\n"); //Empty line marks end of headers, start of body fwrite ($socket, "\r\n"); //Actually write the body fwrite ($socket, $body); //Get the result (half a kB at a time) $result = ''; while (!feof ($socket)) $result .= fread ($socket, 512); //Clean up nicely fclose ($socket); 

Please note that this code is not tested, but it should give you a general idea.

+1
source

Source: https://habr.com/ru/post/1396403/


All Articles