PHP - OOP Login and Sign Up using AJAX/jQuery

Submitted by: 
Language: 
Visitors have accessed this post 7690 times.

Getting Started

Please take note that CSS and jQuery used in this tutorial are hosted so you need internet connection for them to work.

Creating our Database

First step is to create our database.
1. Open phpMyAdmin.
2. Click databases, create a database and name it as login_oop.
3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.

  1. CREATE TABLE `user` (
  2. `userid` INT(11) NOT NULL AUTO_INCREMENT,
  3. `username` VARCHAR(50) NOT NULL,
  4. `password` VARCHAR(50) NOT NULL,
  5. PRIMARY KEY(`userid`)
  6. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

loginoop

Creating our Connection

Next, we create our connection to our database. This will serve as the bridge between our forms and database. We name this as conn.php.

  1. <?php
  2.  
  3. $conn = new mysqli("localhost", "root", "", "login_oop");
  4.  
  5. if ($conn->connect_error) {
  6. die("Connection failed: " . $conn->connect_error);
  7. }
  8.  
  9. ?>

header.php

This contains our header template.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>PHP - OOP Login and Sign Up using Ajax/jQuery</title>
  5. <script src="<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  6. " rel="nofollow">https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></scri...</a> <script src="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  7. " rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></s...</a> <link rel="stylesheet" href="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  8. </head>

" rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
...

index.php

This contains our login form, signup form and our alert.

  1. <?php
  2. if(isset($_SESSION['user'])){
  3. header('location:home.php');
  4. }
  5. ?>
  6.  
  7. <?php include('header.php'); ?>
  8. <body>
  9. <div class="container">
  10. <div style="height:50px;">
  11. </div>
  12. <div class="row" id="loginform">
  13. <div class="col-md-4 col-md-offset-4">
  14. <div class="login-panel panel panel-primary">
  15. <div class="panel-heading">
  16. <h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span> Login
  17. <span class="pull-right"><span class="glyphicon glyphicon-pencil"></span> <a style="text-decoration:none; cursor:pointer; color:white;" id="signup">Sign up</a></span>
  18. </h3>
  19. </div>
  20. <div class="panel-body">
  21. <form role="form" id="logform">
  22. <fieldset>
  23. <div class="form-group">
  24. <input class="form-control" placeholder="Username" name="username" id="username" type="text" autofocus>
  25. </div>
  26. <div class="form-group">
  27. <input class="form-control" placeholder="Password" name="password" id="password" type="password">
  28. </div>
  29. <button type="button" id="loginbutton" class="btn btn-lg btn-primary btn-block"><span class="glyphicon glyphicon-log-in"></span> <span id="logtext">Login</span></button>
  30. </fieldset>
  31. </form>
  32. </div>
  33. </div>
  34. </div>
  35. </div>
  36.  
  37. <div class="row" id="signupform" style="display:none;">
  38. <div class="col-md-4 col-md-offset-4">
  39. <div class="login-panel panel panel-primary">
  40. <div class="panel-heading">
  41. <h3 class="panel-title"><span class="glyphicon glyphicon-pencil"></span> Sign Up
  42. <span class="pull-right"><span class="glyphicon glyphicon-log-in"></span> <a style="text-decoration:none; cursor:pointer; color:white;" id="login">Login</a></span>
  43. </h3>
  44. </div>
  45. <div class="panel-body">
  46. <form role="form" id="signform">
  47. <fieldset>
  48. <div class="form-group">
  49. <input class="form-control" placeholder="Username" name="susername" id="susername" type="text" autofocus>
  50. </div>
  51. <div class="form-group">
  52. <input class="form-control" placeholder="Password" name="spassword" id="spassword" type="password">
  53. </div>
  54. <button type="button" id="signupbutton" class="btn btn-lg btn-primary btn-block"><span class="glyphicon glyphicon-check"></span> <span id="signtext">Sign Up</span></button>
  55. </fieldset>
  56. </form>
  57. </div>
  58. </div>
  59. </div>
  60. </div>
  61.  
  62. <div id="myalert" style="display:none;">
  63. <div class="col-md-4 col-md-offset-4">
  64. <div class="alert alert-info">
  65. <center><span id="alerttext"></span></center>
  66. </div>
  67. </div>
  68. </div>
  69. </div>
  70. <script src="custom.js"></script>
  71. </body>
  72. </html>

custom.js

This contains our jQuery and AJAX codes.

  1. $(document).ready(function(){
  2. //bind enter key to click button
  3. $(document).keypress(function(e){
  4. if (e.which == 13){
  5. if($('#loginform').is(":visible")){
  6. $("#loginbutton").click();
  7. }
  8. else if($('#signupform').is(":visible")){
  9. $("#signupbutton").click();
  10. }
  11. }
  12. });
  13.  
  14. $('#signup').click(function(){
  15. $('#loginform').slideUp();
  16. $('#signupform').slideDown();
  17. $('#myalert').slideUp();
  18. $('#signform')[0].reset();
  19. });
  20.  
  21. $('#login').click(function(){
  22. $('#loginform').slideDown();
  23. $('#signupform').slideUp();
  24. $('#myalert').slideUp();
  25. $('#logform')[0].reset();
  26. });
  27.  
  28. $(document).on('click', '#signupbutton', function(){
  29. if($('#susername').val()!='' && $('#spassword').val()!=''){
  30. $('#signtext').text('Signing up...');
  31. $('#myalert').slideUp();
  32. var signform = $('#signform').serialize();
  33. $.ajax({
  34. method: 'POST',
  35. url: 'signup.php',
  36. data: signform,
  37. success:function(data){
  38. setTimeout(function(){
  39. $('#myalert').slideDown();
  40. $('#alerttext').html(data);
  41. $('#signtext').text('Sign up');
  42. $('#signform')[0].reset();
  43. }, 2000);
  44. }
  45. });
  46. }
  47. else{
  48. alert('Please input both fields to Sign Up');
  49. }
  50. });
  51.  
  52. $(document).on('click', '#loginbutton', function(){
  53. if($('#username').val()!='' && $('#password').val()!=''){
  54. $('#logtext').text('Logging in...');
  55. $('#myalert').slideUp();
  56. var logform = $('#logform').serialize();
  57. setTimeout(function(){
  58. $.ajax({
  59. method: 'POST',
  60. url: 'login.php',
  61. data: logform,
  62. success:function(data){
  63. if(data==''){
  64. $('#myalert').slideDown();
  65. $('#alerttext').text('Login Successful. User Verified!');
  66. $('#logtext').text('Login');
  67. $('#logform')[0].reset();
  68. setTimeout(function(){
  69. location.reload();
  70. }, 2000);
  71. }
  72. else{
  73. $('#myalert').slideDown();
  74. $('#alerttext').html(data);
  75. $('#logtext').text('Login');
  76. $('#logform')[0].reset();
  77. }
  78. }
  79. });
  80. }, 2000);
  81. }
  82. else{
  83. alert('Please input both fields to Login');
  84. }
  85. });
  86. });

signup.php

This contains our signup codes.

  1. <?php
  2. include('conn.php');
  3. if(isset($_POST['susername'])){
  4. $username=$_POST['susername'];
  5. $password=$_POST['spassword'];
  6.  
  7. $query=$conn->query("select * from user where username='$username'");
  8.  
  9. if ($query->num_rows>0){
  10. ?>
  11. <span>Username already exist.</span>
  12. <?php
  13. }
  14.  
  15. elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$username)){
  16. ?>
  17. <span style="font-size:11px;">Invalid username. Space & Special Characters not allowed.</span>
  18. <?php
  19. }
  20. elseif (!preg_match("/^[a-zA-Z0-9_]*$/",$password)){
  21. ?>
  22. <span style="font-size:11px;">Invalid password. Space & Special Characters not allowed.</span>
  23. <?php
  24. }
  25. else{
  26. $mpassword=md5($password);
  27. $conn->query("insert into user (username, password) values ('$username', '$mpassword')");
  28. ?>
  29. <span>Sign up Successful.</span>
  30. <?php
  31. }
  32. }
  33. ?>

login.php

Our login code.

  1. <?php
  2. include('conn.php');
  3. if(isset($_POST['username'])){
  4. $username=$_POST['username'];
  5. $password=md5($_POST['password']);
  6.  
  7. $query=$conn->query("select * from user where username='$username' and password='$password'");
  8.  
  9. if ($query->num_rows>0){
  10. $row=$query->fetch_array();
  11. $_SESSION['user']=$row['userid'];
  12. }
  13. else{
  14. ?>
  15. <span>Login Failed. User not Found.</span>
  16. <?php
  17. }
  18. }
  19. ?>

session.php

This file will be used by our home.html to determine the username of the user that logged in.

  1. <?php
  2. include('conn.php');
  3.  
  4. $query=$conn->query("select * from user where userid='".$_SESSION['user']."'");
  5. $row=$query->fetch_array();
  6.  
  7. $user=$row['username'];
  8. ?>

home.php

Our goto page if login is successful.

  1. <?php include('session.php'); ?>
  2. <?php include('header.php'); ?>
  3. <body>
  4. <div class="container">
  5. <div style="height:50px;">
  6. </div>
  7. <div class="row">
  8. <div class="col-md-4 col-md-offset-4">
  9. <h2>Welcome, <?php echo $user; ?>!</h2>
  10. <a href="logout.php" class="btn btn-danger"><span class="glyphicon glyphicon-log-out"></span> Logout</a>
  11. </div>
  12. </div>
  13. </div>
  14. </body>
  15. </html>

logout.php

Lastly, we need this to destroy our session.

  1. <?php
  2. header('location:index.php');
  3. ?>

That ends this tutorial. If you have any comments, suggestions or questions, feel free to write below or message me. Happy Coding.


Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

This is not oop -> object oriented programing

Great bro well done

Allow me to copy this code. Thank's.

Regiemar Pua

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.