使用activate.php激活电子邮件

时间:2015-11-03 12:18:07

标签: php

我正在尝试编写注册脚本,用户应该激活他的电子邮件。 所以我有activate.php

逻辑正在md5 hash colomn中将1更改为activated。所以用户可以登录后。

但即使我尝试使用正确的md5 hash激活,我的页面也会显示Wrong activation code.

我看不出有什么不对,没有数据库问题。我查了十次。

有人可以帮我一把吗?

activate.php

<?php require_once('config.php');
try {
    $handler = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {  
     echo $e->getMessage(); 
     die(); 
}

 //The Activation key will always be 32 since it is MD5 Hash
if (isset($_GET['key']) && (strlen($_GET['key']) == 32))
 { $key = $_GET['key']; }

   $search = $handler->query("SELECT activated FROM members WHERE activated='$key'");
   $match  = $search->fetchColumn();

    if($match > 0){ 

 // Update the database to set the "activation" field to 1

 $result = $handler->query("UPDATE members SET activated = 1 WHERE activated='$key' LIMIT 1");

        if($result){
            echo "Activated";       
        }

        else{
            echo "database problem.";
        }

}
        elseif($match == 0){ 
            echo "Wrong activation code.";
        }

?>

当我访问activate.php??key=d85516205a57dcf1cfd228c19e3f3eff时,它不会Activated,而是Wrong activation code.

我哪里错了?

1 个答案:

答案 0 :(得分:2)

安全第一。

使用PDO预处理语句来避免SQL注入。

试试这段代码,让我们看看它是否会起作用。

<?php require_once('config.php');
try {
    $handler = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {  
     echo $e->getMessage(); 
     die(); 
}

//collect value from the url
$key = trim($_GET['key']);

//if key is set, not empty and 32 characters.
if(isset($key) && !empty($key) && (strlen($key) == 32)){

    //update users record set the activated column to "1" where the key value match the one provided in url
    $stmt = $handler->prepare("UPDATE members SET activated = '1' WHERE activated = :key LIMIT 1");
    $stmt->execute(array(
        ':key' => $key
    ));

    //if the row was updated redirect the user
    if($stmt->rowCount() == 1){

        //good news
         echo "Your account is activated."; 
        exit;

    } else {
        echo "Your account could not be activated."; 
    }

} else {
    echo "We need right code to confirm your membership.";
} 
?>