Mysql用户身份验证不起作用

时间:2014-11-18 01:11:12

标签: php mysql .htaccess cgi authentication

我正在使用一些php + mysql并进行用户身份验证。我实现了这个:

<?php

    if (!isset($_SERVER['PHP_AUTH_USER']))
    {
            header('WWW-Authenticate: Basic realm="Administrator"');
            header('HTTP/1.0 401 Unauthorized');
            echo  'Username and password are required to view this page';
            exit;
    }
    else
    {
            if(isset($_ENV["OPENSHIFT_MYSQL_DB_HOST"]))
            {

                    $conn = mysql_connect($_ENV["OPENSHIFT_MYSQL_DB_HOST"].':'.$_ENV["OPENSHIFT_MYSQL_DB_PORT"],
                                          $_ENV["OPENSHIFT_MYSQL_DB_USERNAME"],
                                          $_ENV["OPENSHIFT_MYSQL_DB_PASSWORD"]) or die(mysql_error());
            }
            else
            {
                    $conn = mysql_connect("localhost", "user", "pass") or die(mysql_error());
            }
            mysql_select_db("db", $conn) or die(mysql_error());
            $sqlquery = "SELECT * FROM admin_users";
            $result = mysql_query($sqlquery, $conn) or die(mysql_error());
            $access_granted = 0;
            while($user = mysql_fetch_array($result))
            {
                    if ($_SERVER['PHP_AUTH_USER'] == $user['user_name'] &&
                        $_SERVER['PHP_AUTH_PW'] == $user['password'])
                    {
                            $access_granted++;
                    }
            }
            if(!$access_granted)
            {
                    header('WWW-Authenticate: Basic realm="Administrator"');
                    header('HTTP/1.0 401 Unauthorized');
                    echo "Invalid username and/or password";
                    exit;
            }
    }
?>

用户,通行证,表格等都是正确的但是它没有正常工作,没有重定向但也没有错误

我做错了吗?

1 个答案:

答案 0 :(得分:0)

问题是关于我的基于CGI的服务器及其处理头部认证的方式

将此添加到.htaccess中解决了问题

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>