How to run curl get and post api in php?

PHP

Today we will teach you how to run curl get and post api in php.

Modern websites is using APIs for many purposes. Like for sending SMS, for sending EMAILs, for cloud storage, for mobile app APIs, for payment gateways. And also for integrating some native features of mobile apps or websites.

You can run easily your API using php module CURL. And it is almost available for all servers localhost or global servers.

There are two types of mostly used API methods GET and POST. Some others are PUT, PATCH, UPDATE, DELETE. But you can run your application by using these two GET or POST methods.

If you want to run GET Method API then you can use the code given below.

        $url = 'https://apiprovider.com'; // this is your api url

        $headers =array(); 
 // these are your api headers

	$headers[] = 'X-Authorization-Token:fgfdg4545hKUertefgdds';

	$ch = curl_init();

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_URL,$url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	$results=curl_exec($ch);

	curl_close($ch);

If you want to run POST Method API then you can use the code given below.

        $headers =array(); 

	$headers[] = 'X-Authorization-Token:fghjfj4erJGFDgwrhgfhgfh';

	$ch = curl_init();

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_URL,$url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	curl_setopt($ch, CURLOPT_POST, 1);

	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

	$search_results=curl_exec($ch);

	curl_close($ch);

	return $search_results;

In the both code above $url is your API Url, $headers is your API headers, $data is your array post data passing to API and $results is your API results or output. So, just use this code and follow your API provider’s documentation.

That’s it you can learnt how to run curl get and post api in php. Now using these codes, you can run CURL in php, run SMS API in php, run Email API in php, run Payment Gateway API in php, run Google API in php, run Cloud API in php, run AWS API in php, run WordPress API in php and also Image Manipulation API in php.

And also you can use this code for any PHP framework like Laravel, Cakephp, Codeigniter or php based CMS like WordPress, Magento, Joomla etc.

This method is also helpful to run REST API in php, XML API in php or JSON API in php.

That’s it If you want more tutorials and tricks about PHP then visit our PHP Page and for other tutorials or codes visit ReadyMadeCode regularly or subscribe for email updates and follow us on facebooktwittertumblrlinkdedin and if you like this article then share this.