kunalencrypt

Untitled

Feb 26th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.08 KB | None | 0 0
  1.  
  2. <?php
  3.  
  4. session_start();
  5.  
  6. //initialising variables
  7.  
  8. $username = "";
  9. $email = "";
  10. $errors = array();
  11.  
  12. //connect to db
  13.  
  14. $db = mysqli_connect('localhost','root','','practice') or die("couldn't connect to the db");
  15.  
  16. //Register users
  17.  
  18. if (isset($_POST['reg_user'])) {
  19.  
  20. // Receive all input values from the form
  21.    
  22. $username = mysqli_real_escape_string($db, $_POST['username']);
  23. $email = mysqli_real_escape_string($db, $_POST['email']);
  24. $password_a = mysqli_real_escape_string($db, $_POST['password_a']);
  25. $password_b = mysqli_real_escape_string($db, $_POST['password_b']);
  26.  
  27. //form validation : ensure that the form is correctly filled...
  28. // by adding (array_push()) corresponding error onto $errors array
  29.  
  30. if(empty($username))
  31.  {
  32.      array_push($errors, "username is required!");
  33.  }
  34. if(empty($email))
  35.  {
  36.      array_push($errors, "email is required!");
  37.  }
  38. if(empty($password_a))
  39.  {
  40.      array_push($errors, "password is required!");
  41.  }
  42. if($password_a != $password_b)
  43.  {
  44.      array_push($errors, "Password don't match!");
  45.  }
  46.  
  47. // first check the database to make sure
  48. // a user does not already exits with the same username and/or email
  49.  
  50. $user_check_query = "SELECT * FROM user WHERE username = `$username` or email = `$email` LIMIT 1";
  51.  
  52. $result = mysqli_query($db, $user_check_query);
  53. $user = mysqli_fetch_assoc($result);
  54.  
  55. if($user) {       // if user exist
  56.     if($user['username'] === $username)
  57.      {
  58.          array_push($errors, "Username already exists");
  59.      }
  60.     if($user['email'] === $email)
  61.      {
  62.          array_push($errors, "Email already exists");
  63.      }
  64. }
  65.  
  66. // Finally, Register the user if there is no error in the form  
  67.  
  68. if(count($errors) == 0 ){
  69.    
  70.      $password = md5($password_a);   // Encrypt the password before saving in the database
  71.      $query = "INSERT INTO user (username, email, password) VALUES ('$username','$email','$password')";
  72.      
  73.      mysqli_query($db,$query);
  74.  
  75.      $_SESSION['username'] = $username;
  76.      $_SESSION['success'] = "You are now logged in";
  77.  
  78.  }
  79.  header("location: index.php);
  80.  
  81. }
  82.  
  83. ?>
Add Comment
Please, Sign In to add comment