How to send a POST request in PHP?
You can send a POST request in PHP using either the curl or file_get_contents function.
Here is an example code for sending a POST request using curl:
$url = 'http://example.com/post_endpoint';
$data = array('key1' => 'value1', 'key2' => 'value2');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
echo $response;
Here is an example code for sending a POST request using file_get_contents:
$url = 'http://example.com/post_endpoint';
$data = array('key1' => 'value1', 'key2' => 'value2');
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;
In the code example above, the $url variable represents the target URL, while the $data variable represents the data for a POST request. Use either the curl function or file_get_contents function to send the data to the target URL and retrieve the resulting data.