PHP upload and send file with cURL - php

I'm attempting to upload a file to a WordPress installation and then send it, along with other data from other form fields, to Lever's API.
I can send data to the endpoint just fine, but not so much with the file uploading. The following does in fact upload to wp-content/uploads, but I think the problem lies either on the next line move_uploaded_file or where I'm passing it in the $data array.
<form enctype="multipart/form-data" method="post" action="<?php echo get_template_directory_uri(); ?>/jobForm.php">
<input type="file" name="resume">
<button type="submit">Submit</button>
</form>
<?php
// URL
$url = "https://api.lever.co/v0/postings/XXXX/XXXXXX";
$name = $_POST["name"];
$email = $_POST["email"];
$urls = $_POST["urls"];
$target = "/www/wp-content/uploads/" . basename($_FILES["resume"]["name"]);
move_uploaded_file($_FILES["resume"]["tmp_name"], $target);
// data
$data = array(
"name" => $name,
"email" => $email,
"urls" => $urls,
"resume" => #$_FILES["resume"]
);
// initiate curl instance, set options, and post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // url
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // full data to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return results as a string instead of outputting directly
echo $data["resume"];
// $output
$output = curl_exec($ch);
var_dump($output);
// close curl resource to free up system resources
curl_close($ch);
?>
I tried using the $target variable for the "resume" $data value, but that didn't seem to work either. As you can probably tell, I'm not exactly sure where this is going wrong (I'm a front-end developer out of my element :D).
Echoing $data["resume"] gives an Array, while echoing $target gives the location + name of the file, as expected. I guess I'm unsure what I need to be passing through in the $data array...Any ideas what I'm doing wrong here? If it helps, I get no error from Lever when submitting. In fact, it returns a 200 OK message and posts just fine, just without a resume field!

You can do that like this
$localFile = $_FILES[$fileKey]['tmp_name'];
$fp = fopen($localFile, 'r');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'someurl' . $strFileName); //$strFileName is obvious
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);
if (curl_errno($ch)) {
$msg = curl_error($ch);
}
else {
$msg = 'File uploaded successfully.';
}
curl_close ($ch);
$return = array('msg' => $msg);
echo json_encode($return);

Related

How to upload file into target directory with curl?

There is a file "/home/test.mp4" in my local machine,
I want to upload it into /var/www/ok.mp4 (the name changed when uploaded it). All the source file and target file are in the local machine.
How to fix my partial code ,to add something or to change something ?
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_exec($ch);
?>
Think to Ram Sharma, the code was changed as the following:
<?php
$request = curl_init('http://127.0.0.1/');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('/home/test.mp4')
));
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
// close the session
curl_close($request);
?>
An error message occur:
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet.
I have test with ftp_put,code1 works fine.
code1:
<?php
set_time_limit(0);
$host = 'xxxx';
$usr = 'yyyy';
$pwd = 'zzzz';
$src = 'd:/upload.sql';
$ftp_path = '/public_html/';
$des = 'upload_ftp_put.sql';
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
$upload = ftp_put($conn_id, $ftp_path.$des, $src, FTP_ASCII);
print($upload);
?>
The file d:/upload.sql in my local pc can be uploaded into my_ftp_ip/public_html/upload_ftp_put.sql with code1.
Now i rewite it with curl into code2.
code2:
<?php
set_time_limit(0);
$ch = curl_init();
$host = 'xxxx';
$usr = 'yyyy';
$pwd = 'zzzz';
$src = 'd:/upload.sql';
$ftp_path = '/public_html';
$dest = 'upload_curl.sql';
$fp = fopen($src, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://user:pwd#host/'.$ftp_path .'/'. $dest);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($src));
curl_exec ($ch);
$error_no = curl_errno($ch);
print($error_no);
curl_close ($ch);
?>
The error info output is 6 .Why can't upload my local file into the ftp with curl?How to fix it?
Use copy():
copy('/home/test.mp4', '/var/www/ok.mp4');
It does not make sense to run the file through the network stack (which is what cURL does), on any protocol (HTTP, FTP, …), when the manipulation can be done locally, through the file system. Using network is more complicated and error-prone.
It is a low level error.
curl_setopt($ch, CURLOPT_URL, "ftp://$usr:$pwd#$host$ftp_path/$dest");
try something like this and I feel instead of server directory path it would be http url.
// initialise the curl request
$request = curl_init('http://example.com/');
// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('test.txt')
));
// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
// close the session
curl_close($request);
This code might help you:
<?php
$rCURL = curl_init();
curl_setopt($rCURL, CURLOPT_URL, 'http://www.google.com/images/srpr/logo11w.png');
curl_setopt($rCURL, CURLOPT_HEADER, 0);
curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, 1);
$aData = curl_exec($rCURL);
curl_close($rCURL);
file_put_contents('bla.jpeg', $aData);
// file_put_contents('my_folder/bla.jpeg', $aData); /*You can use this too*/
Try to specify the MIME type of the file sent like this
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('/home/test.mp4') . ';type=video/mp4'
));
The code you posted is for the client side. If you want to upload a file using HTTP, you HTTP server must be able to handle this upload request and save the file where you want. The “error message” is probably the server’s default web page.
Sample server-side code in PHP, for your reference:
<?php
if ($_FILES) {
$filename = $_FILES['file']['name'];
$tmpname = $_FILES['file']['tmp_name'];
if (move_uploaded_file($tmpname,'/var/www/ok.mp4')) {
print_r('ok');
} else {
print_r('failure');
}
}
curl -X POST -F "image=#test.mp4" http://example.com/
You will also need a page that can process this request (POST)

Submitting Catcha on an external form

I've been presented with a challenge which has had be stumped now for a few days. I am working on a project for which I need to submit a form on an external sever which also has a captcha.
I am capable of solving the captcha and getting the proper values... I use curl with POST form to get attempt to submit the complete form using the captcha I've managed to get.
However, when I run the script, I a returned message that the security code (captcha) was incorrect. I believe it might be because once use curl to post, the image has a different code?
Here is the code I am using:
# SAVE CAPTCHA
function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIESESSION,true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
function postform(){
grab_image('path to/site', 'captcha.jpg');
$image = 'captcha.jpg';
$client = new DeathByCaptcha_SocketClient("myusername", "mypassword");
if ($captcha = $client->decode($image, 10)) {
$url = "path to url in form action";
$data = array();
$data['submit']='1';
$data['name']='my name';
$data['comments']='Success Posting This Form';
$data['vercode']=$captcha['text'];
$data['Send']='Send Email to Breeder';
$post_str = '';
foreach($data as $key=>$value){
$post_str .= $key.'='.urlencode($value).'&';
}
$post_str = substr($post_str, 0, -1);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
curl_setopt($ch, CURLOPT_COOKIEFILE, TRUE);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
}
Again... after running this, I get that the captcha code is incorrect. Everything else seems to have worked fine and I'm able to solve the captcha. I guess my main difficulty lies in being able to make sure that the captcha code submitted is the same that is expected. Perhaps it refreshed? I'm not sure.
Any help on resolving this challenge will be greatly appreciated!!

Symfony 1.4.2 no content in PHP cURL PUT request

Using PHP cURL and Symfony 1.4.2
I'm trying to do a PUT request including data (JSON) to modify an object in my REST web services, but can't catch the data on the server side.
It seems that the content is attached successfully when checking at my logs:
PUT to http://localhost:8080/apiapp_test.php/v1/reports/498 with post body content=%7B%22report%22%3A%7B%22title%22%3A%22The+title+has+been+updated%22%7D%7D
I attached the data like this:
$curl_opts = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => http_build_query(array('content' => $post_data)),
);
And wanted to get the data using something like this
$payload = $request->getPostParameter('content');
It is not working and I've tried many ways to get this data in my actions file.
I've tried the following solutions:
parse_str(file_get_contents("php://input"), $post_vars);
$payload = $post_vars['content'];
// or
$data = $request->getContent(); // $request => sfWebRequest
$payload = $data['content'];
// or
$payload = $request->getPostParameter('content');
// then I'd like to do that
$json_array = json_decode($payload, true);
I just don't know how to get this data in my actions and it's frustrating, I've read many topics here about it but none is working for me.
Additional informations:
I have these setup for my cURL request:
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, $http_method);
if ($http_method === sfRequest::PUT) {
curl_setopt($curl_request, CURLOPT_PUT, true);
$content_length = array_key_exists(CURLOPT_POSTFIELDS, $curl_options) ? strlen($curl_options[CURLOPT_POSTFIELDS]) : 0;
$curl_options[CURLOPT_HTTPHEADER][] = 'Content-Length: ' . $content_length;
}
curl_setopt($curl_request, CURLOPT_URL, $url);
curl_setopt($curl_request, CURLOPT_CONNECTTIMEOUT, 4);
curl_setopt($curl_request, CURLOPT_TIMEOUT, 4);
curl_setopt($curl_request, CURLOPT_DNS_CACHE_TIMEOUT, 0);
curl_setopt($curl_request, CURLOPT_NOSIGNAL, true);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
In sfWebRequest.php, I've seen this:
case 'PUT':
$this->setMethod(self::PUT);
if ('application/x-www-form-urlencoded' === $this->getContentType())
{
parse_str($this->getContent(), $postParameters);
}
break;
So I tried to set the header's Content-Type to it but it doesn't do anything.
If you have any idea, please help!
According to an other question/answer, I've tested this solution and I got the correct result:
$body = 'the RAW data string I want to send';
/** use a max of 256KB of RAM before going to disk */
$fp = fopen('php://temp/maxmemory:256000', 'w');
if (!$fp) {
die('could not open temp memory data');
}
fwrite($fp, $body);
fseek($fp, 0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));
$output = curl_exec($ch);
echo $output;
die();
And on the other side, you can retrieve the content using:
$content = $request->getContent();
If you var_dump it, you will retrieve:
the RAW data string I want to send

Save Page As XML

I have made a script that generates an IMDB API link for a movie in XML.
Once this link is generated it will save to an XML file with its contents. The only issue is that the contents aren't saving.
Link generated:
http://imdbapi.org/?title=One+Piece&type=xml&plot=simple&mt=none&episode=0&aka=simple&release=simple
PHP script:
$url="http://imdbapi.org/?title=One+Piece&type=xml&plot=simple&mt=none&episode=0&aka=simple&release=simple";
$curl = curl_init();
$data = fopen("text.xml", "w");
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FILE, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec ($curl);
if ( !$data ) {
echo "No";
} else {
$contents = curl_exec($curl);
fwrite($data, $contents);
}
curl_close($curl);
fclose($data);
Instead of using file_get_contents, you can use CURL
$ch = curl_init('http://imdbapi.org/?title=One+Piece&type=xml&plot=simple&mt=none&episode=0&aka=simple&release=simple');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
Now $response shall contains your XML. And you can do something like
file_put_contents('filename.xml', $response);
make sure that filename.xml is writable

Send file via cURL from form POST in PHP

I'm writing an API and I'm wanting to handle file uploads from a form POST. The markup for the form is nothing too complex:
<form action="" method="post" enctype="multipart/form-data">
<fieldset>
<input type="file" name="image" id="image" />
<input type="submit" name="upload" value="Upload" />
</fieldset>
</form>
However, I'm having difficulties understanding how to handle this server-side and send along with a cURL request.
I'm familiar with sending POST requests with cURL with a data array, and resources I've read on uploading files tell me to prefix the filename with an # symbol. But these same resources have a hard-coded file name, e.g.
$post = array(
'image' => '#/path/to/myfile.jpg',
...
);
Well which file path is this? Where would I find it? Would it be something like $_FILES['image']['tmp_name'], in which case my $post array should look like this:
$post = array(
'image' => '#' . $_FILES['image']['tmp_name'],
...
);
Or am I going about this the wrong way? Any advice would be most appreciated.
EDIT: If someone could give me a code snippet of where I would go with the following code snippets then I'd be most grateful. I'm mainly after what I would send as cURL parameters, and a sample of how to use those parameters with the receiving script (let's call it curl_receiver.php for argument's sake).
I have this web form:
<form action="script.php" method="post" enctype="multipart/form-data">
<fieldset>
<input type="file" name="image />
<input type="submit" name="upload" value="Upload" />
</fieldset>
</form>
And this would be script.php:
if (isset($_POST['upload'])) {
// cURL call would go here
// my tmp. file would be $_FILES['image']['tmp_name'], and
// the filename would be $_FILES['image']['name']
}
Here is some production code that sends the file to an ftp (may be a good solution for you):
// This is the entire file that was uploaded to a temp location.
$localFile = $_FILES[$fileKey]['tmp_name'];
$fp = fopen($localFile, 'r');
// Connecting to website.
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "email#email.org:password");
curl_setopt($ch, CURLOPT_URL, 'ftp://#ftp.website.net/audio/' . $strFileName);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);
if (curl_errno($ch)) {
$msg = curl_error($ch);
}
else {
$msg = 'File uploaded successfully.';
}
curl_close ($ch);
$return = array('msg' => $msg);
echo json_encode($return);
For people finding this post and using PHP5.5+, this might help.
I was finding the approach suggested by netcoder wasn't working. i.e. this didn't work:
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
I would receive in the $_POST var the 'uploaded_file' field - and nothing in the $_FILES var.
It turns out that for php5.5+ there is a new curl_file_create() function you need to use. So the above would become:
$data = array(
'uploaded_file' => curl_file_create($tmpfile, $_FILES['image']['type'], $filename)
);
As the # format is now deprecated.
This should work:
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)
curl_exec($ch);
In the receiving script, you would have:
print_r($_FILES);
/* which would output something like
Array (
[uploaded_file] => Array (
[tmp_name] => /tmp/f87453hf
[name] => myimage.jpg
[error] => 0
[size] => 12345
[type] => image/jpeg
)
)
*/
Then, if you want to properly handle the file upload, you would do something like this:
if (move_uploaded_file($_FILES['uploaded_file'], '/path/to/destination/file.zip')) {
// do stuff
}
For my the # symbol did not work, so I do some research and found this way and it work for me, I hope this help you.
$target_url = "http://server:port/xxxxx.php";
$fname = 'file.txt';
$cfile = new CURLFile(realpath($fname));
$post = array (
'file' => $cfile
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec ($ch);
if ($result === FALSE) {
echo "Error sending" . $fname . " " . curl_error($ch);
curl_close ($ch);
}else{
curl_close ($ch);
echo "Result: " . $result;
}
It works for me when sending an attachment to Mercadolibre, through its messaging system.
The anwswer https://stackoverflow.com/a/35227055/7656744
$target_url = "http://server:port/xxxxx.php";
$fname = 'file.txt';
$cfile = new CURLFile(realpath($fname));
$post = array (
'file' => $cfile
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec ($ch);
if ($result === FALSE) {
echo "Error sending" . $fname . " " . curl_error($ch);
curl_close ($ch);
}else{
curl_close ($ch);
echo "Result: " . $result;
}
cURL file object in procedural method:
$file = curl_file_create('full path/filename','extension','filename');
cURL file object in Oop method:
$file = new CURLFile('full path/filename','extension','filename');
$post= array('file' => $file);
$curl = curl_init();
//curl_setopt ...
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
we can upload image file by curl request by converting it base64 string.So in post we will send file string and then covert this in an image.
function covertImageInBase64()
{
var imageFile = document.getElementById("imageFile").files;
if (imageFile.length > 0)
{
var imageFileUpload = imageFile[0];
var readFile = new FileReader();
readFile.onload = function(fileLoadedEvent)
{
var base64image = document.getElementById("image");
base64image.value = fileLoadedEvent.target.result;
};
readFile.readAsDataURL(imageFileUpload);
}
}
then send it in curl request
if(isset($_POST['image'])){
$curlUrl='localhost/curlfile.php';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $curlUrl);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, 'image='.$_POST['image']);
$result = curl_exec($ch);
curl_close($ch);
}
see here http://technoblogs.co.in/blog/How-to-upload-an-image-by-using-php-curl-request/118
Here is my solution, i have been reading a lot of post and they was really helpfull, finaly i build a code for small files, with cUrl and Php, that i think its really usefull.
public function postFile()
{
$file_url = "test.txt"; //here is the file route, in this case is on same directory but you can set URL too like "http://examplewebsite.com/test.txt"
$eol = "\r\n"; //default line-break for mime type
$BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
$BODY=""; //init my curl body
$BODY.= '--'.$BOUNDARY. $eol; //start param header
$BODY .= 'Content-Disposition: form-data; name="sometext"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
$BODY .= "Some Data" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
$BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
$BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
$BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
$BODY.= 'Content-Transfer-Encoding: base64' . $eol . $eol; // we put the last Content and 2 $eol,
$BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
$BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
$ch = curl_init(); //init curl
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
curl_setopt($ch, CURLOPT_URL, "api.endpoint.post"); //setting our api post url
curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); navigate the endpoint
curl_setopt($ch, CURLOPT_POST, true); //set as post
curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY
$response = curl_exec($ch); // start curl navigation
print_r($response); //print response
}
With this we shoud be get on the "api.endpoint.post" the following vars posted
You can easly test with this script, and you should be recive this debugs on the function postFile() at the last row
print_r($response); //print response
public function getPostFile()
{
echo "\n\n_SERVER\n";
echo "<pre>";
print_r($_SERVER['HTTP_X_PARAM_TOKEN']);
echo "/<pre>";
echo "_POST\n";
echo "<pre>";
print_r($_POST['sometext']);
echo "/<pre>";
echo "_FILES\n";
echo "<pre>";
print_r($_FILEST['somefile']);
echo "/<pre>";
}
Here you are it should be work good, could be better solutions but this works and is really helpfull to understand how the Boundary and multipart/from-data mime works on php and curl library,
My Best Reggards,
my apologies about my english but isnt my native language.

Categories