How to send HTTPS posts using php
To send an HTTPS POST request using PHP, you can use the curl
extension. The curl_setopt()
function is used to set options for a cURL session, and the curl_exec()
function is used to execute the request. Here is an example of how you can use these functions to send a POST request:
<?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));
Watch a video course
Learn object oriented PHP
Alternatively, you can use the CURL
extension to post the data.
<?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);
$result = curl_exec($curl);
curl_close($curl);
var_dump(json_decode($result, true));
Both example above will send a POST request to the specified URL with the specified data.