Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

How to post a mutlipart file using file_get_contents in php

/*
First of all, the first rule of multipart Content-Type 
is to define a boundary that will be used as a delimiter 
between each part (because as the name says, it can have 
multiple parts). The boundary can be any string that is 
not contained in the content body. I will usually use a timestamp:
*/

define('MULTIPART_BOUNDARY', '--------------------------'.microtime(true));

/*Once your boundary is defined, you must send it with the 
Content-Type header to tell the webserver what delimiter to expect:
*/
$header = 'Content-Type: multipart/form-data; boundary='.MULTIPART_BOUNDARY;


// equivalent to <input type="file" name="uploaded_file"/>
define('FORM_FIELD', 'uploaded_file'); 

//Then we build the content body:

$filename = "/path/to/uploaded/file.zip";
$file_contents = file_get_contents($filename);    

$content =  "--".MULTIPART_BOUNDARY."
".
            "Content-Disposition: form-data; name="".FORM_FIELD.""; filename="".basename($filename).""
".
            "Content-Type: application/zip

".
            $file_contents."
";

// add some POST fields to the request too: $_POST['foo'] = 'bar'
$content .= "--".MULTIPART_BOUNDARY."
".
            "Content-Disposition: form-data; name="foo"

".
            "bar
";

// signal end of request (note the trailing "--")
$content .= "--".MULTIPART_BOUNDARY."--
";
/*
As you can see, we're sending the Content-Disposition header 
with the form-data disposition, along with the name parameter 
(the form field name) and the filename parameter (the original filename). 
It is also important to send the Content-Type header with the proper 
MIME type, if you want to correctly populate the $_FILES[]['type'] thingy.

If you had multiple files to upload, you just repeat the process with 
the $content bit, with of course, a different FORM_FIELD for each file.
Now, build the context:
*/
$context = stream_context_create(array(
    'http' => array(
          'method' => 'POST',
          'header' => $header,
          'content' => $content,
    )
));

//execute request


file_get_contents('http://url/to/upload/handler', false, $context);
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #How #post #mutlipart #file #php
ADD COMMENT
Topic
Name
9+8 =