Tags
Asked 2 years ago
9 Jun 2021
Views 198
angeo

angeo posted

HTTP POST sample code in php ?

HTTP POST sample code in php ?
ajamil

ajamil
answered Apr 26 '23 00:00

Here's an example of how to make an HTTP POST request in PHP:

$

url = 'https://example.com/api/create-user';
$data = array(
    'name' => 'John Doe',
    'email' => 'johndoe@example.com',
    'password' => 'password123'
);

$options = array(
    'http' => array(
        '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
} else {
    // Process the response
    echo $result;
}

In this example, we specify the URL to make the POST request to and the data to send in an array. We then create an array of options to specify the headers, method, and content of the request.

We then create a stream context using stream_context_create () and pass the options array as an argument. Finally, we call file_get_contents () with the URL, the false parameter to indicate that we don't need to use a local cache, and the context object to make the POST request.

If file_get_contents () returns false , we handle the error. Otherwise, we process the response as needed. Note that this example assumes that the response will be in the form of plain text. If the response is in a different format, such as JSON, you will need to use an appropriate function to decode the response.
Post Answer