leonam-carlos

request_madbuilder.php

Mar 28th, 2024
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.16 KB | Source Code | 0 0
  1. <?php
  2. function request($url, $method = 'POST', $params = [], $authorization = null)
  3. {
  4.     $ch = curl_init();
  5.    
  6.     if ($method == 'POST' OR $method == 'PUT')
  7.     {
  8.         curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
  9.         curl_setopt($ch, CURLOPT_POST, true);
  10.  
  11.     }
  12.     else if ($method == 'GET' OR $method == 'DELETE')
  13.     {
  14.         $url .= '?'.http_build_query($params);
  15.     }
  16.    
  17.     $defaults = array(
  18.         CURLOPT_URL => $url,
  19.         CURLOPT_CUSTOMREQUEST => $method,
  20.         CURLOPT_RETURNTRANSFER => true,
  21.         CURLOPT_SSL_VERIFYPEER => false,
  22.         CURLOPT_CONNECTTIMEOUT => 10
  23.     );
  24.    
  25.     if (!empty($authorization))
  26.     {
  27.         $defaults[CURLOPT_HTTPHEADER] = ['Authorization: '. $authorization];
  28.     }
  29.    
  30.     curl_setopt_array($ch, $defaults);
  31.     $output = curl_exec ($ch);
  32.    
  33.     curl_close ($ch);
  34.     $return = (array) json_decode($output);
  35.    
  36.     if (json_last_error() !== JSON_ERROR_NONE)
  37.     {
  38.         throw new Exception('Return is not JSON. Check the URL');
  39.     }
  40.     if ($return['status'] == 'error') {
  41.         throw new Exception($return['data']);
  42.     }
  43.     return $return['data'];
  44. }
Add Comment
Please, Sign In to add comment