Skip to content
Advertisement

How return http_code 401 with PHP

I’m using cUrl in the client side.

On my webservice (ws.php), i’ve this simple code :

<?php
header('HTTP/1.1 401 Unauthorized', true, 401);
echo 'This is an error';
exit;
?>

When i call this ws.php page, i still have http_code = 200.

Here is my cUrl code is client side :

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "webservice_url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_variables); //array()

$response = curl_exec($ch);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

curl_close($ch);

$code = 200 even i put the header code “401”.

Advertisement

Answer

try this on your ws.php:

<?php
ob_start();
header('HTTP/1.0 401 Unauthorized');
echo 'This is an error';
exit;
?>

Let me know if this works or not ?

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement