Search code examples
phprestdebuggingcurlget

How to debug a get request in php using curl


I'm trying to make a get request in php using curl. This is what I'm doing:

$curl = curl_init();

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($curl);
curl_close($curl);

printf($result);

But $result doesn't print out anything, no success or failure message. I've successfully reached the endpoint via postman and in a web browser so I know it works. Printing out $curl prints: "Resource #1" which makes me think curl is properly installed on the server.

I'm not sure what steps to take next to make things work.


Solution

  • Add a few more option for troubleshooting purposes.

    Check for an error response.

    If no error, get the details:

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT,10);
    curl_setopt($ch, CURLOPT_FAILONERROR,true);
    curl_setopt($ch, CURLOPT_ENCODING,"");
    
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    
    $data = curl_exec($ch);
    if (curl_errno($ch)){
        $data .= 'Retreive Base Page Error: ' . curl_error($ch);
    }
    else {
      $skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE)); 
      $head = substr($data,0,$skip);
      $data = substr($data,$skip);
      $info = curl_getinfo($ch);
      $info = var_export($info,true);
    }
    echo $head;
    echo $info;