Last active
September 15, 2017 12:49
-
-
Save Bizunow/e06817728a3d1180628ce9bfd91277b6 to your computer and use it in GitHub Desktop.
[PHP Curl] Simple helper for create GET and POST requests. Always return JSON. #php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CurlHelper | |
{ | |
static function get($url, $params = [], $timeout = 60) | |
{ | |
$paramsJoined = array(); | |
foreach($params as $param => $value) { | |
$paramsJoined[] = "$param=$value"; | |
} | |
$query = implode('&', $paramsJoined); | |
$curl = curl_init(); | |
curl_setopt($curl,CURLOPT_URL, $url . ($query ? '?' . $query : '')); | |
curl_setopt($curl,CURLOPT_TIMEOUT, $timeout); | |
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); | |
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true); | |
curl_setopt($curl, CURLOPT_MAXREDIRS, 15); | |
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); | |
$result = curl_exec($curl); | |
$result = curl_errno($curl) ? null : json_decode($result); | |
curl_close($curl); | |
return $result; | |
} | |
static function post($url, $params, $timeout = 60, $isJson = false) | |
{ | |
$curl = curl_init(); | |
curl_setopt($curl,CURLOPT_URL, $url); | |
curl_setopt($curl,CURLOPT_TIMEOUT, $timeout); | |
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); | |
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true); | |
curl_setopt($curl, CURLOPT_POST, true); | |
curl_setopt($curl, CURLOPT_POSTFIELDS, $isJson ? json_encode($params) : http_build_query($params)); | |
curl_setopt($curl, CURLOPT_MAXREDIRS, 15); | |
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); | |
$result = curl_exec($curl); | |
$result = curl_errno($curl) ? null : json_decode($result); | |
curl_close($curl); | |
return $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment