webhost

Web hosting

Tuesday, February 21, 2012

HTTP POST Using PHP CURL

Here's how you execute a POST using the PHP CURL library.

//define post values 
$message="test message ";//define post url
 
$url="http://localhost/WebServices/";//encode the message
 
$message = urlencode($message);//initialize the curl
 
$ch = curl_init();

 if (!
$ch){
die(
"Couldn't initialize a cURL handle");
}
//setting options
 
$ret = curl_setopt($ch, CURLOPT_URL,$url);
  
curl_setopt ($ch, CURLOPT_POST, 1);
 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);       
 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);//setup post fields
 
curl_setopt ($ch, CURLOPT_POSTFIELDS,"Message=$message");
 
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//If you are behind proxy then please uncomment below line and provide your proxy ip with port.
// $ret = curl_setopt($ch, CURLOPT_PROXY, "PROXY IP ADDRESS:PORT");

//execute and geting response
 
$curlresponse = curl_exec($ch);

if(
curl_errno($ch))
    echo 
'curl error : '. curl_error($ch);

 if (empty(
$ret)) {
    
// some kind of an error happened
    
die(curl_error($ch));
    
curl_close($ch); // close cURL handler
 
} else {
    
$info = curl_getinfo($ch);
    
curl_close($ch); // close cURL handler
    //echo "<br>";
    
echo $curlresponse;    //echo "post message Sent Succesfully" ;
    
}
 }

No comments:

Post a Comment