Howdy folks,
As I promised to you, I’m back with PHP MySQL Login System with Remember Me, Online Status, Forgot Password & User Profile option. This tutorial is much advanced than the previous one and it is a extension of that. If you are a beginner, then you should start reading with the previous article – PHP MySQL Login System – A Super Simple Tutorial
Skills that you need for this Login System
Files That you need for this Login System
- users.sql
- db-const.php
- functions.php
- register.php
- login.php
- forgot.php
- profile.php
- logout.php
- script.js
- update-status.php
- Download All Files as Zipped – 6.73 KB (Password is w3epic.com)
users.sql
At first, run the query as below and create users table in your database. You can also download the users.sql file and import it via phpMyAdmin to create the same table.

CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `status` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
db-const.php
Change the values with your server details as required.
<?php # mysql db constants DB_HOST, DB_USER, DB_PASS, DB_NAME const DB_HOST = 'db-host'; const DB_USER = 'db-user'; const DB_PASS = 'db-password'; const DB_NAME = 'db-name'; ?>
functions.php
Nothing fancy, two simple functions that works.
The logged_in() function checks for if a user logged in or not and returns true or false respectively.
The redirect_to() function take a URL as argument and redirects to that URL. You can also use simple header(“Location: $url”).
<?php function logged_in () { if (isset($_SESSION['username']) && isset($_SESSION['user_id'])) { return true; } else { return false; } } function redirect_to ($url) { header("Location: {$url}"); } ?>
register.php
At the first of this file, it includes required PHP files and start the session at the beginning (line 2-4). Note that you must start the session before any output is made. Then we check if a user logged in, then he/she will be redirected to profile.php (line 5-7). After that we have a very simple HTML registration form which has Username, Password, First Name, Last Name and Email field. On the line 18, we’re checking for if the form has been submitted or not. If its not, then we’re showing the form to the new user – else on the line 31 we initiate a MySQLi connection and check if username and email exist otherwise we insert user input data to MySQL database (line 45-72). On a successful registration, we’re redirecting the user to login.php with a success message in the URL (line 66). Now register some users for testing.
<?php require_once("functions.php"); require_once("db-const.php"); session_start(); if (logged_in() == true) { redirect_to("profile.php"); } ?> <html> <head> <title>User registration form - PHP MySQL Login System | W3Epic.com</title> </head> <body> <h1>User registration form - PHP MySQL Login System</h1> <h2>By Arpan Das</h2> <hr /> <!-- The HTML registration form --> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Username: <input type="text" name="username" /><br /> Password: <input type="password" name="password" /><br /> First name: <input type="text" name="first_name" /><br /> Last name: <input type="text" name="last_name" /><br /> Email: <input type="type" name="email" /><br /> <input type="submit" name="submit" value="Register" /> <a href="login.php">I already have an account...</a> </form> <?php if (isset($_POST['submit'])) { ## connect mysql server $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); # check connection if ($mysqli->connect_errno) { echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>"; exit(); } ## query database # prepare data for insertion $username = $_POST['username']; $password = $_POST['password']; $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $email = $_POST['email']; # check if username and email exist else insert // u = username, e = emai, ue = both username and email already exists $exists = ""; $result = $mysqli->query("SELECT username from users WHERE username = '{$username}' LIMIT 1"); if ($result->num_rows == 1) { $exists .= "u"; } $result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1"); if ($result->num_rows == 1) { $exists .= "e"; } if ($exists == "u") echo "<p><b>Error:</b> Username already exists!</p>"; else if ($exists == "e") echo "<p><b>Error:</b> Email already exists!</p>"; else if ($exists == "ue") echo "<p><b>Error:</b> Username and Email already exists!</p>"; else { # insert data into mysql database $sql = "INSERT INTO `users` (`id`, `username`, `password`, `first_name`, `last_name`, `email`) VALUES (NULL, '{$username}', '{$password}', '{$first_name}', '{$last_name}', '{$email}')"; if ($mysqli->query($sql)) { redirect_to("login.php?msg=Registred successfully"); } else { echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>"; exit(); } } } ?> <hr /> <h1><a href="http://w3epic.com/">W3Epic.com</a></h1> </body> </html>
login.php
Like the register.php first few lines are similar (line 1-8). After that we have a simple login form with Username, Password and Remember me field (line 18-26). On the line 28, we’re checking if the for has been submitted or not and If its submitted we process it further (line 29-63).
If the Remember me option is checked then we’ll set session cookie expiry time (lifetime) to one week+ from now (604800 seconds) using session_set_cookie_params() function. The session_regenerate_id() function is used to avoid session fixation (line 33-36).
Like before in register.php we instantiate a new MySQLi connection and check for username and password combination (line 45). Now if the username and password combination get matched then it’ll return one row – else zero. So, on the line 48, if returned number of row is not equal to one, then we’ll show an error to the user. Otherwise we’ll fetch the users data from database, register the session, authenticate the user and redirect him/her to profile.php.
We’ll talk about update status to online/offline later (line 56) on this article.
<?php require_once("functions.php"); require_once("db-const.php"); session_start(); if (logged_in() == true) { redirect_to("profile.php"); } ?> <html> <head> <title>User Login Form - PHP MySQL Login System | W3Epic.com</title> </head> <body> <h1>User Login Form - PHP MySQL Login System</h1> <h2>By Arpan Das</h2> <hr /> <!-- The HTML login form --> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Username: <input type="text" name="username" /><br /> Password: <input type="password" name="password" /><br /> Remember me: <input type="checkbox" name="remember" /><br /> <input type="submit" name="submit" value="Login" /> <a href="forgot.php">Forgot Password?</a> <a href="register.php">Register</a> </form> <?php if (isset($_POST['submit'])) { $username = $_POST['username']; $password = $_POST['password']; // processing remember me option and setting cookie with long expiry date if (isset($_POST['remember'])) { session_set_cookie_params('604800'); //one week (value in seconds) session_regenerate_id(true); } $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); # check connection if ($mysqli->connect_errno) { echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>"; exit(); } $sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1"; $result = $mysqli->query($sql); if ($result->num_rows != 1) { echo "<p><b>Error:</b> Invalid username/password combination</p>"; } else { // Authenticated, set session variables $user = $result->fetch_array(); $_SESSION['user_id'] = $user['id']; $_SESSION['username'] = $user['username']; // update status to online $timestamp = time(); $sql = "UPDATE users SET status={$timestamp} WHERE id={$_SESSION['user_id']}"; $result = $mysqli->query($sql); redirect_to("profile.php?id={$_SESSION['user_id']}"); // do stuffs } } if(isset($_GET['msg'])) { echo "<p style='color:red;'>".$_GET['msg']."</p>"; } ?> <hr /> <h1><a href="http://w3epic.com/">W3Epic.com</a></h1> </body> </html>
forgot.php
If someone forgot his/her username or password or both then we can take his/her email address, check our users database and if any account exists with that email address then we’ll send login credentials to his/her email address.
Beginning of this file is same as before and has a similar form with just one field – email address. We take input email address from the user and then initialize a MySQLi connection (line 26). After that we find the email address and if it exists then we’ll send it to the user via PHPMailer (line 46). If email doesn’t exists then we’ll simply show an error to the user.
Please see this article below to configure phpMmailer with your gmail account or own server.
PHPMailer Tutorial – How To Configure with Gmail Account
<?php session_start(); require_once("functions.php"); require_once("db-const.php"); if (logged_in() == true) { redirect_to("profile.php"); } ?> <html> <head> <title>Forgot your Username or Password? - PHP MySQL Login System | W3Epic.com</title> </head> <body> <h1>Forgot your Username or Password? - PHP MySQL Login System</h1> <h2>By Arpan Das</h2> <hr /> <p>Please enter your email address below.</p> <form action="forgot.php" method="post"> Email: <input type="text" name="email" /> <input type="submit" name="submit" value="Submit" /> </form> <?php if (isset($_POST['submit'])) { ## connect mysql server $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); # check connection if ($mysqli->connect_errno) { echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>"; exit(); } ## query database # fetch data from mysql database $sql = "SELECT email FROM users WHERE email LIKE '{$_POST['email']}' LIMIT 1"; if ($result = $mysqli->query($sql)) { $user = $result->fetch_array(); } else { echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>"; exit(); } if ($result->num_rows == 1) { // email login cresendials to the user's email // use phpMailer tutorial on w3epic echo "<p>Login credentials has been sent to <b>{$_POST['email']}</b></p>"; } else { echo "<p>Sorry, no user found with this email.</p>"; } } ?> <a href="login.php">Login</a> | <a href="register.php">Register</a> <hr /> <h1><a href="http://w3epic.com/">W3Epic.com</a></h1> </body> </html>
profile.php
This profile.php is the place where a users data is visible. Here, profile.php is restricted and visible only to the logged in users. If there is no id specified in the URL then profile.php will show the user account owner’s profile itself. If a ID is specified in the URL like …/profile.php?id=10 then profile.php will show the user profile of user ID 10.
So, similar to the previous files – we’ve done file inclusion and started the session (line 1-5). Then we check if the user is logged in or not, and if not – he/she will be redirected to login.php. Otherwise we’ll process further. On the line 19, we’re check if the id in the URL exists and if its not blank, then we’re assigning a variable $id with that value from URL. Else we’ll assign its value with user ID from session.
After that, we’re initializing a MySQLi connection and fetching the user WHERE id = that $id in the MySQL query (line 35). Now if MySQL returned number of rows = 1, then its a valid ID and if 0 – its not.
If the user ID is valid then we’ll calculate the user’s online status and echo the user profile data. Otherwise we’ll show an simple error message.
Calculating online status will be discussed later.
<?php require_once("functions.php"); require_once("db-const.php"); session_start(); if (logged_in() == false) { redirect_to("login.php"); } else { ?> <html> <head> <title>User Profile - PHP MySQL Login System | W3Epic.com</title> <script src="script.js" type="text/javascript"></script><!-- put it on user area pages --> </head> <body> <h1>User Profile - PHP MySQL Login System</h1> <h2>By Arpan Das</h2> <hr /> <?php if (isset($_GET['id']) && $_GET['id'] != "") { $id = $_GET['id']; } else { $id = $_SESSION['user_id']; } ## connect mysql server $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); # check connection if ($mysqli->connect_errno) { echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>"; exit(); } ## query database # fetch data from mysql database $sql = "SELECT * FROM users WHERE id = {$id} LIMIT 1"; if ($result = $mysqli->query($sql)) { $user = $result->fetch_array(); } else { echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>"; exit(); } if ($result->num_rows == 1) { # calculating online status if (time() - $user['status'] <= (5*60)) { // 300 seconds = 5 minutes timeout $status = "Online"; } else { $status = "Offline"; } # echo the user profile data echo "<p>User ID: {$user['id']}</p>"; echo "<p>Username: {$user['username']}</p>"; echo "<p>Status: {$status}</p>"; } else { // 0 = invalid user id echo "<p><b>Error:</b> Invalid user ID.</p>"; } } // showing the login & register or logout link if (logged_in() == true) { echo '<a href="logout.php">Log Out</a>'; } else { echo '<a href="login.php">Login</a> | <a href="register.php">Register</a>'; } ?> <hr /> <h1><a href="http://w3epic.com/">W3Epic.com</a></h1> </body> </html>
logout.php
The main functionality of the logout.php is to unset and destroy the session and update user’s status to offline instantly. On the line 23, we’ve unset all session variables. On the line 25-27, we’ve destroyed the session cookie. Along with on the line 29, we’ve finally destroyed the session. We used three methods all together because its much risk free.
Update status to offline (line 13) will be discussed later on this article.
<?php require_once("functions.php"); require_once("db-const.php"); session_start(); $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); # check connection if ($mysqli->connect_errno) { echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>"; exit(); } // update status to offline $sql = "SELECT status from users WHERE id={$_SESSION['user_id']}"; $result = $mysqli->query($sql); $user = $result->fetch_array(); $timestamp = $user['status'] - 300; $sql = "UPDATE users SET status={$timestamp} WHERE id={$_SESSION['user_id']}"; $result = $mysqli->query($sql); ## finally destroying the session // unset all session variables $_SESSION = array(); // destroy the session cookie if(isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-50000, '/'); } // destroy the session session_destroy(); redirect_to("login.php"); ?>
script.js
In this script.js file, we’re doing some very basic AJAX. We’re triggering a function called update_status whenever any click or keypress is made within the page. The function will send a GET request to update-status.php as-synchronously and update-status.php will do the job for us in background.
window.onload = function () { document.onclick = update_status; document.onkeypress = update_status; } function update_status () { // ajax start var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE xhr.open('GET', 'update-status.php', false); xhr.send(); // ajax stop }
update-status.php
The main code of update-status.php will be executed if the user is found logged in. It will initiate a MySQLi connection and updates the user table’s status field with current timestamp value (line 16).
<?php require_once("db-const.php"); require_once("functions.php"); session_start(); if (logged_in() == true) { ## connect mysql server $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); # check connection if ($mysqli->connect_errno) { echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>"; exit(); } $timestamp = time(); $sql = "UPDATE users SET status = '{$timestamp}' WHERE id ={$_SESSION['user_id']}"; $result = $mysqli->query($sql); } ?>
Setting online-offline status
To calculate whether a user is online or offline we’re using timestamp instead of using regular online-offline flag. Whenever a user logs in, his/her user status field will be updated with current timestamp value. Whenever a logged in user clicks anywhere in the page or press any key from keyboard, the JavaScript do an AJAX GET request which calls update-status.php. Now, on each click or keypress from keyboard on the page will call the update-status.php same number of times. On calling update-status.php, it will update the users status field with current timestamp value.
So, each click or keypress from keyboard on the page = status field updated with the timestamp when the click is made or keypress is done. When a user do not click on anything or keypress on the page for about 5*60 = 300 seconds, he/she will be treated as a offline user. Of course you can edit this value as you want.
In the login.php, its updating users status field with current timestamp. So, the user will be treated as online instantly (line 56).
In the logout.php, its updating users status field with current timestamp – 300 seconds. So, the user will be treated as offline instantly (line 17).
Thank you very much for your time.
If you’re facing any problem, please write it here, I’ll try to solve it.
If you like the article please like, share and comment.
Thank you!
Dear
its really good and your teaching method is awesome.
i was wondering if you could help me with.
1.How do i make it so that all the boxes in register must be filled in before they can make an account?
2.Once a user is logged in or signed in, it redirects them to the index page and the profile button becomes their name?
3.could you do a tutorial on how to protect your website and how to make a twitter like upload system?
thank you so much
hmm…
1. Please see these articles for both client side and serverside form validation:
http://w3epic.com/how-to-validate-form-with-php-server-side-validation/
http://w3epic.com/how-to-handling-and-validating-html-forms-in-javascript-tutorial/
2. Just put $_SESSION[‘username’] or your $username (fetched from database) where you want it to be shown.
like below
3. Check this out http://w3epic.com/how-to-upload-and-validate-files-using-php/ and tell me if you’re not happy…
Thanks that helped!
One more thing, how do i let users upload stuff on my website on certain pages? Like yahoo answers, you fill out a form and you choose what category it goes under and they can upload it? how do i do that?
Thank you
Also i found a ‘bug’? in your simple tutorial if log in was successful it would get rid of the username and password boxes and say you have logged in successfully. How do i redirect people to the homepage if the log n was successful?
You mean this one http://w3epic.com/php-mysql-login-system-a-super-simple-tutorial/ ?
That has no extra features, I tried to kept that as simple as possible. You’ll just be able to see login successful.
Thats why I wrote this one more advanced version, it has all missing features of that.
Use this instead.
To redirect, use php built in header() function or my redirect_to() function. Read the article completely for details.
Write your upload script on that particular page and along with uploading files, use database to store upload information.
Then you can play with that with ease.
the code have so many if logged in and ‘else’ i don’t know where to put it so if logged in, you get redirected to the index page. i don’t know what the code is and where to place it.
thanks
Code for that is like below:
Hey Arpan,
its not working where i put it
connect_errno) {
echo “MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}”;
exit();
}
$sql = “SELECT * from users WHERE username LIKE ‘{$username}’ AND password LIKE ‘{$password}’ LIMIT 1”;
$result = $mysqli->query($sql);
if ($result->num_rows != 1) {
echo “Error: Invalid username/password combination”;
} else {
$user = $result->fetch_array();
$_SESSION[‘user_id’] = $user[‘id’];
$_SESSION[‘username’] = $user[‘username’];
$timestamp = time();
$sql = “UPDATE users SET status={$timestamp} WHERE id={$_SESSION[‘user_id’]}”;
$result = $mysqli->query($sql);
redirect_to(“index.php?id={$_SESSION[‘user_id’]}”);
}
}
if(isset($_GET[‘msg’])) {
echo “”.$_GET[‘msg’].””;
}
if (logged_in() == true) {
echo “You have Logged in successfully. Click here to go to the main page”;
} else {
echo ‘ Oh! No account? Register here!‘;
}
?>
i don’t know how to let people redirect to the main page.
Hello DP,
I checked the script and its working fine.
http://w3epic.com/code-snippets/php-mysql-login-processor/
it’s so perfect pro thank you for that it’s so great tutorial
im testing your script buddy , its good. but i saw some bug. i registered 2 user. after that i log off all. then when i click login without entering any data, it automaticaly logging into user id 2, please advice
Did you clicked on Log Out button properly before that?
After login with remember me not checked, you close the browser = you log out, without clicking log out link.
After login with remember me is checked, you do not click on the log out link and close the browser = you stay logged in for 1 week.
ok got it , now im having this error Parse error: syntax error, unexpected T_CONST in /home/wwwtuiti/public_html/db-const.php on line 3
I guess you’re running with PHP 5.2, and this is the main reason of this problem.
Use define in place of const.
Modify the code of db-const.php like below, instead of the current one.
Great tutorial,
I was following your tutorial but I wanted the data from the registration form to be stored into two separate tables, my address_book table includes Address_Book_id, First_Name, Last_Name, Street, Subburb, Post_Code, Phone_Number fields and customers table has Cust_ID, Cust_Username, Cust_Email, Cust_Password, Address_Book_Address_Id fields .
Could you take a look at my code, and tell me what I have done wrong.
https://www.dropbox.com/sh/kabgajzg2vfbtvp/AACdVqLBnzcU0wNnqaEffk38a
Any help would be much appreciated
Hi tedos,
Can you show me the place near line 128 of your register.php?
BTW, there is no need of address_book_address_id in customers table. Just add a field ‘customer_id’ in address_book table.
customer_id will be the link between two tables.
Thanks for the speedy response.
Line 128 should be there, I have accidentally cut the 1 off so you can only see the 28. So it’s the $sql1 = line.
127- $sql1 = “INSERT INTO `customers` (`Cust_Id`, `Cust_Username`, `Cust_Password`, `Cust_Email`, `Address_Book_Address_Id`)
128- VALUES (NULL, ‘{$username}’, ‘{$password}’, ‘{$email}’, ‘{$id}’)”;
Thanks again
Hi,
id on line 125 is doing all bad. Use $id = $mysqli->insert_id; instead.
I now get the following *error ( ! ) Warning: mysqli::query() expects parameter 2 to be long, string given in C:\wamp\www\pizza2\register.php on line 130*
130: if ($mysqli->query($sql,$sql1)) {
131: redirect_to(“members.php?msg=Registred successfully”);
Do it by parts like below.
Hi,
i think there is a bug? Sometimes it will log in and sometimes it won’t? I have to keep logging in for it to be logged in sometimes? And it dosnt redirect the page like it says in the code?
Thanks
Hi,
I rechecked as you said but working as expected – fully functional.
Something is going wrong with session (in your side).
1. Clear your browser cache.
2. Try with different browsers.
3. If you got any error message, please post it here. (enable php error reporting if disabled)
i see there is a simple tutorial that does the same thing? what is the difference? is this one more secure from hackers or?
Hi Toni,
In the simple one, I’m just showing 1. creating user’s DB, 2. registering users, 3. logging in
In the advanced on, I’m adding 1. stay logged in using session, 2. fetch a users info, 3. managing each users online status, 4. remember me option, 5. logout and 6. forgot password option
hello nice detailed script you have created, but am having a similar problem just like how Toni mentioned. Anytime i try to login, I have to try it twice before i can login.
I have the same issue. Here is the error warning message:
Warning: Cannot modify header information – headers already sent by (output started at /homepages/…/admin/login.php:58) in /homepages/…/admin/functions.php on line 11
functions.php line 11 -> header(“Location:{$url}”);
login.php line 58 – if (isset($_POST[‘submit’])) {
I now receive this error “MySQL error no 1452 : Cannot add or update a child row: a foreign key constraint fails (`pepperoni_pizza`.`customers`, CONSTRAINT `fk_Customers_Address_Book` FOREIGN KEY (`Address_Book_Address_Id`) REFERENCES `address_book` (`Address_Id`) ON DELETE NO ACTION ON UPDATE NO ACTION)”
Hi,
Show me your recent code that generating this error.
Upload it to dropbox and link it here.
Hi Mike, Toni and anyone having similar problem with login,
I have checked again and its working fine.
Have you guys modified anything except db-const.php?
If yes, please show it to me. Upload your code to dropbox and link it here.
If you have any online preview of login system, please post the link here.
Thanks.
Hi I have added the register.php, screenshot of the error “new error.png”, zip of the entire site and dump of the sql file to
https://www.dropbox.com/sh/kabgajzg2vfbtvp/AACdVqLBnzcU0wNnqaEffk38a
Whats in that 48 MB zip file?
BTW, replace line 106 to 119 with the code below, it’ll fix that.
the link is didn’t work pro can u put it on media fire and thnx
Thank you so much, you’re a life saver.
The zip file was the entire site, also I emailed you earlier at [email protected], did you receive it?
Thanks again you’re amazing.
Yes, I just got it (did not noticed until now), will reply tomorrow.
You are welcome 🙂
Thanks for your reply, I have not modified anything in any of the codes/files except for db-const.php file to connect with Msql and I used your sql.
An online demo http://fbadder.com/system/login.php
username mike
pass mikepass
Once password is submitted, it remains on the login.. i have to login again or refresh before am redirected to profile.php tested on Firefox and Chrome but the same issue. Thanks
Open up functions.php and change the line no. 11 as below.
Note that the space after “Location:” is removed.
After that, check and let me know.
I have edited functions.php file as you said but still the same issue. Thanks
Hi,
Give a try with a different server. It will confirm that something is wrong with your server.
hi Arpan , i have some questions ,,.. i want to remove register page its normal or there anything to notice ?
i mean i have already database with users and passwords and i dont want any other members to register just my users in my database
how can it done ???
Hi Hayder,
Just remove the register.php and remove all links which are linked to register.php
Hey Arp, just wondering if you have had a chance to read my email? I could really use your assistance connecting my menu to my database.
Just give me 1 or 2 more days, very busy with a web application. I read it, will reply ASAP.
When do you need it?
Within the next week would be the most helpful, projects due mid week next week. Any help would be much appreciated. 🙂
Hi,
I’ve just sent you a php-mysql-jquery based drag-n-drop via email.
Great stuff! Found one quirky thing. When a user enters login information and hits “login” all the data from the user name and password fields clear and the form just sits there (even though login was successful). But if you then if you click “login” a second time, it will redirect. Why won’t it redirect the first time and give the success message etc?
Also, it doesn’t look like it emails users their login info, but perhaps it is not set up to do so? No big deal for me either way…
Hi Jeff,
It is happening with few people, I’ve tested the code many times, the logic is ok. But somehow redirect is not working for first attempt. Please try with different server and reply.
I didn’t wanted to put different thing here – it will make it more complex; so I mentioned my PHPMailer tutorial.
Thanks
your tuts help me a lot..thanks a bunch arpan…could you help me with this…i need to change the email instead username as user login how do i do this? also how do i implement the login page as bootstrap 3 modal ? and for the register form how do i add in the mysql something like member avatar (image) or big photo upload..( i send you the form look arp149[at]yahoo.com…) Any help would be much appreciated
wow…its very nice…working fine…..thanx w3epic.com team………..
Hi
Thanks for the great script!
I got a problem at “register.php”, after I fill up all fields, and press the register Button, it shows up following error:
“MySQL error no 1364 : Field ‘status’ doesn’t have a default value”
What I did wrong?
Got it!
in the DB (mysql) I had to change the status field “NULL=yes”
So it works great!
Cheers
awesome work man, I am gonna try to add a profile picture to the script so when you edit your profile you can upload a .png image, any help you could give me on it?
Hi,
check this out: http://w3epic.com/how-to-upload-and-validate-files-using-php/
Thank you
Hi Arpan,
One question:
Do you have this code running correctly on your local?
Just to know if it’s been tested.
Yes, of course.
The login script and register script won’t redirect after login or register. How to fix it ?
Okay, try header(“Location: {$url}”); instead of redirect_to ($url); and please post your result here.
Thank you.
Hi
Is this still active as am using this script but have a issue with the log in side/coding
It keeps coming up with invalid username/password combination
I have md5 the password so is secure, could that be why?
Where is best to show the coding, I can use pastebin and add the link here if need be
I’m very busy, but yes – its active 🙂
If you inserted md5 of the password into database while registering the user, then yes – you have to check through md5 in login page.
Yes you can post pastebin links here 😉
Hi there gr8 work on this, just one thing that I cant seem to get working, when i click the logout button, it loads a blank page but does not end the seesion, as i can just go back to the profile page and all is still logged in. ?
thanks in advance
ok i have got this all working now apart from if i add anything els on the login page e.g a p tag with some text in it it stops the login from working ? you have to click the login button again after putting the login details in for it to redirect to the next page?
Hi Sam,
Where did you added the p tag? line number?
It should work as expected. Redirection should be done right after logging in.
hi,everything is perfect, can u plz explain about remember me check button .
Hi Sai,
If we CHECK the remember me checkbox, then we got it in line 33 of login.php
There, we set the session cookie’s expiration time to one week and we and setting session regenerate id to true in line 34 & 35.
Thats all 😉
after login I want to redirect home page with view profile,update profile,logout etc option.but there would be no login option (login option was in my home page before login ) because i have already logged in.
how can i do it?
It is already like that as you said I think.
After getting logged in, the login page won’t be visible.
yes.. do i need ajax for this?
No, AJAX not needed 🙂
Hi, I was wondering what if you have 3 users registered, how would you show who is logged on or not, all on the same profile.php so users know who is logged in or not?
Arpan-
GREAT ARTICLE! Had a quick question:
I have 4 pages that I would like to require login to view, but they also all share a “”.
What do I need to add to those 4 pages to require login? And where do its go? In the file itself or in header.php?
Thanks!
Hi,
This is unexpected. No error, no message, no nothing.
No matter what I try to open, I get an empty page.
Any idea what to look for?
Sorina
Hi Sorina,
Restart your web server, php & mysql services.
Then check for php error reporting settings in the configuration ini file.
One of the best tutorial. Thank you so much.
You’re welcome! 🙂
On the login page I have not edited anything and I keep getting the error: “Warning: Cannot modify header information – headers already sent by (output started at …login.php:17) in …functions.php on line 11”
This seems to be because redirect_to is being called after the page output has started. How do you suggest fixing this? Why didn’t this show up for you when you originally created this code?
I also have this problem
The script has been updated. Sorry for that. Please try again and check if the error is still there.
Thanks a lot for this tut can you please explain how to edit the user profile
Thanks again for your effort
Actually its up to you that how do you want to edit and personalize. What do you want to do actually?
Fatal error: Call to a member function fetch_array() on a non-object in /home/coldcodrr/public_html/logout.php on line 16
Logout isn’t working, please help!
// update status to offline
$sql = “SELECT status from users WHERE id={$_SESSION[‘user_id’]}”;
$result = $mysqli->query($sql);
$user = $result->fetch_array();
$timestamp = $user[‘status’] – 300;
$sql = “UPDATE users SET status={$timestamp} WHERE id={$_SESSION[‘user_id’]}”;
$result = $mysqli->query($sql);
echo the $_SESSION[‘user_id’] and tell me what are you getting?
In the forgot.php page how do we connect PHPMailer?
Yes I’d like to know this too.
Here is a PHPMailer tutorial -> http://w3epic.com/configure-php-mailer-for-gmail-account/
Just add the code to this script.
Good
Hey! this the best tutorial for this lessons ever! please share it with your friends.
i would like to know how to receive other information for other online users through profile? anyone can help me please!!!!!
What kind of information?
I have faced some problem.
Notice: Use of undefined constant localhost – assumed ‘localhost’ in C:\xampp\htdocs\Project1\profile.php on line 26
Notice: Use of undefined constant root – assumed ‘root’ in C:\xampp\htdocs\Project1\profile.php on line 26
Notice: Use of undefined constant database – assumed ‘database’ in C:\xampp\htdocs\Project1\profile.php on line 26
The error code is in the profile.php
## connect mysql server
$mysqli = new mysqli(localhost, root, “”, database);
Actually the real code is
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); but i have changed it like above n i couldnt find the solution for it.
Could u help me with this and thanks in advance.
Your 3rd line should be require_once(“db-const.php”);
Is it like above? and did you provided your login credentials to db-const.php?
Thanks for this great tut!
Welcome!
It does not work in a mobile environment.
What are the problems that you’re getting?
Good tutorial bro … Good work keep it up !
If you are getting function fetch_array() on a non-object on logout.php
Change to the following
// update status to offline
$sql = “SELECT status from users WHERE id={$_SESSION[‘user_id’]}”;
$result = $mysqli->query($sql);
$user = $result->fetch_array();
$timestamp = $user[‘status’] – 300;
$sql = “UPDATE users SET status={$timestamp} WHERE id={$_SESSION[‘user_id’]}”;
$result = $mysqli->query($sql);
Keep getting this error after the code tries to redirect to any page, be it register, login, go to profile or logout
Warning: Cannot modify header information – headers already sent by (output started at /customers/c/8/0/feedits.com/httpd.www/test login/profile.php:15) in /customers/c/8/0/feedits.com/httpd.www/test login/functions.php on line 11
what do i need to do to correct the redirect_to function
Sir, please provide us with anthoer forget.php file using alternative method to send mail. Otherwise this system is fully working with me. THANKS IN ADVANCE.
Thanks, System is working great, however I am just about to update my site to use Bootstrap, do you have any advice on modifying this script to work with Bootstrap (using Dreamweaver CC 2015), login using modal popups etc
Hi,
thank you so much for the tutorial!
It should be working fine, but whats that?
Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in /Applications/XAMPP/xamppfiles/htdocs/viduals.com/register.php on line 98
I basically can´t register.
Hope you see this, thank´s much,
Oliver
Hello..No doubt this is awesome….
I’m getting this error.
Warning: mysqli::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\register.php on line 31
Warning: mysqli::__construct(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\register.php on line 31
MySQL error no 2002 : php_network_getaddresses: getaddrinfo failed: No such host is known.
any guidance..
I’ve replaced all mysqli to mysql…..
now getting this error
Fatal error: Uncaught Error: Class ‘mysql’ not found in C:\xampp\htdocs\register.php:31 Stack trace: #0 {main} thrown in C:\xampp\htdocs\register.php on line 31
Hi there, i was suffring with a error in register page:-
Trying to get property of non-object in C:\xampp\htdocs\myweb\register.php on line 53
and login page:-
Trying to get property of non-object in C:\xampp\htdocs\myweb\login.php on line 48
thank you for this great lesson….please if I want non login users to also view others profile…..and let a loved in user to view other profile apart form his own how will I do it…. thaks
every thing is ok but when i click on forget password then program demand email id from me and i entered my email id but when i open my email id then there is no any information regarding my password
plz solve this problem
hi there please i need the source code, plz help
Your downloadlink (dropbox) results in Errormessage
Error (429)
This account’s links are generating too much traffic and have been temporarily disabled!
That is the result of beeing so popular 😉
Any alternative download links ?
I’ll replace those broken links ASAP.
Hey, if i open it, (login.php) i see olny white. i have the second time all copy and paste. nothing was working. and maybe you can make a new download link. the link is not longer working. thanks!
The link is updated. https://drive.google.com/file/d/0B8WE4msVmkwzYTR6aEplR1NOdlE/view?usp=sharing
it doesn’t work. again only blank. whats wrong? i know that php does work.
Have you configured db-const.php properly with right credentials?
yes, i know where the error is. its in the connection. not the db-const.php but in the login.php. there you will connect to the database and thats going wrong. this works as well: (i hope you can read it, because its code) it is the 4th line: $conn = mysqli_connect. how to fix it?
i hope this is the right problem. other i ask you or search on the web. have a nice day!
After registering as new user I receive this message :
MySQL error no 1364 : Field ‘status’ doesn’t have a default value
What when wrong?
Thanks in advance.
Sir, please help me urgent, sir iam using your script since 6 moths but now i saw some serious issue on login page as it is not protected from SQL Injection, sir please make some changes in login.php page and make it protected from sql injection..
Please replay waiting for your replay….please…
Hi sir, is there anyway it can display all users and their status whether they are online or offline
The password for the file does not work can you send me a zip please thanks
Email me at [email protected] this is my email I use in places like this so it doesn’t need blocking out thanks
It doesn’t sent me a massage when i submit my email in forgot password. please help me
Hi
I also need the email verification system. Please help me.
send me the required script.
Dear Arpan,
You posted very nice and helpful tutorial. I need a help from you and that is I need a php script for “membership expiration system (for a certain time user will browse the web site)”. Would you kindly share this type of tutorial with full code please?
Hie
I saw your login tutorial.I however have one request from you.Is it possible that you add for me table or field in the database that will hold amounts.I need to use that one as an account system where users login to check their balance that i will be updating from the back-end daily
Hi bro, i want to show list of loge in users active.
how can we see that list of users?
I am having a bit problem in running this project, I have tried your code, may be I am missing something very important.
Hello. I am ltonser. And i need to help. hmmm
Hi,
How can I help you?
CREATE FIELDS USER_STATUS
UPON LOGIN UPDATE THE USER_STATUS TO ACTIVE
CREATE A SQL COMMAND THAT SELECT ONLY ACTIVE USERS
hi sir good evening, i want to create a matrimony website but i am new to php could you please send some scripts to me please. (so far i have created the registration system with some updated options only)