使用PHP和MySQL在基本但安全的登录系统上遇到麻烦

时间:2013-07-16 07:30:02

标签: php html mysql sql validation

  • 我正在使用Wamp,
    • myown pc as localhost
    • 端口:80
    • 我已经将php脚本的文件保存在通常的默认位置 C:\wamp\www\webservice
    • 我已经为php访问创建了一个配置文件,我已将其命名为 config.inc.php
    • 我使用凭据username=dev, password=root, databasename=webservice
    • 创建了mysql数据库

代码位于此处::

<?php 

    // These variables define the connection information for your MySQL database 
    $username = "dev"; 
    $password = "root"; 
    $host = "localhost"; 
    $dbname = "webservice"; 


    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

    try 
    { 

        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
    } 
    catch(PDOException $ex) 
    { 

        die("Failed to connect to the database: " . $ex->getMessage()); 
    } 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);    
    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) 
    { 
        function undo_magic_quotes_gpc(&$array) 
        { 
            foreach($array as &$value) 
            { 
                if(is_array($value)) 
                { 
                    undo_magic_quotes_gpc($value); 
                } 
                else 
                { 
                    $value = stripslashes($value); 
                } 
            } 
        }      
        undo_magic_quotes_gpc($_POST); 
        undo_magic_quotes_gpc($_GET); 
        undo_magic_quotes_gpc($_COOKIE); 
    } 
    header('Content-Type: text/html; charset=utf-8'); 
    session_start(); 
?>

然后我使用名为register.php

脚本文件创建了一个简单的功能测试

的代码如下:


<?php

require ("config.inc.php");

?>

<h1>Register</h1>
<form action="register.php" method="post">
    Username:<br/>
    <input type="text" name="username" placeholder="user name"><br/>
    Password:<br/>
    <input type="password" name="username" placeholder="user name"><br/>
    <input type="submit" value="Register user"/>
</form>

当我从浏览器http://localhost/webservice/register.php

运行时

我在显示为

的浏览器中收到此错误

无法连接到数据库:SQLSTATE [28000] [1045]拒绝访问用户'dev'@'localhost'(使用密码:是)


请提出任何有关如何克服此问题的建议

1 个答案:

答案 0 :(得分:0)

出于安全原因,请不要使用root。也许用户配置不好。请查看此文档http://dev.mysql.com/doc/refman/5.1/en/create-user.html

此外,我在你的代码中看到session_start()是在脚本结束时调用的,如果之前发生了这样的错误,PHP将打印错误而不启动会话,所以你应该在开头使用它脚本。

希望它有所帮助。