PHP how to make post request

Learn how to make POST requests in PHP with an example. Explore the different methods and parameters used to send data to a server.

Making a POST Request in PHP

PHP is a scripting language used to create dynamic web pages. It is server-side, meaning that the code is run on the server and the output is sent to the user's web browser. In order to make a POST request in PHP, the cURL library can be used. cURL is a library that enables a script to transfer data using various protocols, such as HTTP, FTP, and so on.

To make a POST request, the following code can be used:


$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://example.com/post-request.php",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => array('data'=>'value'),
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/x-www-form-urlencoded"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

In the above code, the cURL library is initialized and then the cURL options are set. The CURLOPT_URL option sets the URL of the request, in this case http://example.com/post-request.php. The CURLOPT_RETURNTRANSFER option is set to true, meaning that the response will be returned as a string. The CURLOPT_POSTFIELDS option is set to an array of data that will be sent in the request. The CURLOPT_HTTPHEADER option is set to an array of HTTP headers that will be sent in the request. Finally, the response is retrieved and echoed out.

This code can be used to make a POST request in PHP, sending data to a server. This can be used for many purposes, such as submitting a form, uploading a file, and so on.

Answers (0)