Submitting a POST HTTP Request with cURL

Your rating: None Average: 5 (3 votes)

Situations exist where you may need, in the middle of a PHP script, to send data to another server and retrieve the response. Accomplishing this is easy to do with GET strings because you can just generate the string needed by hand and call it via file_get_contents() as a URL. (Or even using http_build_query() to help you create your data request.)

However, the situation is not as simple when you need to do a POST. POST commands go to a regular URL, but the data is sent separately as part of the request headers. The regular PHP URL wrappers cannot handle this. Therefore it is easiest to use the PHP cURL extension, which allows for complex interactions with Internet protocols.

Using cURL for HTTP POST Operations

<?php
// Create a function to handle the posting of data
function http_post($url, $post) {
// Initialize a cURL session:
$c = curl_init();

// Set the URL that we are going to talk to:
curl_setopt($c, CURLOPT_URL, $url);

// Now tell cURL that we are doing a POST, and give it the data:
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $post);

// Tell cURL to return the output of the page, instead of echo'ing it:
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);

// Now, execute the request, and return the data that we receive:
return curl_exec($c);
}

// Create some data that we want to send as a post:
$fields = array('data' => 'Jonathan Swift', 'idx' => 5783);

// Actually perform the post to a url:
echo http_post('http://example.com/script.php', http_build_query($fields));
?>

cURL support in PHP relies on the libcurl library. cURL can handle many advanced Internet protocols and is extremely powerful. This is just a small taste of what it can do. To discover more, read the documentation at http://php.net/curl.

 #

nice curl information dude..
keep it up..

 

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.

Cumulus Tag Cloud

Kiran Says

I love work environment which is:

Informal yet professional
Demanding yet rewarding
Challenging yet inspiring
Mediocrity is not an option
Having fun is serious business
Making mistakes is human
Forgiveness is Company Policy

Travelling Sucks