0

I'm new with using PHP. I'd like to add an auto login part to my site, so users are automatically logged in after they create an account on my site. Can someone please tell me how I can automatically log users in after they register? I am not sure where I should be starting. I appreciate all the help you can give me. Thank you so much! :)

Here is my register.php script:

<?php
 ob_start();
 session_start();
 if( isset($_SESSION['user'])!="" ){
  header("Location: /");
 }
 include_once 'dbconnect.php';

 $error = false;

 if ( isset($_POST['btn-signup']) ) {

  $name = trim($_POST['name']);
  $name = strip_tags($name);
  $name = htmlspecialchars($name);

  $email = trim($_POST['email']);
  $email = strip_tags($email);
  $email = htmlspecialchars($email);

  $pass = trim($_POST['pass']);
  $pass = strip_tags($pass);
  $pass = htmlspecialchars($pass);

  $company = trim($_POST['company']);
  $pcompany = strip_tags($company);
  $company = htmlspecialchars($company);

  if (empty($name)) {
   $error = true;
   $nameError = "Please enter your full name.";
  } else if (strlen($name) < 3) {
   $error = true;
   $nameError = "Name must have atleat 3 characters.";
  } else if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
   $error = true;
   $nameError = "Name must contain alphabets and space.";
  }

  if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
   $error = true;
   $emailError = "Please enter valid email address.";
  } else {
   $query = "SELECT userEmail FROM users WHERE userEmail='$email'";
   $result = mysqli_query($conn,$query);
   $count = mysqli_num_rows($result);
   if($count!=0){
    $error = true;
    $emailError = "Provided Email is already in use.";
   }
  }
  if (empty($pass)){
   $error = true;
   $passError = "Please enter password.";
  } else if(strlen($pass) < 6) {
   $error = true;
   $passError = "Password must have atleast 6 characters.";
  }

  $password = hash('sha256', $pass);

  if( !$error ) {

   $query = "INSERT INTO users(userName,userEmail,userPass,userCompany) VALUES('$name','$email','$password','$company')";
   $res = mysqli_query($conn,$query);

   if ($res) {
    $errTyp = "success";
    $errMSG = "Successfully registered, you may login now";
    unset($name);
    unset($email);
    unset($pass);
    unset($company);
   } else {
    $errTyp = "danger";
    $errMSG = "Something went wrong, try again later..."; 
   } 

  }


 }

 //include your login validation
if(empty($errors)){
   //User->login(); or anything you use for validating logins
}

?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <title>Register | Hexa</title>
    <link rel="icon" href="https://app.myhexa.co/favicon.ico" type="image/x-icon">
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,700&subset=latin,cyrillic-ext" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css">
    <link href="plugins/bootstrap/css/bootstrap.css" rel="stylesheet">
    <link href="plugins/node-waves/waves.css" rel="stylesheet" />
    <link href="plugins/animate-css/animate.css" rel="stylesheet" />
    <link href="css/login.css" rel="stylesheet">
</head>

<body class="signup-page bg-blue-grey">
    <div class="signup-box">
        <div class="logo">
            <center><img src="img/logo.png" height="50" width="155"></center>
        </div>
        <div class="card">
            <div class="body"> 
                <form id="sign_up" method="POST">
                <div class="msg"><h3 class="col-blue-grey">CREATE ACCOUNT</h3></div><br>

                                <?php
   if ( isset($errMSG) ) {

    ?>
    <span class="fa fa-exclamation-triangle"></span> <?php echo $errMSG; ?>
                </div>
             </div>
                <?php
   }
   ?>



                    <div class="input-group">

                        <span class="input-group-addon">

                            <i class="material-icons">person</i>
                        </span>
                        <div class="form-line">
                            <input type="text" name="name" class="form-control"  placeholder="Name" maxlength="50" value="<?php echo $name ?>" /">
                        </div>
                    </div>
                                                                   <span class="text-danger"><?php echo $nameError; ?></span><br>

                    <div class="input-group">

                        <span class="input-group-addon">
                            <i class="material-icons">email</i>
                        </span>
                        <div class="form-line">
                            <input type="email" name="email" class="form-control"  placeholder="Email Address" maxlength="40" value="<?php echo $email ?>" />
                        </div>
                    </div>
                                                                   <span class="text-danger"><?php echo $emailError; ?></span><br>

                        <div class="input-group">
                        <span class="input-group-addon">
                            <i class="material-icons">people</i>
                        </span>
                        <div class="form-line">
                            <input type="text" name="company" class="form-control"  placeholder="Company" value="<?php echo $company ?>" />
                        </div>
                    </div><br>
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="material-icons">lock</i>
                        </span>
                        <div class="form-line">
                            <input type="password" name="password" class="form-control" placeholder="Password"  maxlength="15" id="password" required>
                        </div>
                    </div>
                                                                   <span class="text-danger"><?php echo $passError; ?></span><br>

                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="material-icons">lock</i>
                        </span>
                        <div class="form-line">
        <input type="password" name="pass" class="form-control" placeholder="Confirm Password" maxlength="15" id="confirm_password" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <input type="checkbox" name="terms" id="terms" class="filled-in chk-col-deep-orange">
                        <label for="terms">I read and agree to the <a href="javascript:void(0);">terms of usage</a>.</label>
                    </div>

                    <button type="submit" class="btn btn-block btn-lg bg-deep-orange waves-effect" name="btn-signup">REGISTER</button>

                    <div class="m-t-25 m-b--5 align-center">
                        <a href="login">Have An Account?</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="plugins/jquery/jquery.min.js"></script>
    <script src="plugins/bootstrap/js/bootstrap.js"></script>
    <script src="plugins/node-waves/waves.js"></script>
    <script src="plugins/jquery-validation/jquery.validate.js"></script>
    <script src="plugins/js/admin.js"></script>
    <script>var password = document.getElementById("password")
  , confirm_password = document.getElementById("confirm_password");

function validatePassword(){
  if(password.value != confirm_password.value) {
    confirm_password.setCustomValidity("Passwords Don't Match");
  } else {
    confirm_password.setCustomValidity('');
  }
}

password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
</body>

</html>

<?php ob_end_flush(); ?> 
Qirel
  • 25,449
  • 7
  • 45
  • 62
  • Set the same sort of session as you do when they login, after the registration is completed. – Qirel Sep 17 '17 at 21:39
  • You're already using an API that supports **prepared statements** with bounded variable input, you should utilize parameterized queries with placeholders (prepared statements) to protect your database against [SQL-injection](http://stackoverflow.com/q/60174/)! Get started with [`mysqli::prepare()`](http://php.net/mysqli.prepare) and [`mysqli_stmt::bind_param()`](http://php.net/mysqli-stmt.bind-param). – Qirel Sep 17 '17 at 21:44
  • Also, you shouldn't escape ANYTHING on the passwords - and `htmlspecialchars()` is for output - not input (going into the DB). – Qirel Sep 17 '17 at 21:45
  • Here is my login.php file. Which part do I add to register.php? – Hexa Technologies Sep 17 '17 at 21:45
  • I am not storing passwords in plain text. Database: https://app.myhexa.co/img/phpmyadmin.png – Hexa Technologies Sep 17 '17 at 21:48
  • Ah, didn't see that. But you've got a lot of redundant code here, a lot of it could - and should - be stripped out, as a lot of functions are misused here. That being said, the first comment I had suggests how you can achieve what you're trying to do. But as it stands, there's *a lot* of code, and it's a bit much to go through. – Qirel Sep 17 '17 at 21:50
  • @Qirel I didn't put together the php part, just the html. What shouldn't be used? – Hexa Technologies Sep 17 '17 at 21:54
  • `trim()` in it self is fine, `htmlspecialchars()` is totally wrong on input, `strip_tags()` doesn't belong anywhere near a password, and it's unlikely suitable for anything else either, as long as you use `htmlspecialchars()` on *output* (where you display things on the page from the database). Then you should use a preapared statement with a placeholder for the query instead of putting the variable directly in the query. And `if( isset($_SESSION['user'])!="" ){` doesn't do what you'd think it does. You compare a boolean against an empty string. – Qirel Sep 17 '17 at 21:58
  • Any way we can move this conversation to a chat? It's telling me I need more than 1 reputation – Hexa Technologies Sep 17 '17 at 21:59
  • You'd need 20 reputation to join a chat on this site (it's to prevent spamming). https://stackoverflow.com/help/privileges – Qirel Sep 17 '17 at 22:02
  • Anyways, can you simply tell me what code snippet I need to use to automatically log the user in? You were saying something about using what was in the login script. – Hexa Technologies Sep 17 '17 at 22:05
  • Like I said before, set the session like it's done where the user is successfully logged in :-) I can't tell you exactly how, because I don't know what index or value you use. The code you linked to on jsfiddle was the same code you have in the question :p – Qirel Sep 17 '17 at 22:10
  • I hope you're not going live with this code, you will get hacked and your database compromised, if not deleted. – Funk Forty Niner Sep 17 '17 at 23:08
  • Thanks for letting me know @Fred-ii-. I took the jsfiddle down, but I think it would still have been fine since I never shared where the database was located and the database credentials were never in the code snippet. :) – Hexa Technologies Sep 18 '17 at 01:05

1 Answers1

0

From the JSFiddle you linked in the comments, you set the session after a successful login as such

$_SESSION['user'] = $row['userId'];

That means that you'd need to set the $_SESSION['user'] session as the last inserted ID after a completed registration to achieve what you're asking about. You can use the mysqli_insert_id() function to get the last inserted ID. That'd be like this

if ($res) {
    $errTyp = "success";
    $errMSG = "Successfully registered, you may login now";
    $_SESSION['user'] = mysqli_insert_id($conn); // Sets the session and logs the user in instantly
}

Additional info

  • You're already using an API that supports prepared statements with bounded variable input, you should utilize parameterized queries with placeholders (prepared statements) to protect your database against SQL-injection! Get started with mysqli::prepare() and mysqli_stmt::bind_param().

  • You should also use the PHP password_* functions to hash and verify passwords, instead of using sha512.

  • Furthermore, you have if( isset($_SESSION['user'])!="" ){ - which compares a boolean against an empty string. It should be if (isset($_SESSION['user'])) { instead.

  • exit; should be added after every header("Location: .."); call, to prevent the script from executing any further.

  • Finally, functions such as htmlspecialchars() is intended for output and not input. These have nothing to do with "escaping" or sanitizing data, but is used to ensure that HTML is valid when outputting data from a database (and in turn, prevent XSS attacks). Password shouldn't be changed at all - JUST hash them - as the hash might be different if you use other functions on it before/after hashing.

  • strip_tags() might be applicable on the other variables, but I don't believe it fits here (depends, you should understand what the function does, read the manual on strip_tags()).

References

Qirel
  • 25,449
  • 7
  • 45
  • 62
  • Thank you SO much! By adding that extra piece of code, it automatically logs the user in! :) – Hexa Technologies Sep 17 '17 at 22:44
  • Please read the additional info carefully as well, some of it is very important. If you think this answer sufficiently solved your issue, please consider making it as accepted. It tells others that you found a solution, and might show future readers how to solve similar issues. – Qirel Sep 17 '17 at 22:45