DEV Community

Cover image for Curl get and post api in php
Chetan Rohilla
Chetan Rohilla

Posted on • Updated on • Originally published at w3courses.org

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';

$headers =array();

$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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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.

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.


Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please visit my website.

Thanks:)
Happy Coding:)

Top comments (0)