Search code examples
phpfile-get-contents

file_get_content return null for some url


why some url with json content return null on php function get page content?

i used these ways :

  • file_get_content
  • curl
  • http_get

but return null . but when page open with browser json content show on browser ?? anyone can help me?

    $url = 'https://pardakht.cafebazaar.ir/devapi/v2/api/validate/com.pdgroup.insta/inapp/coin_follow_1/purchases/324234235/?access_token=9IaRpdmQzFppJMabLHbHyzBaQnm8bM';
$result = file_get_content($url);

return null but in browser show

{"error_description": "Access token has expired.", "error": "invalid_credentials"}

Solution

  • It returns the following: failed to open stream: HTTP request failed! HTTP/1.1 401 UNAUTHORIZED

    So, you have to be authorized.

    You ca play with this code snippet (I can't test since token expired again):

    <?php
    $access_token = "s9spZax2Xrj5g5bFZMJZShbMrEVjIo"; // use your actual token
    $url = "https://pardakht.cafebazaar.ir/devapi/v2/api/validate/com.pdgroup.insta/inapp/coin_follow_1/purchases/324234235/";
    
    // Solution with file_get_contents
    // $content = file_get_contents($url . "?access_token=" . $access_token);
    // echo $content;
    
    // Solution with CURL
    $headers = array(
        "Accept: application/json",
        "Content-Type: application/json",
        "Authorization: Basic " . $access_token
    );
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, $url); //  . $params - if you need some params
    curl_setopt($ch, CURLOPT_POST, false);
    // curl_setopt($ch, CURLOPT_USERPWD, $userPwd);
    
    $result = curl_exec($ch);
    $ch_error = curl_error($ch);
    $info = curl_getinfo($ch);
    
    curl_close($ch);
    
    if ($ch_error) {
        throw new Exception("cURL Error: " . $ch_error);
    }
    
    if ($info["http_code"] !== 200) {
        throw new Exception("HTTP/1.1 " . $info["http_code"]);
    }
    
    echo $result;