Click here to Skip to main content
15,038,345 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I am beginner php student. I have a code for login that check if the username and password are correct.
everything is OK, but if the username or password are incorrect, the code generate error message then show blank page. How can I prevent this blank page to be shown?

$username = $_POST['u'];
$password = $_POST['p'];

$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username); 
$password = mysql_real_escape_string($password);


$result = mysql_query("select * from employees where username = '$username' and password = '$password' ") or die("faild");

$row = mysql_fetch_array($result);

if($row['username'] == $username && $row['password']==$password)
{ $NoOFLetter = strlen($username);
  $result = substr($username, $NoOFLetter-3,  $NoOFLetter);
  if($result == "doc"){header('Location: tabeeb.html'); exit;}
  if($result == "sec"){header('Location: sec.html'); exit;}}

else{  } // what to add here? 

What I have tried:

I tried this code

echo '<script language="javascript">';
    echo 'alert("Error in Username or Password!")';
    echo '</script>';

but the blank page also appear.
Updated 3-Feb-17 0:17am

You have multiple options.

You can create a HTML file and show that like the ones shown on successful login:
header('Location: loginerr.html'); exit;

Or you can create the content of a HTML page and print that:
$loginerr = <<<EOT
<title>Login error</title>
<p>Error in username or password.</p>
echo $loginerr;
The above example uses the heredoc syntax for multi line strings (see PHP: Strings - Manual[^]). You can add any HTML content including scripts.
Sallam Mhamad El-Tanna 3-Feb-17 6:53am
I tried the first solution, but it show login page again without the alarm, I need the alarm message to be shown!
Consider using Ajax. From your login page, the username and password pair can be sent over to the PHP script via Ajax, in that way, your login page stays while the authentication is being processed on the server-side. Depending on the response returned, you can then display error message or redirect to other pages. Follow this tutorial Ajax Login Script with jQuery, PHP MySQL and Bootstrap | Coding Cage[^].
However, your have more serious issues here:
First, the way you construct SQL is inviting SQL injection[^], use prepared statement[^] instead.
Next, it seems that you are prepending usernames with "doc" and "sec" as a way to identify the page that a user should be visiting after successful log in, the correct way is to use Role Based Access Control in PHP[^]
Sallam Mhamad El-Tanna 4-Feb-17 13:00pm
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900