Access URL restricted with .htpasswd in PHP with cURL

Tech Bandhu

We are used to accessing external web application or web services using cURL in PHP for information exchange. bellow is the code for that,

<?php
$url = "xyz.com";
// initiate curl resource 
$ch = curl_init();
// set url to be read
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
//$output contains the output in string 
$output = curl_exec($ch); 
//close curl resource to free up system resources
curl_close($ch);
?>

Some time (mostly on development / staging server) we need to access URLs or files which are protected by .htpasswd. Just with the above code We can not access such URLs.

To access such file or URL which is protected by .htpasswd, we need to pass its user name and password with bellow code,

$username = "testuser"; $password = "testpass"; $url = "xyz.com"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERPWD, “$username:$password”); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1)…

View original post 4 more words

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s