top of page

REST API (POST/GET/PUT/DELETE) in php

  • Writer: سُلَيْمَان بْن دَاوُوْد
    سُلَيْمَان بْن دَاوُوْد
  • Jun 21, 2020
  • 1 min read

Create a POST Request


$postdata = array('name'=>'Hosting Transfer','price'=> '250');
$data_json = json_encode($postdata);


$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("admin:1234") ,
    'Content-Length: ' . strlen($data_json)
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://pms.com/api/product');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

echo '<pre>'; print_r($response);*

Create a PUT request

$postdata = array('name'=>'Wpengine Hosting Transfer','price'=> '250');

$data_json = json_encode($postdata); 

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("admin:1234") ,
    'Content-Length: ' . strlen($data_json)
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://pms.com/api/product/2');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

echo '<pre>'; print_r($response);

Create a DELETE request

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("admin:1234")
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://pms.com/api/product/4');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

echo '<pre>'; print_r($response);

Create a GET request

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("admin:1234") 
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://pms.com/api/product');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);

echo '<pre>'; print_r(json_decode($output));

Recent Posts

See All
Get User IP Address in PHP

public static function function get_client_ip() { $ipaddress = ''; if (getenv('HTTP_CLIENT_IP')) $ipaddress =...

 
 
 

Comments


© 2020 by syednazrulhassan

bottom of page