Access files in password protected directory using curl


I had to get a page that is in a password protected directory.
First I used php file_get_contents() which is always my first solution for accessing remote pages. But many web servers disable allow_url_fopen in php config. So curl is the ultimate solution.

Curl has an option called CURLOPT_USERPWD that allows to add the user name and password along with the request. A sample code may be as following:


<?php
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, "http://domain/passdprotected/filename");
curl_setopt($curlObj, CURLOPT_USERPWD, "username:password");
curl_exec($curlObj);
curl_close($curlObj);
?>

Hope this helps!!

, , ,

  1. #1 by Anthony Scaife on January 13, 2012 - 8:50 pm

    Thanks. Just what I was looking for. I used it to get at the RSS for my Google bookmarks:

  2. #2 by Anthony Scaife on January 13, 2012 - 8:54 pm

    Sorry, In my last post I included PHP tags. It looks to have broken the comment. So . . .

    Thanks. Just what I was looking for. I used it to get at the RSS for my Google bookmarks:

    $curlObj = curl_init();
    curl_setopt($curlObj, CURLOPT_URL, “https://www.google.com/bookmarks/?output=rss”);
    curl_setopt($curlObj, CURLOPT_USERPWD, “my_account_login_email:my_account_login_password”);
    curl_setopt ($curlObj, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curlObj);
    echo $response;
    curl_close($curlObj);

(will not be published)