How to Post Data with cURL in PHP

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",
);

<span id="more-40"></span>

$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.

 
May 20th, 2008
PHP cURL
Tags: ,

2 Responses to “How to Post Data with cURL in PHP”

  1. [...] $returndata = curl_exec ($ch); Executes the cURL and saves theoutput in $returndataThanks a lot http://coderscult.com    [...]

  2. Ravi khoda says:

    I am having some problem for fetching data from server in XML format using php Curl method.
    $urltopost = “https://httpapi.com/api/domains/available.xml”;
    $datatopost = array (
    “auth-userid” => “123456″,
    “auth-password” => “abc@xyz”,
    “domain-name” => “ravikhoda”,
    “tlds” => “com”,
    “suggest-alternative” => “true”,
    );
    I am trying to get XML data from server but not any kind of response. So, plz help me to solve this query.