Example of using CURL to GET a response
$Url = "mydomain.org/somefile.php?MyParameter1=abc&MyParameter2=2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_HTTPGET, true); //You don't have to include this for it to work as GET
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //Follow any page redirects etc (optional)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //<<<Include this for the output of curl to go to the curl_exec() output below instead of the browser screen
$CurlResult= curl_exec($ch);
$HttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($HttpCode !== 200)
die("Curl request failed, HTTP status code: $HttpCode");
//If your output is json then you can decode it with this:
$DecodedJson = json_decode($CurlResult);
echo "CurlResult: ";
print_r($CurlResult);
echo "<br>DecodedJson: ";
print_r($DecodedJson);
GET with query parameters loaded as an array
They are still added to the URL, but this method lets you load them as an array
$QueryParameters = [
'param1' => 'value1',
'param2' => 'value2'
];
$Url = "mydomain.org/somefile.php";
$Url .= '?' . http_build_query($QueryParameters); //Append query parameters to URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_HTTPGET, true); //You don't have to include this for it to work as GET
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //Follow any page redirects etc (optional)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //<<<Include this for the output of curl to go to the curl_exec() output below instead of the browser screen
$CurlResult= curl_exec($ch);
$HttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($HttpCode !== 200)
die("Curl request failed, HTTP status code: $HttpCode");
//If your output is json then you can decode it with this:
$DecodedJson = json_decode($CurlResult);
echo "CurlResult: ";
print_r($CurlResult);
echo "<br>DecodedJson: ";
print_r($DecodedJson);
Add header fields
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//For multiple entires use this instead:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "Token:$MyAcccessToken"));
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through resources like this. We hope you find it helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support here. If you need help with a problem please use one of the many online forums.