PHP Curl POST and GET Methods

PHP Curl POST and GET Methods

In this tutorial, we will see how to send data to web services using PHP Curl with Get and Post method.

Whenever we need to send data to API in PHP ,then we use curl for it.

During data sending to the API, we can either use GET or POST method depends on the API.

This article will help you to understand about how to use PHP Curl POST and GET method.

Let’s us see snippet.

PHP Curl POST Method

<?php
function apicurlconnect($apiurl,$postparameter){

		$url= $apiurl;
		$api_request= $postparameter;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url); //using the setopt function to send request to the url
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //response returned but stored not displayed in browser
		curl_setopt($ch, CURLOPT_TIMEOUT, 100); 
		
		curl_setopt($ch, CURLOPT_POST, true); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $api_request); 
		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
		$result = curl_exec($ch); //executing request
		$err = curl_error($ch); 
		
		curl_close ($ch); //terminate curl handler
		
		if ($err) {
        echo "cURL Error #:" . $err;
    }  else {
        return $result; //display response	
    }		
	}
?>	 
To send data to API Using PHP Curl with Post method simply call above function and pass url as first param and post parameter as second param.
   <?php
	  $url = "https://www.website.com/ws";
	
	  $postparam = array( 
			'mobile'   => "aaaa", 
			'api_token'=> "bbbb"
		);
		
	 $api_response = apicurlconnect($url,$postparam);
	 ?> 

PHP Curl GET Method

<?php
function getapicurlconnect($apiurl,$getparameter){

		$url= $apiurl;
		
                $params = http_build_query($getparameter);
                
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url."?".$params); //using the setopt function to send request to the url
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //response returned but stored not displayed in browser
		curl_setopt($ch, CURLOPT_TIMEOUT, 1000); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
	        $result = curl_exec($ch); //executing request
		$err = curl_error($ch);
		
		curl_close ($ch); //terminate curl handler
		
		if ($err) {
        echo "cURL Error #:" . $err;
    }  else {
        return $result; //display response	
    }	
	}

?> 
To send data to API Using PHP Curl with GET method simply call above function and pass url as first param and get parameter as second param.
<?php
	  $url = "https://www.website.com/ws";
	
	  $getparam = array( 
			'mobile'   => "aaaa", 
			'api_token'=> "bbbb"
		);
		
	 $api_response = getapicurlconnect($url,$getparam);
	 ?> 

If find this article helpful, please share with your friends.

Leave a Reply

Your email address will not be published. Required fields are marked *