PHP Object Oriented Programming
Wall Script
Wall Script
Thursday, February 03, 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.
web notification

116 comments:

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

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

    ReplyDelete
  3. 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.

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

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

    Best Wishes,

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

    ReplyDelete
  7. 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.

    ReplyDelete
  8. 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.

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

    Fabian

    ReplyDelete
  10. 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.

    ReplyDelete
  11. I am fan of this chap...:)

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

    ReplyDelete
  13. 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!!

    ReplyDelete
  14. what OOP design pattern is this MVC ?

    ReplyDelete
  15. how to add different user roles? and how to distinguish between them?

    ReplyDelete
  16. 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 ?

    ReplyDelete
  17. 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.

    ReplyDelete
  18. Thanx very nice one,

    jamil shah afridi

    ReplyDelete
  19. 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.

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

    ReplyDelete
  21. 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

    ReplyDelete
  22. 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.

    ReplyDelete
  23. A better programmer indents ;)

    ReplyDelete
  24. 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.

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

    ReplyDelete
  26. 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??

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

    Thanx !

    ReplyDelete
  28. 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

    ReplyDelete
  29. 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.

    ReplyDelete
  30. Very nice tutorial of OOPS

    ReplyDelete
  31. 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

    ReplyDelete
  32. excelente tutorial

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

    ReplyDelete
  34. 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)

    ReplyDelete
  35. 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!

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

    ReplyDelete
  37. many many thanks....

    ReplyDelete
  38. 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.

    ReplyDelete
  39. 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;
    }
    }

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

    ReplyDelete
  41. 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.

    ReplyDelete
  42. 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.

    ReplyDelete
  43. Well done keep it up

    ReplyDelete
  44. 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???

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

    ReplyDelete
  46. 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

    ReplyDelete
  47. 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

    ReplyDelete
  48. Good Example but not Best

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

    ReplyDelete
  50. nice tutorial man thank u...........

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

    ReplyDelete
  52. Its really awesome tutorial.. Many thanks..

    ReplyDelete
  53. very nice tutorial

    ReplyDelete
  54. 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.

    ReplyDelete
  55. good...
    but can do more...

    ReplyDelete
  56. With fix it works, thx. Simple but good

    ReplyDelete
  57. 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?

    ReplyDelete
  58. very helpfull tutorial i really learned a lot
    great

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

    I'm really interested in your opinion ;)

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

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

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

    ReplyDelete
  63. Thanks a lot. It works good

    ReplyDelete
  64. 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

    ReplyDelete
  65. fantabulous coding style..

    ReplyDelete
  66. 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.

    ReplyDelete
  67. 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

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

    ReplyDelete
  69. 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();
    ?>

    ReplyDelete
  70. is it important to close mysql connection ?

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

    ReplyDelete
  72. 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?

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

    ReplyDelete
  74. 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

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

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

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

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

    ReplyDelete
  79. 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.

    ReplyDelete
  80. 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..

    ReplyDelete
  81. 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]

    ReplyDelete
  82. 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

    ReplyDelete
  83. 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.

    ReplyDelete
  84. Not working logout script
    get_session())
    {
    header("location:login.php");
    }
    if ($_GET['q'] == 'logout')
    {
    $user->user_logout();
    header("location:login.php");
    }
    ?>

    LOGOUT
    Hello get_fullname($uid); ?>

    ReplyDelete
  85. This is a good implementation of the log in. But could you please integrate to mysqli because mysql is already deprecated...

    ReplyDelete
  86. good but long and not friendly

    ReplyDelete
  87. Major Flaw With This Script

    Register And Login With Just Your Username Password not required you can enter anything in the password feild and it will let you login

    ReplyDelete
  88. try to login and refresh the browser. it will automatically logout -_- and also after you login click the back button of the browser theres no validation or atleast make it reload everytime you click the back button -_-

    ReplyDelete
  89. very good work and blog is awesome thanks for sharing and keep it up

    ReplyDelete

  90. ( ! ) Notice: Undefined index: login in C:\wamp\www\PHP_OOP\include\functions.php on line 65
    Call Stack
    # Time Memory Function Location
    1 0.0039 370504 {main}( ) ..\login.php:0
    2 0.0196 402560 User->get_session( ) ..\login.php:6

    ReplyDelete

mailxengine Youtueb channel
Make in India
X