Here's one I made earlier.
/*
* Sends a form-encoded HTTP(S) POST to a given URL.
* Returns a string containing the response.
*
* If response code is not 200, throws an error msg.
*/
function SendHttpPost($url, & $fields)
{
$urlencoded = '';
foreach (array_keys($fields) as $key) {
$urlencoded = $urlencoded . "$key=" . rawurlencode($fields[$key]);
$urlencoded .= '&';
}
$context_options = array(
'http'=>array(
'method'=>"POST",
'header'=>"Accept-language: en\r\n" .
"Content-length: " . strlen($urlencoded) . "\r\n" .
"Content-type:application/x-www-form-urlencoded\r\n",
'content'=> $urlencoded)
);
// Make sure the HTTPS options are the same as HTTP
$context_options['https'] = $context_options['http'];
$context = stream_context_create($context_options);
$fp = fopen($url, 'r', false, $context);
// Get the response...
$response = '';
/* For HTTPS, IIS closes the SSL socket improperly hence
* generating a warning. We want to suppress this, as some
* servers will be doing this.
*
* see http://uk.php.net/manual/en/wrappers.http.php
*/
$old_error_reporting = error_reporting();
error_reporting($old_error_reporting & ~E_WARNING);
// Get the headers
$metadata = stream_get_meta_data($fp);
foreach($metadata['wrapper_data'] as $responseheader) {
// Look for the status header...
if (substr($responseheader,0,5) == 'HTTP/') {
$bits = split(' ', $responseheader);
$httpstatus = (int) $bits[1];
$httpstatusmessage = $responseheader;
}
}
// There is no need to check the HTTP status, as fopen wrapper
// that for us anyway.
// Read the the response data
while (!feof($fp)) {
$response .= fread($fp, 8192);
}
fclose($fp);
error_reporting($old_error_reporting);
return $response;
}
Sends a form-encoded HTTP (could be HTTPS) post using the fopen URL wrapper. Tested on PHP 5.2.1
Mark