Not to get too complicated, but if you are doing JSON transfers or POSTs then file_get_contents doesn’t always cut the mustard and you should use curl. Here’s a collection of working functions.
class FileGetContentsURL
{
public static function getJson($strURL)
{
$handleToCURL = curl_init();
curl_setopt($handleToCURL, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($handleToCURL, CURLOPT_URL, $strURL);
curl_setopt($handleToCURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handleToCURL, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($handleToCURL, CURLOPT_TIMEOUT, 10);
curl_setopt($handleToCURL, CURLOPT_POST, false);
$strResponse = curl_exec($handleToCURL);
curl_close($handleToCURL);
return $strResponse;
}
public static function get($strURL,
$arrHeaders = ["Content-type: text/xml;charset=\"utf-8\"", "Accept: text/xml", "Cache-Control: no-cache", "Pragma: no-cache"],
$ynPost = false)
{
$handleToCURL = curl_init();
curl_setopt($handleToCURL, CURLOPT_VERBOSE, false);
curl_setopt($handleToCURL, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($handleToCURL, CURLOPT_URL, $strURL);
curl_setopt($handleToCURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handleToCURL, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($handleToCURL, CURLOPT_TIMEOUT, 10);
curl_setopt($handleToCURL, CURLOPT_POST, $ynPost);
curl_setopt($handleToCURL, CURLOPT_HTTPHEADER, $arrHeaders);
$strResponse = curl_exec($handleToCURL);
curl_close($handleToCURL);
return $strResponse;
}
public static function putJSON($strURL, $strContent)
{
$handleToCURL = curl_init();
curl_setopt($handleToCURL, CURLOPT_VERBOSE, false);
curl_setopt($handleToCURL, CURLOPT_URL, $strURL);
curl_setopt($handleToCURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handleToCURL, CURLOPT_POST, true);
curl_setopt($handleToCURL, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($handleToCURL, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($handleToCURL, CURLOPT_POSTFIELDS, $strContent);
curl_setopt($handleToCURL, CURLOPT_HTTPHEADER, ["Content-type: application/json"]);
$strResponse = curl_exec($handleToCURL);
curl_close($handleToCURL);
return json_decode($strResponse);
}
}