Upload a file using file_get_contents
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;
Once that is done, you must build a proper content body that matches the HTTP specification and the header you sent. As you know, when POSTing a file from a form, you will usually have a form field name. We'll define it:
// 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."\r\n".
"Content-Disposition: form-data; name=\"".FORM_FIELD."\"; filename=\"".basename($filename)."\"\r\n".
"Content-Type: application/zip\r\n\r\n".
$file_contents."\r\n";
// add some POST fields to the request too: $_POST['foo'] = 'bar'
$content .= "--".MULTIPART_BOUNDARY."\r\n".
"Content-Disposition: form-data; name=\"foo\"\r\n\r\n".
"bar\r\n";
// signal end of request (note the trailing "--")
$content .= "--".MULTIPART_BOUNDARY."--\r\n";
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,
)
));
And execute:
file_get_contents('http://url/to/upload/handler', false, $context);
NOTE: There is no need to encode your binary file before sending it. HTTP can handle binary just fine.
php file upload with file_get_contents to a server
Why don't you use cURL instead of streams? It's so easy:
$ch = curl_init('http://www.url.com');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'file_input' => '@/path/to/file',
));
curl_exec($ch);
file_get_contents large file upload
file_get_contents
return contents of whole file as a single string variable. In your case it means it will try to create 2 GB variable which exhausts allowed script memory.
Try using fopen
and fgets
. This will allow you to process the file in smaller chunks.
$file_info = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($file_info, $file_loc);
$fileHandle = fopen($file_loc);
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if ($fp) {
$out = "POST /upload/".basename($url)." HTTP/1.1\r\n";
$out .= "Host: ".$host."\r\n";
$out .= "Accept-Language: en-US,en;q=0.8\r\n";
$out .= "Content-Type: ".$mime_type."\r\n";
$out .= 'Content-Length: ' . filesize($file_loc) . "\r\n";
$out .= "Content-Disposition: attachment; filename=\"".urlencode(basename($file_loc))."\"\r\n\r\n";
fwrite($fp, $out);
while(!feof($fileHandle)){
fwrite($fp, fgets($fileHandle, 1024));
}
fclose($fileHandle);
$response = '';
while (!feof($fp)) {
$response .= fgets($fp, 128);
}
fclose($fp);
Is a file in $_FILES the same as a file_get_contents when referring to an image?
$_FILES['picture']['tmp_name']
and $some_image_url
are both just paths pointing at a file. They are NOT the raw file data.
But if you had
$uploaded_image = file_get_contents($_FILES['picture']['tmp_name']);
then both would be equivalent - you'd have the binary data representing your file in the variable.
How to post data in PHP using file_get_contents?
Sending an HTTP POST request using file_get_contents
is not that hard, actually : as you guessed, you have to use the $context
parameter.
There's an example given in the PHP manual, at this page : HTTP context options (quoting) :
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents
-- nothing more ;-)
As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...
Handling upload file with file_get_contents()
Looks like you are inputting the path to your CSV to str_getcsv
$csvArray = array_map("str_getcsv", explode("\n", $csvFile));
Instead of your actual CSV contents
$csvArray = array_map("str_getcsv", explode("\n", $csv));
php://input and file_get_contents just output the POST data rather than process it
A standard configuration of a web server is to execute PHP directives only in files with a .php
file extension.
You could configure your web server to execute PHP in files with a .jpg
file extension (the specifics depend on which web server you are using) but this would be highly unusual — doubly so because a JPEG image is a binary file and not a text file to start with.
Also note that allowing arbitrary PHP to be accepted as user input and then executed on your server is highly dangerous.
I'm aware I won't get executed when viewing the file but shouldn't the PHP I sent in the body get interpreted?
No. Reading a file into a variable only reads a file into a variable. file_get_contents
does not execute PHP directives in user input.
That would also be highly dangerous and PHP isn't that bad.
Related Topics
How to Run Cronjobs More Often Than Once Per Minute
PHP Decoding and Encoding JSON with Unicode Characters
Can You Put PHP Inside PHP with Echo
Using MySQLi from Another Class in PHP
Mysql_Real_Escape_String VS Addslashes
When to Use HTMLspecialchars() Function
Remove Bom () from Imported .CSV File
PHP Send E-Mail with Attachment
Best Practice: PHP Magic Methods _Set and _Get
Laravel - Pass More Than One Variable to View
Call a C Program from PHP and Read Program Output
Php, Display Image with Header()
Least Memory Intensive Way to Read a File in PHP
Jquery Ajax Settimeout After Form Succes Not Redirecting
Special Characters in PHP/Mysql
Woocommerce: Assigning an Endpoint to a Custom Template in My Account Pages