0

name私は長年の MySQL ユーザーで、最近 PHP 5.5 にアップグレードし、PDO に基づいて新しい Web サイトを構築することにしました。インジェクションによるセキュリティに非常に関心があり、PDO 開発に mysql_real_escape が手元にないので、コード インジェクションは安全なのだろうか?

これが私のテストスクリプトです、ありがとう!

<?php
try {
  $DB = new PDO("mysql:host=localhost;dbname=dbtest", "dbtest", "TbhPXM!Wv9sz");
  $DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}  
catch(PDOException $e) {  
    echo "<div style='text-align: center; margin-top: 100px; font-size: 21px; font-weight: bold;'>Damn, your experiencing technical issues with our website. An administrator has been notified and will address the issue shortly.<br /><br />T_T</div>";  
    file_put_contents('error.txt', $e->getMessage()."\n", FILE_APPEND);  
}

if (isset($_POST['RegUser']) && isset($_POST['Username']) && isset($_POST['Password'])) {
    try { 
    $stmt = $DB->prepare("INSERT INTO users (name, pass) VALUES (:name, :pass)");
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':pass', $pass);
    $name = $_POST['Username'];
    $options = ['cost' => 12,'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),];
    $pass = password_hash($_POST['Password'], PASSWORD_BCRYPT, $options)."\n";
    $stmt->execute();
    }
    catch(PDOException $e) {
        echo "Registration Failed, Try another username.";
    }
}

if (isset($_POST['Login']) && isset($_POST['Username']) && isset($_POST['Password'])) {

    $name = $_POST['Username'];
    $STH = $DB->prepare('SELECT name, pass from users where name=:name LIMIT 0,1');
    $STH->bindParam(':name', $name);
    $STH->execute();
    $STH->setFetchMode(PDO::FETCH_ASSOC);
    if ($STH->rowCount() == 1) {
        while($row = $STH->fetch()) {  
            $hash = $row['pass'];
            if (password_verify($_POST['Password'], $hash)) {
                echo 'Password is valid!';
                session_start();
                $_SESSION['logged'] = true;
                $_SESSION['name'] = $row['name'];
                $_SESSION['pass'] = $row['pass'];
            } else {
                echo 'Invalid password.';
            }  
        }
    } else {
        echo "User Not Found!";
    }

}
?>
<form action="index.php" method="post" target="_self" enctype="multipart/form-data">
<input type="text" placeholder="Username" size="40" name="Username" /><br />
<input type="text" placeholder="Password" size="40" name="Password" /><br />
<input type="submit" value="Register" name="RegUser" />
</form><br />
<form action="index.php" method="post" target="_self" enctype="multipart/form-data">
<input type="text" placeholder="Username" size="40" name="Username" /><br />
<input type="text" placeholder="Password" size="40" name="Password" /><br />
<input type="submit" value="Login" name="Login" />
</form>
<?php

if (isset($_SESSION)) {
    var_dump($_SESSION);
}

if (isset($_SESSION['logged']) && $_SESSION['logged'] == true) {
    echo "Hey ".$_SESSION['name'].", Welcome back!";
}

$DB = null;
4

1 に答える 1