note 102575 deleted from function.file-get-contents by salathe
| From: | salathe@php.net | Date: | Mon, 21 Sep 2020 14:39:46 +0000 |
| Subject: | note 102575 deleted from function.file-get-contents by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-215257@lists.php.net to get a copy of this message | ||
Note Submitter: Stas Trefilov, OpteamIS
----
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
);
}
?>