In part 5 of my PHP Message Board Tutorial, I show you how to create a proper login system.
This isn’t a simple system though. It is multi-layered and very secure. I specifically cover how to:
And, a whole bunch more. All of the code follows the video like always.
This is a more advanced script and you may need help with the following topics:
Code From the Video
<?php
include(‘header.html’);
?>
<style>
#recaptcha_image img {
width: 185px;
height: 28.5px;
border: 1px solid gainsboro;
}
#recaptcha_widget {
height:400;
}
</style>
<script type=”text/javascript”>
// Changes the styling for the Captcha image
var RecaptchaOptions = {
theme : ‘custom’,
custom_theme_widget: ‘recaptcha_widget’
};
</script>
<?php
if (isset($_POST[‘submitted’])) { // Check if the form has been submitted.
// Security check for a valid username
if (preg_match (‘%^[A-Za-z0-9]\S{8,20}$%’, stripslashes(trim($_POST[‘userid’])))) {
// Scrub username with function in header.php
$u = escape_data($_POST[‘userid’]);
} else {
$u = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid User ID!</font></p>’;
}
// Security check for a valid password
if (preg_match (‘%^[A-Za-z0-9]\S{8,20}$%’, stripslashes(trim($_POST[‘pass’])))) {
// Scrub password with function in header.php
$p = escape_data($_POST[‘pass’]);
} else {
$p = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid Password!</font></p>’;
}
// PHP Code for the CAPTCHA System
$captchchk = 1;
$privatekey = “Public Key Here”;
$resp = recaptcha_check_answer ($privatekey,
$_SERVER[“REMOTE_ADDR”],
$_POST[“recaptcha_challenge_field”],
$_POST[“recaptcha_response_field”]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
echo ‘<p><font color=”red” size=”+1″>The CAPTCHA Code wasn\’t entered correctly!</font></p>’;
$captchchk = 0;
}
// Query the database. Verify the username, password and captcha
if ($u && $p && $captchchk) {
$query = “SELECT user_id, first_name, last_name, email, username, passwd, active FROM users WHERE username=’$u’ AND passwd=SHA(‘$p’)”;
$result = mysql_query ($query) or trigger_error(“Either the Userid or Password are incorrect 1”);
if (mysql_affected_rows() == 1) { // A match was made
$row = mysql_fetch_array ($result, MYSQL_NUM);
mysql_free_result($result);
// If they haven’t activated the account redirect
if ($row[6] != NULL)
{
header(“Location: http://localhost/msgbrd/mbforgotpass.php”);
mysql_close(); // Close the database connection.
exit();
}
$_SESSION[‘first_name’] = $row[1];
$_SESSION[‘userid’] = $row[4];
// Create Second Token for security
$tokenId = rand(10000, 9999999);
$query2 = “update users set tokenid = $tokenId where username = ‘$_SESSION[userid]'”;
$result2 = mysql_query ($query2);
$_SESSION[‘token_id’] = $tokenId;
// Reset session id for security
session_regenerate_id();
// Redirect the user
header(“Location: http://localhost/msgbrd/mblogin.php”);
mysql_close(); // Close the database connection.
exit();
}
} else { // No match was made.
echo ‘<br><br><p><font color=”red” size=”+1″>Either the Userid or Password are incorrect 2</font></p>’;
mysql_close(); // Close the database connection
exit();
}
} // End of SUBMIT
?>
<body>
<div id=”header”><h2>Message Board</h2></div>
<div id=”login”>
<?php
echo ‘<h1>Welcome’;
if (isset($_SESSION[‘first_name’])) {
echo “, {$_SESSION[‘first_name’]}!”;
}
echo ‘</h1>’;
// Display links based upon the login status
// If user is on the logout page disable the login
if (isset($_SESSION[‘userid’]) AND (substr($_SERVER[‘PHP_SELF’], -10) != ‘logout.php’)) {
echo ‘<a href=”logout.php”>Logout</a><br />
<a href=”change_password.php”>Change Password</a><br />’;
} else { // Not logged in.
echo ”
<form action=’mblogin.php’ method=’post’>
<p><b>Userid:</b> <input type=’text’ name=’userid’ size=’20’ maxlength=’20’ /></p>
<p><b>Password:</b> <input type=’password’ name=’pass’ size=’16’ maxlength=’30’ /></p>”;
// Captcha stuff from Google
echo ”
<div id=’recaptcha_widget’ style=’display:none’>
<div id=’recaptcha_image’></div>
<div class=’recaptcha_only_if_incorrect_sol’ style=’color:red’>Incorrect please try again</div>
<span class=’recaptcha_only_if_image’>Enter the words above:</span><br />
<span class=’recaptcha_only_if_audio’>Enter the numbers you hear:</span>
<input type=’text’ id=’recaptcha_response_field’ name=’recaptcha_response_field’ />
<div><a href=’javascript:Recaptcha.reload()’>Get another CAPTCHA</a></div>
<div class=’recaptcha_only_if_image’><a href=’javascript:Recaptcha.switch_type(\’audio\’)’>Get an audio CAPTCHA</a></div>
<div class=’recaptcha_only_if_audio’><a href=’javascript:Recaptcha.switch_type(\’image\’)’>Get an image CAPTCHA</a></div>
<div><a href=’javascript:Recaptcha.showhelp()’>Help</a></div>
</div>
<script type=’text/javascript’
src=’http://www.google.com/recaptcha/api/challenge?k=Public Key Here’>
</script>
<noscript>
<iframe src=’http://www.google.com/recaptcha/api/noscript?k=Public Key Here’
height=’300′ width=’500′ frameborder=’0′></iframe><br>
<textarea name=’recaptcha_challenge_field’ rows=’3′ cols=’40’>
</textarea>
<input type=’hidden’ name=’recaptcha_response_field’
value=’manual_challenge’>
</noscript>
“;
echo “<div align=’left’><input type=’submit’ name=’submit’ value=’Login’ /></div>
<input type=’hidden’ name=’submitted’ value=’TRUE’ />
</form>”;
echo ‘<a href=”register.php”>Register</a><br />
<a href=”forgot_password.php”>Forgot Password</a><br />’;
}
?>
</div>
</body>
</html>
so how do I logout?
is it ok to set the token id
and $_session[‘userid’] back to null?
You could do that but it won’t really matter since the token id changes every time
hi sir, my question are:
1. do i need a internet connection to make a captcha?
2. how to remove the captcha from this code.
Yes you need an internet connection for captcha. To remove it, delete the code that follows the comment Captcha stuff from Google. Also delete the check for the captcha that follows the comment PHP Code for the CAPTCHA System
hi again sir,
can i make a request to make another video or tutorial on this part 5 of your tutorial?
because i cant do it. eventhough how many times i try.it is not working. even if i remove the captcha system. i cannot log in. please help me. thank you so much sir. sorry for my bad english. π
I’ll see what I can do, but it will take a while. I just checked the code and it works on my end. What errors are you seeing? What changes did you make? Another common issue is that you need to replace all backquotes in my code into normal quotes with a find and replace command. That was done in the past for security reasons on my old tutorials. – I hope that helps – Derek
hi again sir,
when i input the username and password, nothing happens. the login page just refresh.The page is just returning to login page.
i remove the capcha system. that’s the only changes i made. please help me sir. im so stress.:( sorry for my bad english. thank you so much sir for the reply. thankyou again.
Make sure your user part of your database looks like this
+———–+———————–+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+———–+———————–+——+—–+———+—————-+
| user_id | mediumint(8) unsigned | NO | PRI | NULL | auto_increment |
| lang_id | tinyint(3) unsigned | NO | | NULL | |
| time_zone | varchar(30) | NO | | NULL | |
| username | varchar(30) | NO | UNI | NULL | |
| pass | char(40) | NO | | NULL | |
| email | varchar(60) | NO | UNI | NULL | |
+———–+———————–+——+—–+———+—————-+
Hi sir,
May i ask you what lang_id is? Because i cant find any lang_id in your tutorial in the user’s table. I followed all your steps from 1 to 5. The registration script and the activation script worked. But the log in script isnt really Working.it goes back and refreshes to log in script.i downloaded all the phpmsgboard script and tried to use it but i still have the same problem. Please help me figure out whats wrong.the only thng i chaned was the capcha.
And may i ask what data base are you using? Is it the phpmyadmnin or thE xammp or the wammp or mysql/workbench.
Thankyou
I put lang_id in there to track the language the person may use. It isn’t really important for this tutorial. The database I’m using is MySQL. I just edit MySQL using the terminal. I don’t use phpmyadmin, workbench, or any other gui interface for it
hi again sir.
im done with the login process.
my problem now is the comment section.
i downloaded the jquery script.
how can i change the scr= on the javascript?
can you please give me an example on how can i put the correct script on the scr=…
thank you sir.
You just need to put in the location of JQuery on your web server. There is no way for me to guess how your web server is set up. Just look for the JQuery location in relation to the pages that you can pull up in a browser and then base the JQuery script location on those. I hope that helps
hi again sir,
can you teach me how to edit mysql to? are you using apache server?
i cant run php script using mysql server only.
thanks for the reply
Sure go to this page PHP MySQL Video Tutorial and watch tutorials 14 thru 19. Those tutorials teach how to use MySQL and also how to use MySQL with PHP. I hope they help
Hello,
i’m having issues with the code, i’ve even copied and pasted and such but when ever I try to log in I get the following error:
“Please enter a valid Username” and “The Password or Username provided are incorrect2” but they are correct.
I am using your code and tutorial as a learning tool. I am running the code on my localhost and would like to test it without having the email validation to activate the account. I delete the code in the mbregister.php, but I still can’t seem to login in. Please show me where else to remove code so that email validation can be bypass.
Thanks. And thanks for the great tutorial.
Thank you π Did you edit this query $query = βSELECT user_id, first_name, last_name, email, username, passwd, active FROM users WHERE username=β$uβ AND passwd=SHA(β$pβ)β;
You basically need to delete any references to emails. You could always assign a fixed value for an email as well in the code and the database. That would allow you to do what you need while still keeping the code intact. I hope that helps.