Skip to content
Advertisement

PHP, cURL request not fetching data

I want to get some informations through github API, i tried to use file_get_contents and it does not seem to work, so i moved to cURL, it does not give an error but it’s not returning anything

PHP code :

if (!empty($_POST["username"])) {
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.github.com/users/".$_POST["username"]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output=curl_exec($ch);
        print_r($output);
        curl_close($ch);
    }

I checked the http code with CURLINFO_HTTP_CODE and its set to 0. is there any fix that i can get the json data when requesting.

Advertisement

Answer

I have tried accessing the same URL using curl in php and it seems to work fine. Checkout the following example:

<form method="post">
    <input type="text" name="username">
    <button>Submit</button>
</form>

<?php
if (!empty($_POST["username"])) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.github.com/users/".$_POST["username"]);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $output = curl_exec($ch);
    curl_close($ch);
    print_r($output);
}
?>

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement