Home > Backend Development > PHP Tutorial > How Can I Send POST Requests and Read the Response Content Using PHP?

How Can I Send POST Requests and Read the Response Content Using PHP?

DDD
Release: 2024-12-23 21:36:14
Original
742 people have browsed it

How Can I Send POST Requests and Read the Response Content Using PHP?

POST Requests with PHP: Reading Response Content

In your query, you express the need to send POST requests and read the subsequent response content using PHP. As GET requests are not accepted by the targeted URL, this article will guide you through the process of utilizing POST methods for this purpose.

Sending POST Requests with PHP

To initiate a POST request, consider employing the following PHP code:

$url = 'http://server.com/path';
$data = ['key1' => 'value1', 'key2' => 'value2'];

// use key 'http' even if you send the request to https://...
$options = [
    'http' => [
        'header' => "Content-type: application/x-www-form-urlencoded\r\n",
        'method' => 'POST',
        'content' => http_build_query($data),
    ],
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
    // Handle error
}

var_dump($result);
Copy after login

This code snippet illustrates how to create a stream context with specified HTTP options, including POST method, data submission, and relevant headers. It then uses the file_get_contents() function to retrieve the response content.

For more detailed information on the nuances of this method and incorporating additional headers, consult the PHP manual page: https://www.php.net/manual/en/function.stream-context-create.php

The above is the detailed content of How Can I Send POST Requests and Read the Response Content Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template