Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the HTTP-Code for a .htpasswd-protected url using cURL?

Tags:

php

curl

I'm trying to access a protected site (.htpasswd) with curl to check if its reachable and returns a code like 200 or 302.

I tried to access it with a wrong password and username. I don't want to login, i just want to check if it's online/reachable.

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "aaa:bbb");

How do i get the 401 code via curl?

Im' checking the http-code like this, but in the htpasswd, it is empty

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE),true

Thank you in advance!

like image 221
Marcus Avatar asked Dec 05 '25 14:12

Marcus


1 Answers

You can get the Status Code from the curl if you use CURLINFO_HTTP_CODE attribute in curl_getinfo function like this:

<?php
$URL = 'http://yourdomain.com/protected_dir';
$Auth_Username = "username_here";
$Auth_Password = "password_here";

//make curl request
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_USERPWD, "{$Auth_Username}:{$Auth_Password}");  

$Output = curl_exec($ch);

//get http code
$HTTP_Code = curl_getinfo($ch, CURLINFO_HTTP_CODE);    //this is important to get the http code.
curl_close($ch);

echo 'HTTP code: ' . $HTTP_Code;
?>
like image 134
Ghulam Ali Avatar answered Dec 08 '25 02:12

Ghulam Ali