[英]Every entered username and password works in PHP login
我的php代碼有問題。 我想制作一個從數據庫獲取用戶名和密碼的登錄系統。 我幾乎使一切正常。 但是有一個問題..當您輸入名稱和密碼/沒關系時,甚至是random /都會登錄我並將我重定向到我想要的地方。 如何解決該問題並使其僅使用數據庫中正確的用戶名和密碼? 我將在此處導入我的登錄代碼文件。 在此先感謝您,我的英語很抱歉。
<?php
include 'dbh.php';
$uid = $_POST['uid'];
$pwd = $_POST['uid'];
$query = "SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
$result = mysqli_query($conn, $query);
if ($result = mysqli_query($conn, $query))
{
while ($row = mysqli_fetch_assoc($result))
{
printf("Login success\n");
}
// If the while loop fails, password/username combo was incorrect
printf("Login failed - Invalid username or password.");
} else {
printf("Login failed, could not query the database.\n");
}
header("Location: panel.php");
?>
$sql="SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
if ($result=mysqli_query($con,$sql))
{
if (mysqli_num_rows($result)!=0) {
printf("Login success\n");
}else{
printf("Login failed - Invalid username or password.");
}
mysqli_free_result($result);
}
首先,您對SQL注入非常開放,您將需要對其進行更新。 它覆蓋在噸的其他地方,查找它。
但是要解決您的問題,無論您進行何種檢查,都將進行重定向。 將其移動到您的while循環中:
while ($row = mysqli_fetch_assoc($result))
{
printf("Login success\n");
header("Location: panel.php");
}
將其置於底部意味着無論如何都會被解雇。
嘗試這個
<?php
function Db(){
$host = "localhost"; // your db settings
$username = "yourusername";
$password = "yourpass";
$db = "users";
$conn = new mysqli($host, $username, $password, $db);
// use mysqli instead mysql_connect, it is outdated I guess
if(!$conn){
die("Could not connect");
}
}
if(isset($_POST['login'])){
$uid = trim($_POST['username']);
$pwd = trim($_POST['password']);
if($uid == ""){
$err[] = "Username is missing.";
}elseif($pwd == ""){
$err[] = "Password is missing.";
}else{ // When validation succeed then make query.
$db = Db();
$uid = $db->real_escape_string($uid); // escape strings from mysql injection
$pwd = $db->real_escape_string($pwd);
$sql = "SELECT * FROM users
WHERE username = '$uid'
AND password = '$pwd'";
$result = $db->query($sql);
if($result->num_rows == 1){
header("location:panel.php"); // login succeed
}else{
$err[] = "Username or password are incorrect";
header("location:login.php"); // login failed
}
}
}
?>
<?php
if(isset($err)):
foreach($err as $loginErr):
echo $loginErr; // Print login errors.
endforeach;
endif;
?>
<!-- HTML login form goes here -->
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.