Need help creating custom user registration/login

2019-04-18 01:43发布

问题:

I am working on a website which I would like to require users to have an account for. If they need an account, users go to the registration page, where they put in their name, username, and password. That data is then put into a mysql database, and the user can then use their username and password to login on the login page. Without being logged in, the user is not able to enter the main section of the site.

The idea is to be able to have the user register a username, password and full name, and then for them to be able to login using the username and password.

I would like to use the same interface as the pages I linked to above for it.

I would really appreciate some help with this.

Edit: Thanks for the help! It is working great

回答1:

For this example I'm going to leave out prepared statements, but you'll need to do some research on SQL-injection prevention.

First you need a form for the user to use to login. Here is a basic one that will be on a page called NewUser.html:

<form action="AddUser.php" method="POST">
<p>Enter A Username: </p>
<input type="text" name="User" maxlength="20" size="10">
<br />
<p>Enter A Password: </p>
<input type="password" name="Password" maxlength="40" size="10">
<br />
<p>Enter Password Again: </p>
<input type="password" name="PasswordX2" maxlength="40" size="10">
<br />
<input type="submit" value="Create Account">
</form>

You can of course add other fields such as email address, etc- but I'm keeping it simple.

Now let's go to the AddUser.php page:

<?php

//Now let's grab our $_POST data from our form and assign them to variables...
$User = $_POST['User'];
$PW = $_POST['Password'];
$PW2 = $_POST['PasswordX2'];

//Check whether user put anything in the fields for user or passwords
if (!$User || !$PW || !$PW2) {
echo "You have not entered all the needed info. Please try again.";
exit();
}

//Check if passwords match
if ($PW <> $PW2) {
echo "Your passwords do not match. Please go back and try again.";
exit();
}

//Now we want to be good stewards of passwords and information so let's hash that password
$hash = password_hash($PW, PASSWORD_BCRYPT);

//Open your connection to database
$dbconnect-> blah blah(make your database connection here)....

//Now let's insert the new user into the database - remember do not do this without SQL-injection prevention. I'm just giving you the basics.
$sql = "INSERT INTO UsersTable (UserName, Password)
VALUES ('".$User."', '".$hash."')";

//Verify Successful Entry
if (mysqli_query($dbconnect,$sql)) {
echo "User Added Successfully";
} else {
echo "Error Creating User: " . mysqli_error($dbconnect);
}

echo "<br /><p>Please go to the main page to login now.</p>";
?>

So the user has now been created, password has been hashed with a salt and inserted into DB... seriously don't forget SQL-injection.

Now you'll have a form that is very similar to the NewUser.html form for logging in, but it won't require the password to be entered twice. Let's say that login form sends the user to a page called login.php:

<?php
session_start(); //starts a session for tracking user on each page - this has to be on every page

//Let's get our variables from the POST data- will be identical to before most likely
$User = $_POST['User'];
$PW = $_POST['Password'];

//Open your connection to database
$dbconnect-> blah blah(make your database connection here)....

//Let's see if the username and password matches what we have in the database
$sql = "SELECT UsersTable.UserName, UsersTable.Password
FROM UsersTable
WHERE UsersTable.UserName = '$User'";
$result = $dbconnect->query($sql);

//Let's get the hashed password that corresponds to that username
$row = $result->fetch_assoc();
$HashedPassword = $row['Password'];

//Let's verify the password is correct
if (password_verify($PW, $HashedPassword))
{

//if it is correct(true) this will now happen
$_SESSION['verified_user'] = $User; //registers user by storing it in a SESSION
}
else {
echo "Login failed. Try again.";
exit();
}
?>

Just a tip, if you want to add access levels you can store a place in the database with an access number (ex: 1, 2, 3) and then upon successfully logging in you would assign another $_SESSION that represents their access level and gives them access to certain sections you allow.

Now when they navigate to other pages on your site their session will be verified like this:

ExamplePage.php

<?php
session_start();

if (isset($_SESSION['verified_user'])) {
//User is verified and whatever is here will be visible and happen- YAY!
}
else {
echo "You are not logged in and cannot see this page.";
}
?>

Just get in the habit of starting a session on every page where access is only allowed by those who are logged in. Sessions are remembered from page to page.

Don't forget to give them a logout page which will destroy the session: logout.php

<?php
session_start();

unset($_SESSION['verified_user']);
session_destroy();
echo "You are logged out.";
?>


回答2:

Create files with each of the following names (all .php files). You know that once you start a session you use the session_start() before the <!DOCTYPE html>. You should put the following line of code before each php document in your website:

<?php require_once 'session-renewal.php'; ?>
//and then you have your <!DOCTYPE> ect.

See the bottom of my answer for the contents of 'session-renewal.php'.

In your MySQL table (in my examples I call the table users) you want five slots for your users. I have copied this code from my script where I user emails for the users instead of usernames, but you can swap everything out. Your id column should auto_increment.

register-form.php:

<form action="register-user.php" method="post">
    <input type="text" name="name" placeholder="Your Name">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <input type="submit" value="Register >>">
</form>

register-user.php:

<?php
if ($_POST) {
    $connection = mysqli_connect("/*IP Address or host name*/", "/*username*/", "/*password*/", "/*database name*/") or die(mysql_error());
    require_once 'database-functions.php';
    $name = sanitize($connection, $_POST['name']);
$email = sanitize($connection, $_POST['email']);
    $password = sanitize($connection, $_POST['password']);
    $encrypted_password = generate_password($password);
    if (!empty($name) && !empty($email) && !empty($password)) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $register_status = 'Your email is not valid.';
        } else if (exists($connection, 'email', 'email', $email) || exists($connection, 'email', 'password', $encrypted_password)) {
            $register_status = "It seems you're already a member.";
        } else {
            if (add($connection, $name, $email, $encrypted_password)) {
                $query = verifyLogin($connection, $email, $encrypted_password);
                if ($query == true) {
            ini_set('session.gc_maxlifetime', $inactive_session);
            $_SESSION['logged_in'] = detail($connection, 'id', 'email', $email);
            $_SESSION['last_activity'] = time();
            $_SESSION['name'] = detail($connection, 'name', 'email', $email);
            $_SESSION['email'] = detail($connection, 'email', 'email', $email);
            $_SESSION['privileges'] = detail($connection, 'privileges', 'email', $email);
                    if (isLoggedIn()) {
                $register_status = "Your account has been added!";
            }
            }
        }
    }
    } else {
        $register_status = 'Please fill out all fields.';
    }
    mysqli_close($connection);
} else {
    header('Location: /home');
}
?>
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <p><?php echo $register_status ?></p>
    </body>
</html>

login-form.php:

<form action="login-user.php" method="post">
    <input type="text" name="login_username" placeholder="Username">
    <input type="password" name="login_password" placeholder="password">
    <input type="submit" value="Login">
</form>

login-user.php:

<?php
require_once 'users/database/database-functions.php';

if ($_POST) {
    if (isLoggedIn()) {
        header('Location: /home');
    } else {
        /*database connection script*/
    $email = sanitize($connection, $_POST['login_email']);
    $password = sanitize($connection, $_POST['login_password']);
    $encrypted_password = generate_password($password);
    if (!empty($email) && !empty($password)) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $login_status = 'Your email is not valid.';
            } else if(exists($connection, 'email', 'email', $email) == false) {
                $login_status = "We didn't find anyone with that email and password.";
            } else if (exists($connection, 'email', 'password', $encrypted_password) == false) {
                $login_status = "Please enter the correct password.";
            } else {
                $query = verifyLogin($connection, $email, $encrypted_password);
                if ($query == true) {
                ini_set('session.gc_maxlifetime', $inactive_session);
                $_SESSION['logged_in'] = detail($connection, 'id', 'email', $email);
                $_SESSION['last_activity'] = time();
                $_SESSION['name'] = detail($connection, 'name', 'email', $email);
                $_SESSION['email'] = detail($connection, 'email', 'email', $email);
                $_SESSION['privileges'] = detail($connection, 'privileges', 'email', $email);
                if (isLoggedIn()) {
                    $login_status = 'You have been logged in.';
                }
            }
        }
    } else {
        $login_status = 'Please enter an email and password.';
    }
        mysqli_close($connection);  
    }
} else if (isLoggedIn()) {
    header('Location: /home');
} else {

}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <p><?php echo $login_status ?></p>
</body>
</html>

database-function.php:

<?php
function add($connection, $name, $email, $password) {
    $query = mysqli_query($connection, "INSERT INTO `users` (`name`, `email`, `password`) VALUES ('$name', '$email', '$password')");
    return ($query) ? true : false;
}
function update($connection, $column, $columnValue, $detail, $detailValue) {
    $query = mysqli_query($connection, "UPDATE `users` SET `$column` = '$columnValue' WHERE `$detail` = '$detailValue'");
    return ($query) ? true : false;
}
function isLoggedIn() {
    return (!empty($_SESSION['logged_in'])) ? true : false;
}
function delete($connection, $user_id, $email, $password) {
    $query = mysqli_query($connection, "DELETE FROM `users` WHERE `id` = '$user_id' AND `email` = '$email' AND `password` = '$password'");
    return ($query) ? true : false;
}
function sanitize($connection, $data) {
    return mysqli_real_escape_string($connection, strip_tags($data));
}
function exists($connection, $detail, $row, $value) {
    $query = mysqli_query($connection, "SELECT `$detail` FROM `users` WHERE `$row` = '$value'");
    $count = mysqli_num_rows($query);
    return ($count >= 1) ? true : false;
}
function generate_password($password) {
    $password = sha1($password);
    return $password;
}
function detail($connection, $detail, $row, $value) {
    $query = mysqli_query($connection, "SELECT `$detail` FROM `users` WHERE `$row` = '$value'");
    $associate = mysqli_fetch_assoc($query);
    return $associate[$detail];
}
function verifyLogin($connection, $email, $password) {
    $query = mysqli_query($connection, "SELECT `email`, `password` FROM `users` WHERE `email` = '$email' AND `password` = '$password'");
    $count = mysqli_num_rows($query); //counting the number of returns
    return ($count >= 1) ? true : false;
}
?>

session-renewal.php:

<?php
    session_start();
    $inactive_session = 259200;//forgot to put this here before... this is in seconds and determines how long the user has to be inactive for the session to automatically end. Every time they sign in or visit the page, it resets it, so it's not like it ends three days after they have logged in since the last session ended period, but it ends three days after the most recent visit.
    ini_set('session.gc_maxlifetime', $inactive_session);

    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] >         $inactive_session)) {
        session_unset();     // unset $_SESSION variable for the run-time 
        session_destroy();   // destroy session data in storage
    }
    $_SESSION['last_activity'] = time(); // update last activity time stamp
?>

Hopefully that helps. Let me know if you have any other questions. I hope I didn't leave any of my personal settings in there...!