在表单散列后使用PHP重定向脚本

时间:2013-05-11 13:58:13

标签: php

我刚开始使用PHP进行编码,而且我一直坚持使用重定向。我已经从提交的表单中接受了$ _POST信息并将其分配给变量。我收到2个密码变量:$ password和$ c_password。我的目的是检查这两个密码是否匹配,如果它们我想要哈希它们。如果不是,我想将用户(重定向)发送回register.php页面。问题是如果我阻止javascript重定向下的所有内容,它就可以了。但是如果我在js重定向之后没有阻止脚本,则用户在数据库上注册并被重定向到login.php页面。这是我到目前为止所编码的内容:

<?php

// Open database connection
include 'db_connect.php';

// check existence and accept form data
if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['c_password'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$c_password = $_POST['c_password'];
}

// Hash the password if password and c_password match
if(strcmp($password, $c_password) == 0) {
$password = hash('sha512',$_POST['password']);
} 
else { ?>
    <script type="text/javascript">
        document.location = './register.php?pass_nomatch=1';
    </script>
<?php
}

// Create a random salt
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));

// Create salted password (Careful not to over season)
$password = hash('sha512', $password.$random_salt);

// Add your insert to database script here. 
// Make sure you use prepared statements!
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {    
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt); 
// Execute the prepared query.
$insert_stmt->execute();
// Close MYSQL database connection
mysqli_close($mysqli);
// Redirect user to login page
header('Location: ./login.php');
}

?>

如果有人对我的问题有答案,请尽快回复:)

2 个答案:

答案 0 :(得分:1)

只需使用:

header('Location: http://www.yoursite.com/page.php');

然后暂停脚本:

die();

这将保证脚本停止。

答案 1 :(得分:0)

要在PHP中重定向页面,您可以使用内置函数header();

ex:header('Location: http://www.yoursite.com/page.php')

请记住,将绝对路径作为参数添加到标题中非常重要。这就是Wikipedia: HTTP_location的原因。

  

互联网标准要求绝对URI跟随位置   标题,这意味着它必须包含一个方案[4](例如,http:,https:,   telnet:,mailto:)[5]并且符合特定于方案的语法和   语义。例如,HTTP方案特定的语法和语义   对于HTTP URL,需要“主机”(Web服务器地址)和“绝对”   path“,带有”port“和”query“的可选组件。在这种情况下   如果没有绝对路径,则必须以“/”表示   用作资源的请求URI。[6]

现在,匹配密码应该很简单,如:

if($passwordA === $passwordB) {
    // === is called, identity comparison operator. 
   // http://www.php.net/manual/en/language.operators.comparison.php

else{ 
    header('Location: http://site.com/register.php?pass_nomatch=1');
    die("If you are not redirected in 5 seconds, click <a href='#'>here<a/> ");
  }