Home >Backend Development >PHP Tutorial >How to Send POST Requests and Retrieve Responses in PHP Without cURL?
Sending POST Requests with PHP
When encountering endpoints that only accept POST methods, it can be challenging to access and read the resulting contents. This article explores a practical method for sending POST requests and retrieving the server's response using PHP.
CURL-less Method:
For scenarios where CURL is not a viable option, the following solution utilizing PHP's native file_get_contents() function provides an alternative:
$url = 'http://server.com/path'; $data = ['key1' => 'value1', 'key2' => 'value2']; // Specify HTTP method and headers $options = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data), ], ]; // Create stream context with POST data $context = stream_context_create($options); // Send POST request and retrieve response $result = file_get_contents($url, false, $context); if ($result === false) { // Handle error } var_dump($result);
This approach constructs an HTTP stream context using the provided options and sends a POST request to the specified URL. The server's response is then stored in the $result variable, providing access to its contents for further processing using methods like DOMDocument or file_get_contents().
For additional information on stream context creation and customization, refer to the PHP manual:
The above is the detailed content of How to Send POST Requests and Retrieve Responses in PHP Without cURL?. For more information, please follow other related articles on the PHP Chinese website!