需要帮助创建自定义用户注册/登录脚本

时间:2014-06-04 02:58:37

标签: php mysql authentication login registration

我正在开设一个网站,我想要求用户拥有一个帐户。如果他们需要帐户,用户会转到registration page,他们会在其中输入他们的姓名,用户名和密码。然后将该数据放入mysql数据库,然后用户可以使用他们的用户名和密码登录login page。未登录,用户无法进入网站的主要部分。

我们的想法是让用户注册用户名,密码和全名,然后让他们能够使用用户名和密码登录。

我想使用与我上面链接的页面相同的界面。

我真的很感激这方面的一些帮助。

编辑:感谢您的帮助!它工作得很好

2 个答案:

答案 0 :(得分:2)

使用以下每个名称(所有.php文件)创建文件。您知道,一旦开始会话,您就可以在session_start()之前使用<!DOCTYPE html>。您应该在网站中的每个php文档之前添加以下代码行:

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

请参阅我的答案的底部,了解'session-renewal.php'的内容。

在您的MySQL表格中(在我的示例中,我称之为表格users),您需要为您的用户提供五个广告位。我已经从我的脚本中复制了此代码,我为用户发送电子邮件而不是用户名,但您可以将所有内容交换掉。您的id列应该是auto_increment。

寄存器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>

寄存器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>

登录-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>

登录-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>

数据库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;
}
?>

会话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
?>

希望这会有所帮助。如果您有任何其他问题,请告诉我。我希望我没有留下任何个人设置......!

答案 1 :(得分:2)

对于这个例子,我将遗漏准备好的陈述,但是你需要对SQL注入预防做一些研究。

首先,您需要一个供用户登录的表单。 这是一个名为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>

您当然可以添加其他字段,例如电子邮件地址等,但我保持简单。

现在让我们转到AddUser.php页面:

<?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>";
?>

因此,用户现在已经创建,密码已经用盐进行哈希并插入到数据库中......严重的是不要忘记SQL注入。

现在,您将拥有一个与NewUser.html表单非常相似的用于登录的表单,但它不会要求输入密码两次。让我们说登录表单将用户发送到名为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();
}
?>

只是提示,如果要添加访问级别,可以使用访问号码(例如:1,2,3)在数据库中存储一个位置,然后在成功登录后,您将分配另一个代表他们的$ _SESSION访问级别,并允许他们访问您允许的某些部分。

现在,当他们导航到您网站上的其他网页时,他们的会话将会像这样进行验证:

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.";
}
?>

养成在每个页面上开始会话的习惯,只有登录的人才能访问。会话会在页面之间被记住。

别忘了给他们一个会破坏会话的登出页面:logout.php

<?php
session_start();

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