note 102575 added to function.file-get-contents

[email protected] Tue, 22 Feb 2011 07:30:38 -0800
Newsgroups php.notes
Message-ID <[email protected]>
here is another (maybe the easiest) way of doing POST http requests from php using its built-in capabilities. feel free to add the headers you need (notably the Host: header) to further customize the request.

note: this method does not allow file uploads. if you want to upload a file with your request you will need to modify the context parameters to provide multipart/form-data encoding (check out http://www.php.net/manual/en/context.http.php ) and build the $data_url following the guidelines on http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

<?php
/**
make an http POST request and return the response content and headers
@param string $url	url of the requested script
@param array $data	hash array of request variables
@return returns a hash array with response content and headers in the following form:
	array ('content'=>'<html></html>'
		, 'headers'=>array ('HTTP/1.1 200 OK', 'Connection: close', ...)
		)
*/
function http_post ($url, $data)
{
	$data_url = http_build_query ($data);
	$data_len = strlen ($data_url);

	return array ('content'=>file_get_contents ($url, false, stream_context_create (array ('http'=>array ('method'=>'POST'
			, 'header'=>"Connection: close\r\nContent-Length: $data_len\r\n"
			, 'content'=>$data_url
			))))
		, 'headers'=>$http_response_header
		);
}
?>
----
Server IP: 195.221.21.36
Probable Submitter: 92.128.24.184
----
Manual Page -- http://www.php.net/manual/en/function.file-get-contents.php
Edit        -- https://master.php.net/note/edit/102575
Del: integrated  -- https://master.php.net/note/delete/102575/integrated
Del: useless     -- https://master.php.net/note/delete/102575/useless
Del: bad code    -- https://master.php.net/note/delete/102575/bad+code
Del: spam        -- https://master.php.net/note/delete/102575/spam
Del: non-english -- https://master.php.net/note/delete/102575/non-english
Del: in docs     -- https://master.php.net/note/delete/102575/in+docs
Del: other reasons-- https://master.php.net/note/delete/102575
Reject      -- https://master.php.net/note/reject/102575
Search      -- https://master.php.net/manage/user-notes.php