PHP cURL :How to make POST Request to URL

| | 1 min read

By default, all HTTP requests made out by cURL are GET requests. It simply fetches the URL and doesn't submit any POST variables. However, if we need to fetch and retrieve URL by the POST method with cURL, you will need the snippet below:

Here, we will be setting CURLOPT_POST to true and sending an array of data through with the setting CURLOPT_POSTFIELDS.

  $url = 'http://www.example.com/submit.php';  
  // The submitted form data, encoded as query-string-style
  // name-value pairs
  $body = 'name=uttam&lastname=kotekar'; 
  // Get cURL resource
  $c = curl_init ($url);
  curl_setopt ($c, CURLOPT_POST, true);
  curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
  // CURLOPT_RETURNTRANSFER returns the response as a string instead of outputting it to the screen
  curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
  $page = curl_exec ($c);
  curl_close ($c);

I hope this article helps you :-).