user77413
user77413

Reputation: 31245

Need help with libcurl username/password authentication

I'm trying to access a secure webpage on one of our servers. The webpage is inside a .htaccess protected directory that requires a username and password. I'm trying to get libcurl to submit the authentication request so it can access the file. After finding some guidance in various places, I've come up with what I believe should work, but it doesn't.

$url="https://www.myurl.com/htaccess_secured_directory/file.php";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_USERPWD, 'myusername:mypassword');
$result = curl_exec($ch);
echo $result;

The file.php file should simply echo "Hello World!", but the $result variable is coming up blank. Is there a way to get error messages back from curl? Am I doing something wrong? I've also used CURLLAUTH_ALL without success, but I believe I just have basic authorization anyway.

Upvotes: 2

Views: 3571

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598134

Use curl_errno() and curl_error() to retrieve error information, ie:

$url="https://www.myurl.com/htaccess_secured_directory/file.php";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_USERPWD, 'myusername:mypassword');
$result = curl_exec($ch);

if(curl_errno($ch))
{
  echo 'Curl error: ' . curl_error($ch);
}
else
{    
  echo $result;
}

curl_close($ch);

The available error codes are documented here.

Upvotes: 2

Related Questions