Advertisement
Guest User

Simple signup/ login example by Miro Balearski

a guest
Feb 4th, 2019
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.44 KB | None | 0 0
  1. <?php
  2.  
  3. /****
  4. Db schema
  5.  
  6. create table users (
  7.     id int(10) not null primary key auto_increment,
  8.     username varchar(255) not null unique,
  9.     password varchar(255) not null,
  10.     email varchar(255) not null default ''
  11. );
  12.  
  13. ****/                  
  14.                    
  15.                    
  16. function get_dblink(){
  17.     return  mysqli_connect("localhost","db_username","db_password","db_name");
  18. }
  19.  
  20. function register_form(){?>
  21.     <form method="post" >
  22.         Username :<input type = "text" name="username"><br/>
  23.         Passwod: <input type = "password" name="pass"> <br/>
  24.         Retype Passwod:<input type = "password" name="pass2"><br/>
  25.         <input type="hidden" name="action" value="register"><br/>
  26.         <input type="submit" value="Register"><br/>
  27.     </form>
  28.     <?php
  29. }
  30.  
  31. function login_form(){?>
  32.     <form method="post">
  33.         Username :<input type = "text" name="username"><br/>
  34.         Passwod: <input type = "password" name="pass"><br/>
  35.         <input type="hidden" name="action" value="login"><br/> 
  36.         <input type="submit" value="Login"><br/>
  37.     </form>
  38.     <?php
  39. }
  40.  
  41. function logout_form($username){ ?>
  42.     <form method="post">
  43.         <input type="hidden" name="action" value="logout">     
  44.         Logout <?=$username?> <input type="submit" value="Logout">
  45.     </form>
  46.     <?php
  47. }
  48.  
  49.  
  50. /**************************************************************/
  51.  
  52.  
  53. #Validators :
  54.  
  55. function validate_username_size_and_chars($username){
  56.    
  57.     if(preg_match('/^[a-zA-Z0-9]{5,}$/', $username)) {
  58.         return true;
  59.     }else{
  60.         throw new Exception("The username should contain a-zA-Z0-9 and should be long 5 chars or more ") ; 
  61.     }
  62. }
  63.  
  64. function validate_password_size_and_chars($pass){
  65.    
  66.     if(preg_match('/^[a-zA-Z0-9]{5,}$/', $pass)) {
  67.         return true;
  68.     }else{
  69.         throw new Exception("The password should contain a-zA-Z0-9 and should be long 5 chars or more ");
  70.     }
  71. }
  72. function validate_password_dont_match_the_username($pass, $username){
  73.    
  74.     if($pass===$username){
  75.         throw new Exception("The password can not be the same as the username");   
  76.     }else{
  77.         return true;
  78.     }
  79. }
  80.  
  81. function validate_registration_passwords_match($pass, $pass2){
  82.    
  83.     if($pass===$pass2){
  84.         return true;
  85.     }
  86.     throw new Exception("The passwords don't match");
  87. }
  88.  
  89. function validate_username_available($username){
  90.    
  91.     if(get_user_id_by_username($username)){
  92.         throw new Exception("The username \"$username\" is already registered");
  93.     }  
  94.     return true;
  95. }
  96.  
  97. # DB functions ################################################
  98.  
  99. function authenticate_user($username, $password){
  100.    
  101.     $username= mysqli_real_escape_string(get_dblink(),$username);
  102.    
  103.     $qry = "select id, username, password from users where username='$username' ";
  104.     $res= mysqli_query(get_dblink(), $qry);
  105.     $rr= mysqli_fetch_assoc($res);
  106.    
  107.     return password_verify($password, $rr['password']);
  108. }
  109.  
  110. # Register user
  111.  
  112. function add_user_to_the_database($username,$pass){
  113.    
  114.     $dblink=get_dblink();
  115.    
  116.     $hashed_pass = password_hash($pass, PASSWORD_BCRYPT);
  117.     $username= mysqli_real_escape_string(get_dblink(),$username);
  118.     $qry = "insert into users(username, password) values ('$username', '$hashed_pass')";
  119.  
  120.     mysqli_query( $dblink ,$qry);
  121.     if (mysqli_error($dblink)){
  122.         throw new Exception("Error inserting into the DB ". mysqli_error($dblink));
  123.     }  
  124. }
  125.  
  126. function register_user($username, $pass, $pass2){
  127.    
  128.     try{
  129.         validate_username_size_and_chars($username);
  130.         validate_username_available($username);
  131.         validate_password_dont_match_the_username($pass,$username);
  132.         validate_password_size_and_chars($pass);
  133.         validate_registration_passwords_match($pass, $pass2);
  134.        
  135.             # and finally
  136.         add_user_to_the_database($username,$pass);
  137.  
  138.             # todo email validation
  139.             # or
  140.             # automaticaliy login the new user;
  141.        
  142.         login_user($username, $pass);
  143.    
  144.     } catch (Exception $e){
  145.        
  146.         print_r("<div style='color:red'>".$e->getMessage()."</div>");
  147.     }
  148. }
  149.  
  150. function get_user_id_by_username($username){
  151.    
  152.     $username= mysqli_real_escape_string(get_dblink(),$username);
  153.     $qry = "select id  from users where username='$username' ";
  154.     $res= mysqli_query(get_dblink(), $qry);
  155.     $rr= mysqli_fetch_assoc($res);
  156.     return $rr['id'];
  157. }
  158.  
  159. function login_user($username, $password){
  160.    
  161.     if(authenticate_user($username, $password)){
  162.         $_SESSION['valid_user_id'] = get_user_id_by_username($username);
  163.         $_SESSION['username']=$username;
  164.        
  165.     }else{ 
  166.         print_r("<div style='color:red'>Invalid username or password</div>");
  167.     }
  168. }
  169.  
  170. function loggedin_user(){
  171.     return isset($_SESSION['valid_user_id']) ? $_SESSION['valid_user_id'] : 0;
  172. }
  173.  
  174. function logout_user(){
  175.     session_destroy();
  176.     unset($_SESSION);
  177. }
  178.  
  179. /*****************************************************************************/
  180.  
  181. session_start();
  182.  
  183. # handle http post requests
  184.  
  185. if(isset($_POST['action']))
  186.     switch($_POST['action']){
  187.        
  188.         case "login":
  189.             login_user($_POST['username'], $_POST['pass']);
  190.         break;
  191.         case "logout":
  192.             logout_user();
  193.         break;  
  194.         case "register":
  195.             register_user($_POST['username'], $_POST['pass'], $_POST['pass2']);
  196.         break;
  197.     }
  198.  
  199. # application
  200.  
  201. if(!loggedin_user()){
  202.    
  203.     # show_some_content_for_NOT_logged_in_users_here();
  204.    
  205.     echo "<h1>You are not logged in. Please Login or Register</h1>\n";  
  206.    
  207.     echo "<H2>Login:</H2>\n";
  208.     login_form();
  209.    
  210.     echo "<br><H2>Register:</H2>\n";
  211.     register_form();
  212.  
  213.     # not registered users exprience stops here
  214.     exit(0);
  215. }
  216.  
  217.  
  218. # This content will be available only for logged in users
  219.  
  220. echo "<h1>You are logged in as \"$_SESSION[username]\" </h1>";  
  221. logout_form($_SESSION['username']);
  222.  
  223. # show_content_for_logged_in_users_only();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement