How to send a multipart request with php

纵饮孤独 提交于 2019-12-12 05:39:18

问题


I'd like to know how I can send a multipart/form-data encoded post request out of php. I already found this code here:

$destination = "http://yourdomain.com/yoururl";



$eol = "\r\n";

$data = '';


$mime_boundary=md5(time());


$data .= '--' . $mime_boundary . $eol;

$data .= 'Content-Disposition: form-data; name="somedata"' . $eol . $eol;

$data .= "Some Data" . $eol;

$data .= '--' . $mime_boundary . $eol;

$data .= 'Content-Disposition: form-data; name="somefile"; 
filename="filename.ext"' . $eol;

$data .= 'Content-Type: text/plain' . $eol;

$data .= 'Content-Transfer-Encoding: base64' . $eol . $eol;

$data .= chunk_split(base64_encode("Some file content")) . $eol;

$data .= "--" . $mime_boundary . "--" . $eol . $eol; // finish with two 
eol's!!


$params = array('http' => array(

                  'method' => 'POST',

                  'header' => 'Content-Type: multipart/form-data; boundary=' 
. $mime_boundary . $eol,

                  'content' => $data


               ));


$ctx = stream_context_create($params);

$response = @file_get_contents($destination, FILE_TEXT, $ctx);

(http://vedovini.net/2009/08/posting-multipart-form-data-using-php/) My question is: How can I define the file that should be sent? (Just to explain what I like to do: The User uploads a file with a simple http form, the php script receives it and should "resend" the file to another url). I also have to send 1 variable in a json array along with the file.


回答1:


Use cURL instead of file_get_contents, there is a similar question about using it with multipart POST submissions here.



来源:https://stackoverflow.com/questions/32797740/how-to-send-a-multipart-request-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!