PHP simulate POST request send file

Source: Internet
Author: User
Tags add foreach array continue header http request version nginx server

Because the project needs, the local server needs to receive data, and then forward the data to another server, so use an analog post request to send data, of course, the data also contains file flow.

Curl is one of the more common ways of PHP, the general code is as follows:

$params 1 = test;
$params 2 = @. $absolute _path;//If it is a file The argument 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 Routing    
	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 the requested return value    
	curl_setopt ($ch, Curlopt_connecttimeout, $timeout);    Set the request timeout  
	$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 the other party to handle the file received. The above method was successful in the Win7 Wamp environment, but failed to put the code on the Centos+nginx server, and the message returned was that the file received failed. After the analysis of the bag, it was found that the packages issued by Win7 Wamp and CentOS Nginx were different in the format of HTTP packets. Under normal circumstances curl default Content_Type set to Multipart/form-data, on my machine Win7 wamp is so, but CentOS Nginx under application/ X-www-form-urlencoded. Of course this could be a server configuration issue, but I don't know what the problem is. Then I looked at the PHP version, same as php5.3.x, but there was a slight difference. Also do not exclude the PHP version of the problem. Add code after:
$header = Array (
	' Content-type:multipart/form-data ',
);
curl_setopt ($ch, Curlopt_httpheader, $header);
Set header, but still invalid under CentOS. Can't change Content-type, it's just a pit dad.

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 win Wamp and CentOS Nginx under the POST request has been successful. Read the code carefully, found that the practice is completely written in the body of the HTTP request, rather than curl their own generation of parts, have to admire. The following release code:

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 * @ret  URN bool/function curl_custom_postfields ($ch, array $assoc = Array (), array $files = Array ()) {//invalid characters
	
	For name and filename static $disallow = Array (,,,); Build normal parameters foreach ($assoc as $k => $v) {$k = Str_replace ($diSallow, _, $k);
	$body [] = implode (, array (Content-disposition:form-data name={$k}, Filter_var ($v)); }//Build file Parameters foreach ($files as $k => $v) {switch (true) {case false = = = 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 (Directory_separator, $v));
		$k = Str_replace ($disallow, _, $k);
		$v = Str_replace ($disallow, _, $v); $body [] = implode (, array (Content-disposition:form-data name={$k}; filename={$v}, Content-type:application/octe
	T-stream,, $data,));
	}//Generate safe boundary do {$boundary =---------------------. MD5 (Mt_rand (). Microtime ());
	
	while (Preg_grep (/{$boundary}/, $body)); Add boundary for each parameters Array_walk ($body, function (& $part) use ($boundary) {$part =--{$boundary} {$p
	Art};
	
	}); Add Final boundary $body [] =--{$boundary}--;
	
	$body [] =; 
Set options return @curl_setopt_array ($ch, Array (Curlopt_post => true, Curlopt_postfields => implode ( , $body), Curlopt_httpheader => Array (expect:100-continue, content-type:multipart/form-data; boundary={$bou
Ndary},//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 separated by different arrays and processed differently when simulating the body part of HTTP. Finally uploaded the file successfully.



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.