curl failing after making site password protected

307 views Asked by At

Recently we made our staging site password protected. This means that if i want to go this mysitestaging.com the browser asks for user/pass. Note that its not a site login. The browser asks for the user/pass

After that a part of my PHP code returns error. Here is the cURl code:

$prefix = GetProtocol().GetDomain();
    $url = $prefix."/ecomm-merged/ajax.php?action=dosomething";

    $url .= "&sid=".$sid;
    $url .= "&sessionid=".$sessionid;

    doLog("Ajax URL: " . $url);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, ‘curl’);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);

    $result = curl_exec($ch);

Here is what i see in my logs:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Unauthorized</title>
<style>
    body {margin: 20px; font-family: helvetica, sans-serif; max-width: 800px;}
    .error {color: #e00;}
    pre {font-size: 16px;}
    h1 {font-size: 28px;}
</style>
</head><body>
<h1>Unauthorized</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>

If i type the URL that i am cURLing to in the browser after entering the user/pass everything work. So how do i address this and add user/pass capability to cURL

1

There are 1 answers

0
Sudhir Bastakoti On BEST ANSWER

As your website is password protected, you need to pass in username and password while doing cURL, using CURLOPT_USERPWD option, like:

...
$your_username = "your-basic-auth-username";
$your_password = "your-basic-auth-password";
$ch = curl_init();
...
curl_setopt($ch, CURLOPT_USERPWD, $your_username . ":" . $your_password);
...
$result = curl_exec($ch);