First of all create a database & create a table with the name ‘users’.
CREATE TABLE users ( uid INT PRIMARY KEY AUTO_INCREMENT, uname VARCHAR(30) UNIQUE, upass VARCHAR(50), fullname VARCHAR(100), uemail VARCHAR(70) UNIQUE );
Now as we’ve created our database it’s time for some coding. First we need to get our database in php coding. Create a file named db_config and put the below code in there.
define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_DATABASE', 'oop');
As we can see in the above code we’ve created a class called db_con & in there we’ve defined our db name, user & password.
Now it’s time for the database to get to work. Create a file named class.user.php & put the below listed code:
include "db_config.php"; class User{ public $db; public function __construct(){ $this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE); if(mysqli_connect_errno()) { echo "Error: Could not connect to database."; exit; } } /*** for registration process ***/ public function reg_user($name,$username,$password,$email){ $password = md5($password); $sql="SELECT * FROM users WHERE uname='$username' OR uemail='$email'"; //checking if the username or email is available in db $check = $this->db->query($sql) ; $count_row = $check->num_rows; //if the username is not in db then insert to the table if ($count_row == 0){ $sql1="INSERT INTO users SET uname='$username', upass='$password', fullname='$name', uemail='$email'"; $result = mysqli_query($this->db,$sql1) or die(mysqli_connect_errno()."Data cannot inserted"); return $result; } else { return false;} } /*** for login process ***/ public function check_login($emailusername, $password){ $password = md5($password); $sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'"; //checking if the username is available in the table $result = mysqli_query($this->db,$sql2); $user_data = mysqli_fetch_array($result); $count_row = $result->num_rows; if ($count_row == 1) { // this login var will use for the session thing $_SESSION['login'] = true; $_SESSION['uid'] = $user_data['uid']; return true; } else{ return false; } } /*** for showing the username or fullname ***/ public function get_fullname($uid){ $sql3="SELECT fullname FROM users WHERE uid = $uid"; $result = mysqli_query($this->db,$sql3); $user_data = mysqli_fetch_array($result); echo $user_data['fullname']; } /*** starting the session ***/ public function get_session(){ return $_SESSION['login']; } public function user_logout() { $_SESSION['login'] = FALSE; session_destroy(); } }
I’ve quoted every single line with commenting that which line doing what & which function is using for what. As we can see first of all we’ve included the db connection so that we can have the connection while calling the db connection through a object in constructor.
For the registration process we are first encrypting the password with “md5 hashing” & then searching that if there is any username there in the db already by querying it & if the row is empty then we’re heading to insert the data in database.
For the login process we’re searching for the username & password given by the user & then if it returns true than we’re giving a flag with $_SESSION[‘login’] = true so that when anyone tries to visit the other pages without login we can use this flag stop them.
Then there is a function to get the fullname of the user & after that we’re starting the session & checking that if the user is logged in or not by the get_session() function.
Now the main part are closed it’s time for to generate forms to user. Create a file named login.php & in the very first section put these php code into the file from below:
session_start(); include_once 'include/class.user.php'; $user = new User(); if (isset($_REQUEST['submit'])) { extract($_REQUEST); $login = $user->check_login($emailusername, $password); if ($login) { // Registration Success header("location:home.php"); } else { // Registration Failed echo 'Wrong username or password'; } }
Now put the html work just after the php content you’ve putted in the file.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> OOP Login Module <style><!-- #container{width:400px; margin: 0 auto;} --></style> <script type="text/javascript" language="javascript"> function submitlogin() { var form = document.login; if(form.emailusername.value == ""){ alert( "Enter email or username." ); return false; } else if(form.password.value == ""){ alert( "Enter password." ); return false; } } </script> <span style="font-family: 'Courier 10 Pitch', Courier, monospace; font-size: 13px; font-style: normal; line-height: 1.5;"><div id="container"></span> <h1>Login Here</h1> <form action="" method="post" name="login"> <table> <tbody> <tr> <th>UserName or Email:</th> <td><input type="text" name="emailusername" required="" /></td> </tr> <tr> <th>Password:</th> <td><input type="password" name="password" required="" /></td> </tr> <tr> <td></td> <td><input onclick="return(submitlogin());" type="submit" name="submit" value="Login" /></td> </tr> <tr> <td></td> <td><a href="registration.php">Register new user</a></td> </tr> </tbody> </table> </form></div>
In this form we’re having some validation for the form. Now above the code we’ve included the user class file so that we can have access to that user class. We’ve created a object for the user class & checking that if the submit button pressed than calling the check_login() function to log the user.
Now it’s time for the registration page. Create a file named registration.php & paste the code below in the very first section:
include_once 'include/class.user.php'; $user = new User(); // Checking for user logged in or not if (isset($_REQUEST['submit'])){ extract($_REQUEST); $register = $user->reg_user($fullname, $uname,$upass, $uemail); if ($register) { // Registration Success echo 'Registration successful <a href="login.php">Click here</a> to login'; } else { // Registration Failed echo 'Registration failed. Email or Username already exits please try again'; } }
Then go & post the code below right after your php code.
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> Register <style><!-- #container{width:400px; margin: 0 auto;} --></style> <script type="text/javascript" language="javascript"> function submitreg() { var form = document.reg; if(form.name.value == ""){ alert( "Enter name." ); return false; } else if(form.uname.value == ""){ alert( "Enter username." ); return false; } else if(form.upass.value == ""){ alert( "Enter password." ); return false; } else if(form.uemail.value == ""){ alert( "Enter email." ); return false; } } </script> <div id="container"> <h1>Registration Here</h1> <form action="" method="post" name="reg"> <table> <tbody> <tr> <th>Full Name:</th> <td><input type="text" name="fullname" required="" /></td> </tr> <tr> <th>User Name:</th> <td><input type="text" name="uname" required="" /></td> </tr> <tr> <th>Email:</th> <td><input type="text" name="uemail" required="" /></td> </tr> <tr> <th>Password:</th> <td><input type="password" name="upass" required="" /></td> </tr> <tr> <td></td> <td><input onclick="return(submitreg());" type="submit" name="submit" value="Register" /></td> </tr> <tr> <td></td> <td><a href="login.php">Already registered! Click Here!</a></td> </tr> </tbody> </table> </form></div>
Same as we do in login page we’re passing the form to php by post method it’s capturing them & then passing the values of the form into reg_user() function as parameter.
Now the last part of the tutorial is how to log out. It’s so easy just create a file named home.php the paste the code below in the first section:
session_start(); include_once 'include/class.user.php'; $user = new User(); $uid = $_SESSION['uid']; if (!$user->get_session()){ header("location:login.php"); } if (isset($_GET['q'])){ $user->user_logout(); header("location:login.php"); }
Now to show our user just use html code below after your php code.
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> Home <style><!-- body{ font-family:Arial, Helvetica, sans-serif; } h1{ font-family:'Georgia', Times New Roman, Times, serif; } --></style> <div id="container"> <div id="header"><a href="home.php?q=logout">LOGOUT</a></div> <div id="main-body"> <h1>Hello <?php $user->get_fullname($uid); ?></h1> </div> <div id="footer"></div> </div>
Here we’re first checking that if the user is logged in or not if yes then we’re showing the user full name. For the logout button I don’t know but for the procedural php user it’s kind of new maybe we’re using a link like this “<a href=”home.php?q=logout”>LOGOUT</a>” and above the code in php tag we’re getting the “q” variable with $_GET function & running the function user_logout() to logout.
You can download the source code frome here by simply clicking on the button. .
You can Fork me on Github also for the updated version of this one.
I don’t know this is my first tutorial in php maybe not clear as i know. But if you understand this tuts a little than please leave a comment if you want anything else or what am i mistaking in here.
An enthusiastic of work with over 8+ years of experience. I’m extensively experienced in WordPress, Codeigniter, Laravel.
##Visit my GitHub page (https://github.com/ashawkat)
##Visit my blogging page where I spread out my knowledge around all other people (http://w3programmers.com/author/tanim)
If you want to hire me, you can contact me via email or skype.
Skype: ashawkat89
Email: contact@adnanshawkat.me
Nice one Adnan, Carry on…. 🙂
What about e-mail verification ?
@bonaca: actually this is an easiest login & registration method. this is only for the beginners who wants to start with oop php so that’s why i just didn’t pack the email varification at this code sorry for that!!
Thats why its is so awesome, Gone through many sites to learn oophp, but this one is best for beginers , thank you, 🙂
can you share email verification code
Great one.
Pretty! This has been an extremely wonderful post. Thanks for providing these details.
Amazing! Its truly amazing article, I have got much clear idea on the topic of from this article.
It was very useful, thanks
I am really inspired together with your writing abilities as neatly as with the format in your weblog. Is that this a paid topic or did you modify it yourself? Anyway keep up the excellent quality writing, it is uncommon to see a nice weblog like this one nowadays..
nothing stays paid in the world of web sir… & this is not a paid topic also !! what i tries to do here give the knowledge that i got coz sharing extends more knowledge & i believe that truely !! thanks for the nice comment !! 🙂
how can i remove this warning:
Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\w3progm_oop_login\include\class.user.php:70) in C:\xampp\htdocs\w3progm_oop_login\login.php on line 11
plz say. i am new in php.
put the session variable at the beginning of the php file that will help you .. else use javascript redirect function which is window.location .. 🙂
jus download this script and create database and connect it
add ” ob_start(); ” [without quotes] in the beginning of the code
Somebody essentially help to make critically articles I might state. That is the first time I frequented your website page and thus far? I amazed with the research you made to create this actual put up extraordinary. Wonderful activity!
thanks a lot !! hope this article helps you a lot !! 🙂
this is the part i don’t get it , can u explain it to me ?
first we deal with query verify yes yes bla bla and :
$user_data = mysql_fetch_array($result);
$count_row = mysql_num_rows($result);
if ($count_row == 1) {
$_SESSION[‘login’] = true;
$_SESSION[‘uid’] = $user_data[‘uid’];
yes ofcourse i can explain. while fetching data of the user i’m counting if there’s any other user in that name is stored in my db or not. if yes means 1 row is there in that name than it’ll store that login user name in a session variable & if not than it’ll create an error message, that’s it !!
Excellent post. I’m dealing with a few of these issues as well..
hai..your post oops concept is nice for me..if u dont mind can u please give me ur gmail id??i want talk 2 u on something else??
I am getting error as check_login() function at line 16 is not defined.
I don’t know what to do . Please help !
hlo tanim,
i need a code in php oop without using form from which the data directly inserted into the database. plz help me
you can’t do that. without submitting form how can you insert something. is there any logic? what you can do is may be can do with jquery on hover or click effect by which you can run an ajax request than by that request you can insert something into db. otherwise it’s not possible. there must be a click or hover or some event needs to take place. try study jquery with ajax request. may be it can help you.
You can insert data without form submitting into db , which is called static data.
thanks for ur reply…. i need a code for registration for the testing purpose.
what you need to do is just insert some data using php into mysqli.
when inserting some data for registration use this code for the query
$query = "INSERT INTO users SET uname='Stuttgart', upass='****', fullname='Stuttgart Yeah', uemail'test@test.com',)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
this code will help you to insert your desired data..
I think your insert query is not right. “SET ” is for UPDATE query right?
pleas i want the code of the payment method in the technical support system for college and how can I set the terms of reference of each user if a student or admin , or what is known as URL .. thanks in advance 🙂
For setting the terms of reference of each user you might need to user user role in your system by that you can have the information of each user who’s logging into your system with the credibility. In that way you can provide the terms to each person of that role. And for the payment method what sort of payment method you want to use? Is it paypal or something else? For that you might want to google that or if you’re not able to do this than might want to hire someone who can do this job for you. 🙂
For me it’s getting error while login on the line as (Parse error: syntax error, unexpected T_OBJECT_OPERATOR in C:\xampp\htdocs\oop_log_tuts\include\class.user.php on line 35)
and also getting error on the line 19 as (trying to get property of non-object),i can’t rectify the error ,help me please
I think there’s an object error. According to your first error there seems to be syntax error. Please debug with print_r or var_dump the whole array of objects. Then you might be able to sought out the errors.
As for the second error you’re pulling a non-object file. Please do this in the correct manner. Debug the array of objects. You’ll get the idea of what you’re pulling from the database. May be you’re pulling something like this:
$arr = array(
‘a’=>’ab’,
‘b’=>’cd’
);
with this type of code $arr->a; You should get such arrays with this manner $arr[‘a’]. I think this is the solution. Debug first then you’ll get the answer.
hello, could you please explain to me what “true” and “false” and “return true” mean? i don’t understand 🙁
“true” & “false” is the boolean part. If you get true it means the user entered the corrent information into the database & if you get false that means the user entered the wrong information.
Please w3programmers, I need help to become a good oop php programmer can u guys help me ?
I’m a young and new programmer.
hello, i want create db with “PosgreeSql”.. how that code working.
can you explain..?
Man, you are a gem!
Cool, though no email validation.
it was very helpful thanks a lot 🙂
thank you for the share your code bro..can i ask if do you have login for admin to?
thank you for the share your code bro..can i ask if do you have login for admin? can you share to me bro.
thank you adnan its very useful thanks a lot
sir what is the purpose of $this.db -> in this function of login
This is going to be very useful for me thank you very much for posting
Thanks.
Result on local server:
Notice: Trying to get property of non-object in C:\xampp\htdocs\Niet goed\include\class.user.php on line 28
0Data cannot inserted
Thanks for this article. You have helped me complete a project at my University. 🙂
Can you please help me out with object oriented MVC in php to create a login registration form
sir..nice code.thanks a lot. bt how can i add namespace to it?
wonderfully coded for beginners.Thankyou ADNAN
In class.user.php, What does this line do “$_SESSION[‘uid’] = $user_data[‘uid’];” ?
First time. I am going to share view with you Mr Code provider.
Really Your code is good for fresher developer of php.
Nice Dear.
R K Singh : 9818597149 New delhi (INDIA).
Good Luck.
Great blog you have here but I was curious about if you knew of any message boards that cover the same topics talked about
in this article? I’d really like to be a part of group where I can get comments from other
knowledgeable individuals that share the same interest.
If you have any recommendations, please let me know.
Thanks!
Please try to make the same tutorial by using MySQLi procedural, i’d like to read from you this tutorial.
Thanks.
Warning: myswli_fetch_array() expects parameter 1 Tobe mysqli_result,Boolean given in line no 43.
Notice:trying to get property of non object in class.user.php on line 44.
When I login the above errors are occured please help me on that…
I can’t download file…..
Sir, thanks . Sir How to add profile pic .??? Please add sir .
Very Very Thanks Full Name is working after login
Wonderful post! We are linking to this great post on our site.
Keep up the great writing.
As Salam O Alaikum Thank you so much!
HEy, I am getting this warning
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp64\www\sub\log.php on line 23
But, I checked my code my I followed all tings, which you mentioned in your post.
Any help will be highly appreciated.
2018 still this code is kicking! 🙂
this was what I was looking for… how to call a login from a class! thanks a lot, buddy!
Your web has proven useful to me.
can you help me out object oriented MVC in php to create a login registration form
Salamo Alikom first I really appropriate your effort and your contribution ,thanks for everything .
second I have a notice that the query :
“SELECT uid from users WHERE uemail=’$emailusername’ or uname=’$emailusername’ and upass=’$password'”;
can any one enter email with wrong password will login
must to:
“SELECT uid from users WHERE uemail=’$useremail’ and upass=’$password’ or uname=’$useremail’ and upass=’$password'”;
and again thank you very much
Very shortly this site will be famous among all blogging and site-building visitors, due to it’s pleasant posts
Hello sir,
As i have learned a lot from this tutorial, But i am stuck in case of edit user. I have a view page where all user are shown and I can easily edit ,delete every user. But when I edit single user then how to apply already user register validation check in case of edit. In case of add user, it work fine but in case of edit user, i am stuck. For example, As in a database table, if some entries like xyz@gmail.com already exist. When i go to view page and edit single user whose email id is like pqr@gmail.com, But when he enter xyz@gmail, alert has been shown. Any help would be appreciated.
CSS
Practical
Security
thanks broo