use Curl to access API with username and password in PHP


This is the sample code but using Curl on cmd :

curl -u {username}:{password}

How do I query it in PHP?


maybe answered on How to use basic authorization in PHP curl
so try from that:


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
curl_close ($ch);

to print or show the json use:

$obj = json_decode($result);
print $obj->{'user'}; 
echo $obj->{'message'}; 

Answered By – Muhammad Dyas Yaskur

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published