PHP CURL The Basics
Getting started;
Before getting started with curl and php we must ensure that we have the extension installed.
package name on linux is php-curl;
Now we can use php-curl in our php code, like this for a simple GET call;
<?php 
// URL requested
$url = 'http://www.yourdomain.com/endpoint';
// Initializing curl request
$ch = curl_init( $url );
// Configuring curl options
$options = array(
    CURLOPT_RETURNTRANSFER => true
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results by executing the curl request.
$result = curl_exec($ch);
// dump the content 
var_dump($result); 
Posting to an endpoint using php-curl
There are situations where you may need to post some type of data into an endpoint which may or maynot be protected by authentication, here is a simple example that cover this situation.
<?php
// JSON URL requested
$json_url = ‘http://www.yourdomain.com/json_script.json’;
// Initializing curl request
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
    CURLOPT_RETURNTRANSFER => true,
    // authentication
    CURLOPT_USERPWD => $username . “:” . $password,
    // setting the headers for the data to be posted to json
    CURLOPT_HTTPHEADER => array(‘Content-type: application/json’) ,
    CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Executing the request and get the response to result
// Getting JSON result as string
$result = curl_exec($ch);
// converting the json response to type array 
$responseArray = json_decode($result, true);
Uploading file using curl
<?php
$curl = curl_init();
$data = file_get_contents('test.png');
curl_setopt_array($curl, array(
  CURLOPT_URL => "http://woo.dev/wp-json/wp/v2/media",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_HTTPHEADER => array(
    "authorization: Basic XxxxxxxXxxxxXx=",
    "cache-control: no-cache",
    "content-disposition: attachment; filename=test.png",
    "content-type: image/png",
  ),
  CURLOPT_POSTFIELDS => $data,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
Comments
Post a Comment