9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Thursday, February 3, 2011

PHP Object Oriented Programming

A better programmer follows object oriented programming principals. It is deal with objects and easy to update the code. In this post I want to explain how to develop user registration and login system implementing with object oriented programming in PHP.

PHP Object Oriented Programming

Download Script     Live Demo

The tutorial contains a folder called include with PHP files.
login.php
registration.php
home.php
include
-- functions.php
-- config.php

Database
Sample database users table columns uid, username, passcode, name and email.
CREATE TABLE users
(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) UNIQUE,
password VARCHAR(50),
name VARCHAR(100),
email VARCHAR(70) UNIQUE
);

functions.php
Contains PHP code class User{} contains functions/methods.
<?php
include_once 'config.php';
class User
{
//Database connect 
public function __construct()
{
$db = new DB_Class();
}
//Registration process 
public function register_user($name, $username, $password, $email)
{
$password = md5($password);
$sql = mysql_query("SELECT uid from users WHERE username = '$username' or email = '$email'");
$no_rows = mysql_num_rows($sql);
if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name, email) values ('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}
}
// Login process
public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return TRUE;
}
else
{
return FALSE;
}
}
// Getting name
public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
// Getting session 
public function get_session()
{
return $_SESSION['login'];
}
// Logout 
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}

}
?>

registration.php
Here $user = new User(); is the class User{} object using this calling method $user->register_user{} and inserting values.
<?php
include_once 'include/functions.php';
$user = new User();
// Checking for user logged in or not
if ($user->get_session())
{
header("location:home.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$register = $user->register_user($_POST['name'], $_POST['username'], $_POST['password'], $_POST['email']);
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';
}
}
?>
//HTML Code
<form method="POST" action="register.php" name='reg' >
Full Name
<input type="text" name="name"/>
Username
<input type="text" name="username"/>
Password
<input type="password" name="password"/>
Email
<input type="text" name="email"/>
<input type="submit" value="Register"/>
</form>

login.php
Calling method $user->check_login{} for login verification.
<?php
session_start();
include_once 'include/functions.php';
$user = new User();
if ($user->get_session())
{
header("location:home.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$login = $user->check_login($_POST['emailusername'], $_POST['password']);
if ($login)
{
// Login Success
header("location:login.php");
}
else
{
// Login Failed
$msg= 'Username / password wrong';
}
}
?>
//HTML Code
<form method="POST" action="" name="login">
Email or Username
<input type="text" name="emailusername"/>
Password
<input type="password" name="password"/>
<input type="submit" value="Login"/>
</form>

home.php
<?php
session_start();
include_once 'include/functions.php';
$user = new User();
$uid = $_SESSION['uid'];
if (!$user->get_session())
{
header("location:login.php");
}
if ($_GET['q'] == 'logout')
{
$user->user_logout();
header("location:login.php");
}
?>
//HTML Code
<a href="?q=logout">LOGOUT</a>
<h1> Hello <?php $user->get_fullname($uid); ?></h1>

config.php
Database configuration class DB_class() function __construct() is the method name for the constructor.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
class DB_Class
{
function __construct()
{
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or
die('Oops connection error -> ' . mysql_error());
mysql_select_db(DB_DATABASE, $connection)
or die('Database error -> ' . mysql_error());
}
}
?>

How to add new function/method.
For example if you want to get email value. Just include the following function inside class User{}
public function get_email($uid)
{
$result = mysql_query("SELECT email FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
echo $user_data['email'];
}

Print email values.
<?php $user->get_email($uid); ?>

If you're planning to start running a website and you'll be using PHP. You can check the dirrerent web hosting plans online. Some even offer a free domain name.
Comments
{ 106 comments }
Anonymous said...

very helpful, I've been looking for this tutorial for many days, thanks alot!

Михаил said...

Thanks a lot for this topic. It very helped me with my first project=)

Anonymous said...

Hi,
I just need to say that this is not the real power of PHP OOP.You are using it wrong == Your classes are just collections of methods, and your
public function __construct()
{
$db = new DB_Class();
}
is wrong. NEVER INITIATE db connection in the constructor.

REAL PHP OOP is more complex, and nothing like this.

dskanth said...

Good startup tutorial....

noel balaba(noprobz09) said...

nice tutorial...keep on sharing...I like it...

sarunathan said...

That was an excellent code. . .

Seyha said...

That was the best code...
And I want you to implement the crud function.
If you have time please do it ASAP.

Best Wishes,

ben said...

I love snippets. Love 'em. thanks for this @bentrem

Seyha said...

ha.., I have an error after I test your code on localhost.

When I access this link: http://localhost/test/PHP_OOP/login.php

I have an error say that: Notice: Undefined index: login in C:\wamp\www\test\PHP_OOP\include\functions.php on line 65

When I log in success: I have an error say like this: Notice: Undefined index: q in C:\wamp\www\test\PHP_OOP\home.php on line 13

Could u help me to solve this problem?

Thanks in advances.

Olinklist said...

I agree with Anonymous about OOP in PHP syntax is more complex.

But in this article reminds me of when I first created the initial website design with OOP syntax code.

This process, not everyone will understand, but the quality of syntax in a system requires in-depth knowledge about the functions of PHP.

Anonymous said...

Esta super entendible tu explicacion... Muchas gracias...

Fabian

Mehedi Hasan said...

Thanks for this great tutorial.

Anonymous said...

Thanz mate, well done. I have been try looking for how to combine data which is submited by form and object. This is the very good one.

Anonymous said...

I am fan of this chap...:)

jaygizer said...

Thank u srinivas your a big help in our Career! Thank u so much! may God bless you...

Sachin said...

u know what u are simply superb mannn!!!
awesum!!
i have lookin for dis systematic way of coding for a long tym....
thnk u bro!!!!! cheers!!

Anonymous said...

what OOP design pattern is this MVC ?

Anonymous said...

how to add different user roles? and how to distinguish between them?

munge83 said...

Hy somehow before I dident remove this code from register.php
if ($user->get_session())
{
header("location:home.php");
}

I't didn't wonted to go to registration I't always put me back to login if I click to register new user
Is that an mistake ore what ?

Raza Rahil Hussain said...

Hello, I want to add userlevel in script like if user_level=2 we consider it admin and if its 1 the user is normal.
Now i want to add script where admin user are able to see more content like add user, delete user.
Urgent Help needed.

jamil said...

Thanx very nice one,

jamil shah afridi

RRPowered said...

Srinivas great post again.

Koustav said...

thank U so MUCH

Anonymous said...

very helpful tutorial, thanks..
i'm using XAMPP 1.7.4 [PHP: 5.3.5]
i got error when i execute this code.
error:
Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 80

Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 166

Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config\Container.php on line 111

Fatal error: Class 'DB_Class' not found in C:\xampp\htdocs\oops\include\functions.php on line 10

Any one pls assist me.

Anonymous said...

Cool i find this for a long time.. thank you !

Anonymous said...

hey there is no register.php file in tutorial thn how can u give action=register.php in the form please reply ASAP.

thnk u

Anonymous said...

Following Instructions:
Notice: Undefined index: login in C:\Inetpub\wwwroot\atp-software\serial-safe\include\functions.php on line 54

If using downloaded source:
Notice: Undefined index: login in C:\Inetpub\wwwroot\atp-software\serial-safe\include\functions.php on line 65

Please correct code.

Anonymous said...

A better programmer indents ;)

Ravi Kumar Jangra said...

Hello every one

there is a mistake in ( registration.php ) file please correct u all

when a user will not be login in how the session value will be in memory

remove the following header line

// Checking for user logged in or not
if ($user->get_session())
{
header("location:home.php");
}


because user has to register first then he will be logged in give him chance to register.

Program is very nice and helpful.

Thank you Very Much.

Sharvy said...

This is a GREAT Beginner Tutorial! Could we have some ADVANCED PHP tutorials using FRAMEWORKS?
Thank you Brother for this extra-ordinary tech blog!

Mustafa said...

Thats nice and helpful, but for long time, i'v thinking, whats wrong if we use functions instead of class? i mean, same thing, if we use (echo functionName) instead of (echo $user->functionName), if i am wrong, or my opinion has something wrong, please let me know, i really dont know what to use, for sure for me and others its more easy to use a direct function, but does have something better that function??

Anonymous said...

You see man, Its a great workout for a bigginer ! There always a stepping stone and surely this was it for me !

Thanx !

rpms said...

GREAT! stuff Srinivas. I got so very much from your kind sharing.
I will share all errors & the solutions that worked for me...
<---IN fixes:
functions.php:
Fatal error: Class 'DB_Class' not found in F:\xampp\htdocs\Randy\include\functions.php on line 10
Fix : line#3: include_once 'config.php' -> include_once 'include/config.php';

Notice: Undefined index: login in F:\xampp\htdocs\Randy\include\functions.php on line 64
Fix : line#64 added an if exists test.. if (isset($_SESSION['login'])){

register.php
Loop : have to comment out line #9 or can't get to register from login page.
Fix : line#9 #header("location:login.php");

home.php
Notice: Undefined index: q in F:\xampp\htdocs\Randy\home.php on line 13
Fix : check using isset.. line#13 if (isset($_GET['q']))
FIN---> fixes

RS said...

Hi. I have spent a couple of days with this work by Srinivas. Now I converted the code to use MySQLi from the MySQL that is in the original work. This makes for a more overall OOP approach. Also added some more
functionality for retrieving user data.
If you would like to get a set of the files I created they are
here >> http://members.shaw.ca/rskret/offSite/PHP_OOP2.zip

Thank you for your valuable posting Srinivas.

Anonymous said...

Very nice tutorial of OOPS

Elton Jain said...

THERE IS A HUGE MISTAKE HERE. IT DOESN'T WORK.
DURING REGISTRATION, IF YOU TRY TO USE mysql_insert_id($connection), it will give error (Notice: Undefined variable: connection...)
There is a problem with the scope.

Kindly rectify and reply on elton2jain{at}gmail.com

Anonymous said...

It's nice

Anonymous said...

excelente tutorial

aziz said...

Fatal error: Class 'User' not found in C:\xampp\htdocs\login.php on line 4 fix me plss this probllem

Templus said...

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'username'@'localhost' (using password: YES) in C:\xampp\htdocs\config.php on line 10
Oops connection error -> Access denied for user 'username'@'localhost' (using password: YES)

Anonymous said...

Hi there,

I did not read it all not yet, but finally a COMPLETE (realistic) example which show you how php oop and a database is set up. Thanks a lot!

suchi said...

Very good post. Thanks for that kind of post. Waiting for next.

Anonymous said...

many many thanks....

Kevlyn said...

Can you give me an idea to load all the classes for once and wont reload for the next page to save the loading time. I can do it with jquery and PHP but want to do it only with php.

th3phantom said...

login doesn't working because there is a mistake at check login function in user class and this is a fixed code for that function :

public function check_login($emailusername, $password)
{
$password = md5($password);
$email = $_POST["emailusername"];
$username = $_POST["emailusername"];
$password = $_POST["password"];

$result = mysql_query("SELECT uid from users WHERE email = '$email' or username='$username' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);

if ($no_rows == 1)
{

$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return TRUE;
}
else
{
return FALSE;
}
}

Anonymous said...

Dear How can i close the mysql connection basis of this tutorial?

sovy said...

Thanks

James said...

Nice tutorial :D

Peter said...

This is in response to the "Hi,
I just need to say that this is not the real power of PHP OOP. " comment. If you disagree so much with this article being called OOP PHP, then it would be useful and helpful if you could provide a link to something that you consider better or something that could supplement this tutorial.

Andrew said...

Nice tutorial, but just saying, no one should use this script on a live site. Or at least filter all database connnections with mysql_real_escape_string and change the md5() to hash() with a better algorithm. Or else your site will get hacked pretty fast.

Raffy Egcas Arevalo said...

big help to us beginners

Anonymous said...

Well done keep it up

Anonymous said...

when i m running this code in localhost, its not working, following error are shown:


Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 80

Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 166

Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config\Container.php on line 111

Fatal error: Class 'DB_Class' not found in C:\xampp\htdocs\PHP_OOP\include\functions.php on line 10

how to remove these errors???

AF shop said...

The blog is absolutely fantastic. Lots of great information and inspiration, both of which we all need. Thanks.

Anonymous said...

I got this error
"Warning: include_once(include/functions.php) [function.include-once]: failed to open stream: No such file or directory in C:\wamp\www\zz\home.php on line 3"

kindly help me to fix this .. thanks

Anonymous said...

Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 80

Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 166

Fatal error: Class 'DB_Class' not found in C:\xampp\htdocs\login\include\functions.php on line 10

anybody plz fix this problem

Anonymous said...

Good Example but not Best

Anonymous said...

nice blog.very helpful.but,i am not able to $_SESSION['uid'] in the next page??????????

Sudhakar Narra said...

nice tutorial man thank u...........

JoJo said...

Nice tutorial i'm learning very much from you !
Keep goin' on ! : D

jonyalam said...

Its really awesome tutorial.. Many thanks..

Anonymous said...

very nice tutorial

Anonymous said...

I second the comments above about this not using OOP to its full advantages (inheritance and polymorphism).

Also, I realize this isn't a security tutorial but to point out just one of vulnerabilities: NEVER concatenate external input in a query. Since you are using MySQL use PDO. Even the mysql_real_escape_string would have been a start (even though it is futile), but prepared statements via PDO is the way to go.

Anonymous said...

good...
but can do more...

conflict said...

With fix it works, thx. Simple but good

joelevis said...

I have a silly doubt.
The class DB_Class is called everytime a 'User' object is created. and 'User object is created in every page,login,home,registration' . Isn't it weird everytime DB_Class gets called and attempts database connection for every page. Doesn't it slow down the performance?
Or Am I missing out something basically?

abhishek shukla said...

very helpfull tutorial i really learned a lot
great

Roca said...

tnx a lot..

Anonymous said...

Thanks

Albert said...

Hi, I was wondering how you would implement this with use of RedBean. An PHP ORM system.

I'm really interested in your opinion ;)

shiny said...

its really helpfull for me as i a beginer
but can send some tutorials on oops in php
so i can became like you............ ;)

Roldan Villaber said...

I would not forget this tutorial. This is a good tutorial.

MAHESH said...

It is very better if session time out also included with session id

Ajay Dev said...

:-)

nisha said...

Thanks a lot. It works good

Jay Khatri said...

return $_SESSION['login'];
I got error in this Line plz Do something
i got Error from server like
Notice: Undefined index: login in C:\wamp\www\18\include\functions.php on line 65
Call Stack
Time Memory Function Location
0.0008 370416 {main}( ) ..\login.php:0
0.0249 402424 User->get_session( ) ..\login.php:6

Anonymous said...

fantabulous coding style..

Raffy Egcas Arevalo said...

good

anuj subedi said...

thank god I got u...

Anonymous said...

hi,
it is really a good tutorial but i am looking for a tutorial in which you tell me about updating(edit) data in the database using oop's concept in php.
i am looking for it for long.hope, you can help me in this regard.

Jules said...

Please, could you explain me, how to add a new function to my class, but this new function must show different datas from my database table, for example:

Uid --- Name --- Lasname --- Age
01 --- John --- Brown --- 25
02 --- Mery --- White --- 28

public function get_user_profile($uid)
{
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
.....
}

and use

get_user_profile($uid); ?> or some like that....

but i need only show "age", and in other field show only "Name" for example, but in the same function, becasue in different functions i know do it.

Sorry, but I am a begginer with Object Oriented Programming

Thanksss in advance

Mehedi Hasan said...

Good But Not So easy .....

Anonymous said...

MD5 to hash a password? Are you for real? Please no one use this code on a live website! Please never.

administrator said...

hello please help me
the code is working but not inserting the data into database please help me out

username=$Postedusername;

$this->password=$postedpassword;


}
//constructor for connecting the database
public function __construct()
{
$connect=mysql_connect("localhost","root","usbw") or die ("couldnt connect!");
mysql_select_db("prototype") or die ("couldnt find db");
echo "connected";
}

//inserting the data into data base
public function insert()
{
$inputusername=$this->username;
$inputpassword=$this->password;
$check=mysql_query("SELECT * FROM Register WHERE username='$inputusername'");
$count=mysql_num_rows($check);
if($count!=0)
{
echo"user already exist";

}
else
{
$insert=mysql_query("INSERT INTO register VALUES ('','$inputusername','$inputpassword')");

echo"inserted successfuly";
}

}
}
//creating the object of type basic
$user= new basic;
//calling the methodes
$user->post('ali','itsseceret');
$user->insert();
?>

Anonymous said...

good.........

Question said...

is it important to close mysql connection ?

Anonymous said...

a very good for beginners but need to explian keywords saperately in starting.

Digambar said...

Hi,
Very helpful but getting below mentioned prblem

Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 80

Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 166

Notice: Undefined index: login in C:\xampp\htdocs\oops\login\includes\functions.php on line 45

can anybody help me please?

kumaresh kumaresh said...

This tutorial is very helpful for me to understand the oops concepts. thanks again...

S.PremKumar said...

update it with email validation

Anonymous said...

thanks alot

saroj said...

I got error on localhost

http://localhost/php_oops/
error: http://localhost/php_oops/login.php
how to resove it
and
http://localhost/php_oops/register.php
error:Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 80

Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\php\PEAR\Config.php on line 166

Fatal error: Class 'DB_Class' not found in C:\xampp\htdocs\php_oops\include\functions.php on line 10

Anonymous said...

error wht do yar
Notice: Undefined index: Login in C:\wamp\www\loginfun\class.php on line 34

Yugant Khokhar said...

Thanks a lot

Cheenu said...

Thanks a lot it was very helpful.....

Rakesh Ranjan Tiwari said...

Tanks a lot..
How to add different user roles? and how to distinguish between them?

paul said...

That is nice. Petty things like indentation should not worry some people very much. Keep it up!

Srilankatourguidedriver said...

There I have got following error..
Fatal error: Class 'DB_Class' not found in "C:\xampp\htdocs\PHP_OOP\include\functions.php on line 10"

It sloved using this
"$filepath = realpath (dirname(__FILE__));
require_once($filepath."/config.php");"
for
"include_once 'config.php';" in functions.php file.

Anonymous said...

nice...

Shumani Masakona said...

Thanx a lot,its very helpful

manni said...

session var error comes when i run login.php page and new registration link doesn't work, pl help me out, this login app not working at all..

Anonymous said...

Good Script, but this is vulnerable to XSS.
What is someone regieters with
fullname :
<script>alert(\this is your cookie\+document.cookie)</script>
username : thisis
password : thisis
email : thisis

Script will get executed.
try username : thisis ; password : thisis

[TechnoKnol]

Karl Limlengco said...

When I access this link: http://localhost/test/PHP_OOP/login.php

I have an error say that: Notice: Undefined index: login in C:\wamp\www\test\PHP_OOP\include\functions.php on line 65

Inamullah Buksh said...

very nice code

Mohd Rehan said...

thank you! it's very nice.

Ashwin Pathak said...

You should never use query like this: SELECT id FROM users WHERE emai = $email AND password = $password.
Instead you should always use query like this: SELECT id, password FROM users WHERE email = $email
and then to use mysql_row or mysql_fetch_array or any other to grad the password and then to compare it with the submitted password.

Post a Comment