Post a File String Using Curl in PHP

Send string as a file using curl and php

You can create a file using tempnam in your temp directory:

$string = 'random string';

//Save string into temp file
$file = tempnam(sys_get_temp_dir(), 'POST');
file_put_contents($file, $string);

//Post file
$post = array(
"file_box"=>'@'.$file,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

//do your cURL work here...

//Remove the file
unlink($file);

How to POST upload a file via PHP CURL

You should do something like this

$postData = array(
'folderId' => '3276800',
'filename' => 'TxT_12323.txt',
'filedata' => file_get_contents('847327489732984.txt'),
);

For the most part you can just treat any file as string data in PHP. That doesn't mean you can read and make sense of them, but they can be represented that way in a variable or output and should work just fine.

POST a file string using cURL in PHP?

Should be possible: here's a form, posted through a browser (irrelevant fields omitted):

POST http://host.example.com/somewhere HTTP/1.1
Content-Type: multipart/form-data; boundary=---------------------------7da16b2e4026c
Content-Length: 105732

-----------------------------7da16b2e4026c
Content-Disposition: form-data; name="NewFile"; filename="test.jpg"
Content-Type: image/jpeg

(...raw JPEG data here...)
-----------------------------7da16b2e4026c
Content-Disposition: form-data; name="otherformfield"

content of otherformfield is this text
-----------------------------7da16b2e4026c--

So, if we build the POST body ourselves and set an extra header or two, we should be able to simulate this:

// form field separator
$delimiter = '-------------' . uniqid();
// file upload fields: name => array(type=>'mime/type',content=>'raw data')
$fileFields = array(
'file1' => array(
'type' => 'text/plain',
'content' => '...your raw file content goes here...'
), /* ... */
);
// all other fields (not file upload): name => value
$postFields = array(
'otherformfield' => 'content of otherformfield is this text',
/* ... */
);

$data = '';

// populate normal fields first (simpler)
foreach ($postFields as $name => $content) {
$data .= "--" . $delimiter . "\r\n";
$data .= 'Content-Disposition: form-data; name="' . $name . '"';
// note: double endline
$data .= "\r\n\r\n";
}
// populate file fields
foreach ($fileFields as $name => $file) {
$data .= "--" . $delimiter . "\r\n";
// "filename" attribute is not essential; server-side scripts may use it
$data .= 'Content-Disposition: form-data; name="' . $name . '";' .
' filename="' . $name . '"' . "\r\n";
// this is, again, informative only; good practice to include though
$data .= 'Content-Type: ' . $file['type'] . "\r\n";
// this endline must be here to indicate end of headers
$data .= "\r\n";
// the file itself (note: there's no encoding of any kind)
$data .= $file['content'] . "\r\n";
}
// last delimiter
$data .= "--" . $delimiter . "--\r\n";

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_HTTPHEADER , array(
'Content-Type: multipart/form-data; boundary=' . $delimiter,
'Content-Length: ' . strlen($data)));
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);

This way, we're doing all the heavy lifting ourselves, and trusting cURL not to mangle it.

Use CURL to send a file and parameters in PHP

Uploading files with cURL will become available like just a regular HTTP FILE POST and should be available through $_FILE global variable to be handled the same regular way you'd handle a regular file upload with PHP.

test.php

$cURL = curl_init();

curl_setopt($cURL, CURLOPT_URL, "http://localhost/Projects/Test/test-response.php");
curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

curl_setopt($cURL, CURLOPT_POSTFIELDS, [
"ID" => "007",
"Name" => "James Bond",
"Picture" => curl_file_create(__DIR__ . "/test.png"),
"Thumbnail" => curl_file_create(__DIR__ . "/thumbnail.png"),
]);

$Response = curl_exec($cURL);
$HTTPStatus = curl_getinfo($cURL, CURLINFO_HTTP_CODE);

curl_close ($cURL);

print "HTTP status: {$HTTPStatus}\n\n{$Response}";

test-response.php

print "\n\nPOST";
foreach($_POST as $Key => $Value)print "\n\t{$Key} = '{$Value}';";

print "\n\nFILES";
foreach($_FILES as $Key => $Value)print "\n\t{$Key} = '{$Value["name"]}'; Type = '{$Value["type"]}'; Temporary name = '{$Value["tmp_name"]}'";

Output

HTTP status: 200

POST
ID = '007';
Name = 'James Bond';

FILES
Picture = 'test.png'; Type = 'application/octet-stream'; Temporary name = 'C:\Windows\Temp\php76B5.tmp'
Thumbnail = 'thumbnail.png'; Type = 'application/octet-stream'; Temporary name = 'C:\Windows\Temp\php76C6.tmp'

I assume you will keep the relevant 2 images in the same path as 'test.php' to obtain the output as shown.

Php Curl send File with data

Here the sample curl request

$curlFile = curl_file_create($uploaded_file_name_with_full_path);
$post = array('val1' => 'value','val2' => 'value','file_contents'=> $curlFile );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$your_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

Don't forget to put the appropriate header.

You can also find good source here
Curl File Upload
to send file via CURL. Make sure that you are passing your file on file_contents key in above code.

PHP upload file using a directory string

your problem here is that you're using json_encode. json_encode cannot encode CURLFile objects. also, JSON is not binary safe, so you can't send PNG files with json (PNG files contain binary data, for example including the FF/255 byte, which is illegal in json. that said, a common workaround is to encode binary data in base64, and send the base64 in json). stop using json, just give CURLOPT_POSTFIELD the array, and curl will encode it in the multipart/form-data-format, which is the de-facto standard for uploading files over the http protocol. going that route, you must also get rid of the Content-Type: application/json header, and curl will automatically insert Content-Type: multipart/form-data for you.



Related Topics



Leave a reply



Submit