본문 바로가기
MySql

MySQL PHP-잘못된 사용자 이름 / 암호-올바르게 에코하는 방법

by 베이스 공부 2020. 11. 23.
반응형

PHP로 로그인 양식을 코딩하려고합니다. 로그인 / 로그 아웃은 잘 작동하지만 특정 코드에 대해 "잘못된 사용자 이름 / 암호"를 표시하는 적절한 방법이 궁금합니다.

다음은 내 코드입니다 (사이드 바의 index.php에 포함 된 login.php에서) :

<form method="post" action="security.php">
<input name="username" type="text" placeholder="Username" id="username"><br />
<input name="password" type="password" placeholder="Password" id="password"><br />
<input name="login" type="submit" value="Log in" class="login">
<small><input type="checkbox"> Keep me logged in</small>
</form>
<?php
if ($failed == 1) {
echo "Wrong Username / Password";
}
?>

다음은 security.php에 대한 내 코드입니다.

<?php
require 'connect.php';

// username and password sent from form 
$tbl_name = 'users';
$username=$_POST['username']; 
$password=$_POST['password'];

// To protect MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($conn, $sql);

// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);

// If result matched $username and $password, table row must be 1 row
if($count == 1)
{
// Register $username, $password and redirect to file "login_success.php"
session_start();
$_SESSION["username"] = $username;
header("location:home.php");
}
else {
$failed = 1;
header("location:index.php");
}
?>

보시거나 안 보셨 겠지만, $ failed라는 security.php에 설정된 변수를 사용하려고했습니다. $ failed는 security.php에 설정되고 login.php의 if에 사용되어 실패 메시지를 에코합니다. 그게 일에 가깝지 않다는 것을 알고 있지만, 내가하려는 일을 말할 수있는 유일한 방법이었습니다. 도움이 필요하세요?

 

해결 방법

 

security.php 를 사용해보십시오.

if($count == 1)
{
// Register $username, $password and redirect to file "login_success.php"
session_start();
$_SESSION["username"] = $username;
header("location:home.php");
}
else {
header("location:index.php?msg=failed");
}

그리고 이것은 index.php :

if (isset($_GET["msg"]) && $_GET["msg"] == 'failed') {
echo "Wrong Username / Password";
}

 

참조 페이지 https://stackoverflow.com/questions/29024361

 

 

반응형

댓글