Advertisement
Guest User

Untitled

a guest
Feb 26th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.00 KB | None | 0 0
  1. <?php
  2. session_start();
  3.  
  4. // initializing variables
  5. $username = "";
  6. $email    = "";
  7. $errors = array();
  8.  
  9. // connect to the database
  10. $db = mysqli_connect('localhost', 'root', '', 'registration');
  11.  
  12. // REGISTER USER
  13. if (isset($_POST['reg_user'])) {
  14.   // receive all input values from the form
  15.   $username = mysqli_real_escape_string($db, $_POST['username']);
  16.   $email = mysqli_real_escape_string($db, $_POST['email']);
  17.   $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  18.   $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
  19.  
  20.   // form validation: ensure that the form is correctly filled ...
  21.   // by adding (array_push()) corresponding error unto $errors array
  22.   if (empty($username)) { array_push($errors, "Username is required"); }
  23.   if (empty($email)) { array_push($errors, "Email is required"); }
  24.   if (empty($password_1)) { array_push($errors, "Password is required"); }
  25.   if ($password_1 != $password_2) {
  26.     array_push($errors, "The two passwords do not match");
  27.   }
  28.  
  29.   // first check the database to make sure
  30.   // a user does not already exist with the same username and/or email
  31.   $user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
  32.   $result = mysqli_query($db, $user_check_query);
  33.   $user = mysqli_fetch_assoc($result);
  34.  
  35.   if ($user) { // if user exists
  36.     if ($user['username'] === $username) {
  37.       array_push($errors, "Username already exists");
  38.     }
  39.  
  40.     if ($user['email'] === $email) {
  41.       array_push($errors, "email already exists");
  42.     }
  43.   }
  44.  
  45.   // Finally, register user if there are no errors in the form
  46.   if (count($errors) == 0) {
  47.     $password = md5($password_1);//encrypt the password before saving in the database
  48.  
  49.     $query = "INSERT INTO users (username, email, password)
  50.               VALUES('$username', '$email', '$password')";
  51.     mysqli_query($db, $query);
  52.     $_SESSION['username'] = $username;
  53.     $_SESSION['success'] = "You are now logged in";
  54.     header('location: index.php');
  55.   }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement