How to Post Data with cURL in PHP

Posted by Mike Lopez under PHP cURL
May 2008
20
12:10pm

Do you need to post data to a website using PHP? It’s actually pretty easy to do. Here’s the code.

<?php
$urltopost = "http://somewebsite.com/script.php";
$datatopost = array (
"firstname" => "Mike",
"lastname" => "Lopez",
"email" => "my@email.com",
);

$ch = curl_init ($urltopost);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec ($ch);
?>

And what happened? Here’s my quick explanation.

$urltopost

The url where you want to post your data to

$datatopost

The post data as an associative array. The keys are the post variables

$ch = curl_init ($urltopost);

Initializes cURL

curl_setopt ($ch, CURLOPT_POST, true);

Tells cURL that we want to send post data

curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);

Tells cURL what are post data is

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

Tells cURL to return the output of the post

$returndata = curl_exec ($ch);

Executes the cURL and saves theoutput in $returndata

There ya go! If you have questions, just ask in our forum.


Share this Post through Social Bookmarking These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • StumbleUpon
  • Technorati
  • YahooMyWeb

Related Posts

Tags: ,

Leave a Reply