PHP analog POST request send file _php tutorial

Source: Internet
Author: User
Tags php website nginx server

PHP analog POST request send file


Because of the needs of the project, the local server needs to receive data, and then forward the data to another server, it is necessary to use the analog POST request to send data, of course, the data also contains file streams.

Curl is one of the most common ways PHP is used, and the general code is as follows:

$params 1 = test; $params 2 = @. $absolute _path;//If it is a file, the parameter is @+ absolute path $post_data = Array (  ' params1 ' = = $params 1,  ' Params2 ' = $params 2,); function PostData ($url, $data) {      $ch = Curl_init ();      $timeout =;       curl_setopt ($ch, Curlopt_url, $url);   Request Address//curl_setopt ($ch, Curlopt_referer, $IP);//construct the route    curl_setopt ($ch, Curlopt_post, true);  Post Request curl_setopt ($ch, curlopt_binarytransfer,true);//binary Stream    curl_setopt ($ch, Curlopt_postfields, $data);      Data curl_setopt ($ch, Curlopt_returntransfer, 1);  When Curlopt_returntransfer is set to 1 o'clock $head has the requested return value    curl_setopt ($ch, Curlopt_connecttimeout, $timeout);    Set request time  -out $handles = curl_exec ($ch);      Curl_close ($ch); return $handles;}
The other side is the Java server, I only know the interface, do not know how to handle the file received. The above approach was successful in the Win7 Wamp environment, but it failed to put the code on the Centos+nginx server, and the message returned was that the file received failed. After grasping the packet analysis, found in Win7 Wamp issued by the package and CentOS Nginx issued by the HTTP packet format is different. In general, curl defaults to Content_Type set to Multipart/form-data, on my machine Win7 Wamp, but the CentOS Nginx is application/ X-www-form-urlencoded. Of course this may be a server configuration problem, but I don't know where the problem is. Then I looked at the next PHP version, the same as php5.3.x, but with a slight difference. Also does not exclude is the PHP version of the problem. Then add the code:

$header = Array (' Content-type:multipart/form-data ',); curl_setopt ($ch, Curlopt_httpheader, $header);
The header is set, but it still does not work under CentOS. Can not change the content-type, it is the pit father.

Later, with the help of the technical Director, read a link on the official PHP website http://php.net/manual/en/class.curlfile.php, referring to the official website practice in the win Wamp and CentOS Nginx POST request has been successful. Read the code carefully, found that the procedure was completely written in the body of the HTTP request, rather than curl their own generated parts, have to admire. Release the code below:

function PostData ($url, $data = Array (), $data 1 = array ()) {$header = array (' Content-type:multipart/form-data ',); $ch = Curl_init (); curl_setopt ($ch, Curlopt_url, $url), curl_setopt ($ch, Curlopt_httpheader, $header); curl_setopt ($ch, Curlopt_ Returntransfer, 1); curl_setopt ($ch, curlopt_connecttimeout,10); curl_setopt ($ch, curlopt_binarytransfer,true); curl_setopt ($ch, Curlopt_postfields, $data) curl_custom_postfields ($ch, $data, $data 1); $dxycontent = Curl_exec ($ch ); Curl_close ($ch); return $dxycontent;} /*** for safe multipart POST request for PHP5.3 ~ PHP 5.4.* * @param resource $ch CURL resource* @param array $assoc name = = value* @param array $files name = path* @return bool*/function curl_custom_postfields ($ch, array $assoc = Array ( ), Array $files = Array ()) {//invalid characters for name and filenamestatic $disallow = Array (,,,);/Build Normal PA Rametersforeach ($assoc as $k + $v) {$k = Str_replace ($disallow, _, $k); $body [] = implode (, Array (content-dispositIon:form-data; name={$k},,filter_var ($v),));} Build file Parametersforeach ($files as $k = + $v) {switch (true) {case false = = = $v = Realpath (Filter_var ($v)): Case !is_file ($v): Case!is_readable ($v): continue; or return false, throw new invalidargumentexception} $data = file_get_contents ($v); $v = Call_user_func (end, Explode (DIR Ectory_separator, $v)); $k = Str_replace ($disallow, _, $k); $v = Str_replace ($disallow, _, $v); $body [] = implode (, Array (Con Tent-disposition:form-data; name={$k}; filename={$v},content-type:application/octet-stream,, $data,));} Generate safe boundary do {$boundary =---------------------. MD5 (Mt_rand (). Microtime ()),} while (Preg_grep (/{$bound ary}/, $body));//Add boundary for each parametersarray_walk ($body, function (& $part) use ($boundary) {$part =--{$bou ndary}{$part};});       /Add final boundary$body[] =--{$boundary}--; $body [] =;//Set Optionsreturn @curl_setopt_array ($ch, Array (curlopt_post = True,curlopt_postfields-Implode (, $boDY), Curlopt_httpheader + = Array (expect:100-continue,content-type:multipart/form-data; boundary={$boundary},// Change content-type),));}
Parameter passing has no effect, if the file is +@ before the absolute path. The only difference is that the file data and the normal data are distinguished by different arrays, which are handled differently when simulating the body part of HTTP. Finally, the file is uploaded successfully.

http://www.bkjia.com/PHPjc/1043339.html www.bkjia.com true http://www.bkjia.com/PHPjc/1043339.html techarticle PHP analog POST request send file due to project needs, the local server needs to receive data, and then forward the data to another server, it is necessary to use the analog POST request to send data, ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.