What I am trying to do is add a password,username headers to this http get request. Then have the .php page allow the function if the username and password are correct. I have seen a lot of answers concerning headers for basic authorization and posting data. What I am trying to do is add some basic security to this http get request.
data.ts
getData() {
let headers = new Headers({ 'Content-Type':'*/*' });
headers.append('Authorization', 'Basic' + (loginname + ':' + password) );
this.http.get('https:data.php', { headers: headers }, {})
.map(res => res.json())
.subscribe(data => {
console.log(data.data);
},
err => {
this.connectionAlert();
});
}
data.php
<?php
$login = ‘loginname’; // move to lib config
$pass = ‘password’; // move to lib config
if (!isset($_SERVER['PHP_AUTH_PW']!= $pass || $_SERVER['PHP_AUTH_USER'] != $login)) {
header('WWW-Authenticate: Basic realm="My Site"');
header('HTTP/1.0 401 Unauthorized');
echo 'User not allowed';
exit;
} else {
echo "<p>Sucess</p>";
}
?>
My error is
Cannot use isset() on the result of an expression (you can use "null !== expression" instead)
The answers I have found online do not seem to fix the problem.
isset
is used to test if a variable exists, not to compare it to another value. You have to do the comparison as a separate part of your if
statement:
if (
!isset($_SERVER['PHP_AUTH_PW'])
|| $_SERVER['PHP_AUTH_PW'] !== $pass
|| !isset($_SERVER['PHP_AUTH_USER'])
|| $_SERVER['PHP_AUTH_USER'] !== $login
) {
header('WWW-Authenticate: Basic realm="My Site"');
It's always a good idea to check for the existence of a server variable before using it. In this case, the !isset()
checks are necessary if a user visits the page directly in their browser, as the page will be requested at least once before the user has had a chance to enter their username and password in their browser's basic auth dialog. See the PHP manual for more information about isset
.
To ensure secure username and password checking, I suggest using strict comparison !==
operators. Not sure if this is relevant in your use case, but please note that basic auth transmits the username and password in plain text, and is only secure over the internet if used with https.
Also, I had to change the quotes in the first two lines to plain '
characters to be able to test this code:
$login = 'loginname'; // move to lib config
$pass = 'password'; // move to lib config