Thursday, October 24, 2013

PHP Function to send post using CURL

This is one of my PHP snippet collection. This function can performs post request with parameters set. I have used this function for sending request to several API servers and so far it works as well as I need. May be you need to add curl_setopt based on your needs.

The Snippet:
<?php 
function curl_post($url,$params) {
  $parse_url = parse_url($url);
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$url);
  curl_setopt($ch, CURLOPT_TIMEOUT,60);
  curl_setopt($ch, CURLOPT_POST,1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  if($parse_url['scheme'] == 'https') {
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  }
  $result = curl_exec($ch);
  curl_close ($ch);
  return $result;
}
?>

Usage

Below is just example usage to work with API service.

<?php
$url = 'https://api.server.example.com/post.php';
 
// you need to set post parameters
$params = Array(
    'app_id'       => $app_id,
    'app_secret'   => $app_secret,
    'message'      => $message
);

$result = curl_post($url,$params);

?>

No comments :

Post a Comment