W3docs

How to send HTTPS posts using php

To send an HTTPS POST request using PHP, you can use the curl extension.

To send an HTTPS POST request using PHP, you can use the built-in stream context functions or the curl extension. Here is an example using file_get_contents() with a stream context:

Example of sending HTTPS posts using php

<?php

$url = 'https://jsonplaceholder.typicode.com/posts';
$data = ['key1' => 'value1', 'key2' => 'value2'];

$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(json_decode($result, true));

Note: The allow_url_fopen directive must be enabled in php.ini for this method to work.

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

Alternatively, you can use the curl extension to post the data.

Example of sending HTTPS posts using PHP cURL

<?php

$url = 'https://jsonplaceholder.typicode.com/posts';
$data = ['key1' => 'value1', 'key2' => 'value2'];

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
$result = curl_exec($curl);
if ($result === false) {
  /* Handle error: curl_error($curl) */
}
curl_close($curl);

var_dump(json_decode($result, true));

Both examples above will send a POST request to the specified URL with the specified data.