如何使php将每个用户重定向到各自的页面?

问题描述 投票:-1回答:1

好,所以我在这里有一个关于php的小问题。我知道有很多类似的问题,但是我发现的问题没有帮助。我不想使用更多像javascript之类的东西。我设置了mysql,共有3列ID用户名和密码。

   <?php 

$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost","root","");
mysql_select_db("login");
$result = mysql_query("select * from users where username='$username' and password= '$password'") 
or die("failed to query DB".mysql_error());
$row = mysql_fetch_array($result);
if ($row['username'] == $username && $row['password'] == $password) {header(suc.html);
die();}else{header("Location: fail.html");die();}
?>

此代码,它有效,但是当我不填写任何详细信息并也按提交时,它使我进入显示成功登录的suc.html。现在我要进行以下操作:我将使ID类似于每个单独的html名称,然后php将ID编号与目录中的文件名匹配,并显示相应用户的页面。就像说user1。登录userlol密码123 ID user1文件user1.html然后使用要使用的代码,并将ID user1与.html名称匹配,然后将用户重定向到他们自己的自定义页面。有办法吗? Kinda开始使用php,所以请减少一些懈怠:)附言:我知道这些代码是较旧的php代码,但是任何对我个人而言都是有效的方法。

php authentication
1个回答
1
投票

之所以会发生这种情况,是因为未提交用户名和密码时,它们各自的值求值为空,并且SQL查询成功,但返回0行,从而使您的$ row ['username']和$ row [' password']为空。通常,您的$ row ['username'],$ row ['password'],$ username,$ password都等于null,这满足重定向到“ suc.html”的所有要求。

要解决此问题,只需检查mysql_num_rows($ result)== 1,因为通常,由于唯一的用户名,成功的登录将仅返回一行。

但是

我不建议您继续使用不推荐使用的mysql和易受SQL注入攻击的逻辑。请允许我如下重写您的逻辑:
<?php 
$username = $_POST['user'];
$password = $_POST['pass'];
//    You don't have to escape or sanitize user inputs if you use Prepared Statement plus sanitizing user password is highly discouraged.
//    $username = stripcslashes($username);
//    $password = stripcslashes($password);
//    $username = mysql_real_escape_string($username);
//    $password = mysql_real_escape_string($password);

// Initiate a PDO connection and set your error mode to exception.
$conn=new pdo("mysql:host=localhost;dbname=login;","root","",array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

try{
    // Prepare your query and replace all values with ? which would be provided as an array in execute(); I added limit 1 to make sure we are getting a maximum of one row from our query.
    $result_stmt = $conn->prepare("select * from `users` where (`username`=? and `password`=?) limit 1");
    $result_stmt->execute([$username,$password]);
    // fatch() would return a single row just like mysql_fetch_array or mysql_fetch_assoc while fetchAll() would return all rows. 
    $result=$result_stmt->fetch();
    if(count($result)==1){
        // There is no need to check this again because your query to the database already did.
        // if ($row['username'] == $username && $row['password'] == $password) 
        // Redirect users to the same page but identify each user through session (recommended)
        header("location:suc.html");
    }else{
        header("location:fail.html");
    }
}catch(Exception $e){
    echo $e->getMessage();
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.