M
M
Max Payne2015-03-20 08:26:40
PHP
Max Payne, 2015-03-20 08:26:40

How to send a POST file from a script?

There is an HTML form that submits a file:

<form enctype="multipart/form-data" method="post">
  <p><input type="file" name="file[]" multiple required><input type="submit" name="submit"></p>
 </form>

Next, the script catches this file through the $_FILES array and processes it.
Question: How to send a file through PHP so that it is sent in the $_FILES array, and not using $_POST['file'] = file_get_contents("file.txt");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valery Ryaboshapko, 2015-03-21
@YardalGedal

Apparently, the receiving script is out of your control, or at least you can't edit it. I guessed? :-)
The PHP documentation says that it "is capable of receiving downloaded files from any RFC-1867 compliant browser". RFC-1867 , in turn, introduced the "multipart/form-data" encoding type . Therefore, in order for PHP to understand that it is being passed not just a variable in POST, but a file (and mark it in the $_FILES array), the client needs to pass it the appropriate type. So you can either carefully study the document and organize the transmission yourself using sockets, or carefully study the PHP documentation for cURL.
In PHP 5.5, the rules for using cURL have changed, so that in order to transfer a file, you need to use the CURLFile object (by the way, this page is not in the Russian version of the documentation). In code it will look something like this (not tested).

$ch = curl_init();
$curlfile = new CURLFile('/home/user/we-are-champions.mp3', 'audio/mp3', 'best-song.mp3')
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlfile);
$content = curl_exec($ch);
curl_close ($ch);

Well, or just rollback to an older version of PHP (up to 5.5) and use the approach described in the answer above. But this is unreasonable, in my opinion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question