Reputation: 2055
I have a function which must check basic auth setted credentials, if user exist in file .htgroup and check their password from file .htpasswd and return 0 if no matches 1 if matches.
$password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
$user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
function authenticate($user, $password) {
$AuthUserFile = file(".htpasswd");
$AuthGroupFile = file(".htgroup");
$group = "Members";
if(!preg_grep("/$group: $user$/", $AuthGroupFile)) {
if(!($authUserLine = array_shift(preg_grep("/$user:.*$/", $AuthUserFile)))) {
preg_match("/$user:((..).*)$/", $authUserLine, $matches);
$authPW = $matches[1];
$salt = $matches[2];
$submittedPW = crypt($password, $salt);
if($submittedPW != $authPW) { return 0; } else { return 1; };
} else { return 0; };
}else { return 0; };
}
I got error on if(!($authUserLine = array_shift(preg_grep("/$user:.*$/", $AuthUserFile)))) {
Strict Standards: Only variables should be passed by reference in /var/www/auth.php on line 54
What is wrong?
Upvotes: 1
Views: 2474
Reputation: 21681
As from PHP.net documentation following things can be passed by reference:
- Variables, i.e. foo($a)
- New statements, i.e. foo(new foobar())
- References returned from functions
No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid.
array_shift
is the only parameter is an array passed by reference. The return value of $AuthGroupFile
does not have any reference. Hence the error. You should store the produced value of preg_grep("/$user:.*$/", $AuthUserFile);
to $pregGrap
a variable first. After that use array_sift()
for referencing.
Final code is like :
if(!($authUserLine = array_shift(preg_grep("/$user:.*$/", $AuthUserFile)))) {}
If you're not passing a variable in then there's nothing for a reference to point to.
Thanks!
Upvotes: 1
Reputation: 40919
array_shift needs to have the first argument passed as reference as it needs to updated the array you pass and remove the first element.
In order to make it work, you'll need to store the result of preg_grep in a variable:
$matches = preg_grep("/$user:.*$/", $AuthUserFile);
if(!($authUserLine = array_shift($matches))) {
...
}
Upvotes: 1