Home > Backend Development > PHP Tutorial > How Can I Send POST Requests and Receive Responses in PHP Using cURL or a cURL-less Approach?

How Can I Send POST Requests and Receive Responses in PHP Using cURL or a cURL-less Approach?

DDD
Release: 2024-12-24 10:53:10
Original
507 people have browsed it

How Can I Send POST Requests and Receive Responses in PHP Using cURL or a cURL-less Approach?

Sending POST Requests with PHP

This guide addresses the issue of sending POST requests in PHP and subsequently reading the returned content. While the target URL exclusively accepts POST methods, this article provides a solution using either cURL or a cURL-less approach.

cURL-less Method

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

// Use key 'http' even if sending 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

For more information on this method and how to add headers, refer to the PHP manual:

  • stream_context_create: 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 Receive Responses in PHP Using cURL or a cURL-less Approach?. 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