PHP-登录页面
我们都认为它能工作,但我测试了它,它没有输出任何东西。它检查是否有会话e.t.c,如果没有,那么它意味着输出一个表单,但它没有任何人可以告诉我我的错误 代码:PHP-登录页面,php,authentication,login,Php,Authentication,Login,我们都认为它能工作,但我测试了它,它没有输出任何东西。它检查是否有会话e.t.c,如果没有,那么它意味着输出一个表单,但它没有任何人可以告诉我我的错误 代码: 我认为如果您从前两行中删除isset,您的问题将得到解决,因此您的第一行应该如下所示: if(!$_SESSION['username'] && ! $_POST['username'] && ! $_POST['password']) { echo $loginForm; } elsei
我认为如果您从前两行中删除isset,您的问题将得到解决,因此您的第一行应该如下所示:
if(!$_SESSION['username'] && ! $_POST['username'] && ! $_POST['password']) {
echo $loginForm;
} elseif(isset($_SESSION['username']) && isset($_POST['username']) && isset($_POST['password'])) {
$grantAccess = login(); //after some serious validation or validate inside
if(!$grantAccess) {
echo 'Test 2';
}
}
我认为如果您从前两行中删除isset,您的问题将得到解决,因此您的第一行应该如下所示:
if(!$_SESSION['username'] && ! $_POST['username'] && ! $_POST['password']) {
echo $loginForm;
} elseif(isset($_SESSION['username']) && isset($_POST['username']) && isset($_POST['password'])) {
$grantAccess = login(); //after some serious validation or validate inside
if(!$grantAccess) {
echo 'Test 2';
}
}
就我个人而言,我尝试将任务分开,这样我就可以把事情搞清楚。我基本上是这样做的。注意,所有函数都将位于它们自己的文件中,并根据需要包含在需要它们的任何页面中。我已注明感兴趣的领域:
<?php
session_start();
// This would be better as a static class so as not to create new connections all the time
// You can populate all the false values here with actual database info
// If you do it here, then the function will not need arguments when you go
// To use it. The only time you would populate the args after this point is if
// you need to connect to multiple databases on the same page.
function Connect($host = false,$username = false,$password = false,$dbname = false)
{
try {
//Create a PDO Session.
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
//Session Attributes.
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
echo "<code><pre>".print_r($e)."</pre></code>";
$con = false;
}
return $con;
}
// Since you are just assigning a variable some html, may as well make it a bit flexible in a function (just incase)
function LoginForm($settings = false)
{
$method = (!empty($settings['method']))? $settings['method']:"post";
$action = (!empty($settings['action']))? $settings['action']:"";
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':"";
$class = (!empty($settings['class']))? $settings['class']:"pure-form";
ob_start();
?>
<form method='<?php echo $method; ?>' action='<?php echo $action; ?>' class='<?php echo $class; ?>' style='color: #000;'<?php echo $id; ?>>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>
</fieldset>
</form>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function fetch($sql = false,$bind = false,$obj = false)
{
if(empty($sql))
return 0;
$query = Connect()->prepare($sql);
if(!$query)
return 0;
$query->execute($bind);
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(!empty($row))
$row = ($obj)? (object) $row : $row;
else
$row = 0;
return $row;
}
function user_login($username = false, $password = false)
{
$st = fetch("SELECT username,password FROM users WHERE username = :username",array(":username"=>$username));
$valid = false;
if($st != 0) {
if($st[0]['password'] == $password) {
$_SESSION['username'] = $row[0]['username'];
$valid = true;
}
}
return $valid;
}
function user_logout($location = 'loggedout.php')
{
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout') {
session_destroy();
header("Location: ".$location);
exit;
}
}
// Include Database Config.
// If you just have $username,$password,$host,$dbname here,
// you can skip this if you just add those values into the Connect()
// function as default arguements
include('../cdn/global/db.php');
//Add static function that listens for logout
user_logout();
// If username set (password is also going to be set)
if(!empty($_POST['username']))
// Get true/false for user hit
echo (user_login($_POST['username'],$_POST['password']))? "Welcome ".htmlspecialchars($_SESSION['username']) : "Invalid username and/or password!";
// If there is no session username, show login form
echo (empty($_SESSION['username']))? LoginForm() : '<a href="?action=logout">Log Out</a>';
?>
>
登录
编辑:在这种情况下我将如何做(一般意义上)
/functions/functions.php
>
登录
login.php
session_start();
包括一次(uuu DIR_uuu.'/functions/functions.php');
用户_注销();
?>
就我个人而言,我会尝试将任务分开,这样我就能把事情搞清楚。我基本上是这样做的。注意,所有函数都将位于它们自己的文件中,并根据需要包含在需要它们的任何页面中。我已注明感兴趣的领域:
<?php
session_start();
// This would be better as a static class so as not to create new connections all the time
// You can populate all the false values here with actual database info
// If you do it here, then the function will not need arguments when you go
// To use it. The only time you would populate the args after this point is if
// you need to connect to multiple databases on the same page.
function Connect($host = false,$username = false,$password = false,$dbname = false)
{
try {
//Create a PDO Session.
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
//Session Attributes.
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
echo "<code><pre>".print_r($e)."</pre></code>";
$con = false;
}
return $con;
}
// Since you are just assigning a variable some html, may as well make it a bit flexible in a function (just incase)
function LoginForm($settings = false)
{
$method = (!empty($settings['method']))? $settings['method']:"post";
$action = (!empty($settings['action']))? $settings['action']:"";
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':"";
$class = (!empty($settings['class']))? $settings['class']:"pure-form";
ob_start();
?>
<form method='<?php echo $method; ?>' action='<?php echo $action; ?>' class='<?php echo $class; ?>' style='color: #000;'<?php echo $id; ?>>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>
</fieldset>
</form>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function fetch($sql = false,$bind = false,$obj = false)
{
if(empty($sql))
return 0;
$query = Connect()->prepare($sql);
if(!$query)
return 0;
$query->execute($bind);
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(!empty($row))
$row = ($obj)? (object) $row : $row;
else
$row = 0;
return $row;
}
function user_login($username = false, $password = false)
{
$st = fetch("SELECT username,password FROM users WHERE username = :username",array(":username"=>$username));
$valid = false;
if($st != 0) {
if($st[0]['password'] == $password) {
$_SESSION['username'] = $row[0]['username'];
$valid = true;
}
}
return $valid;
}
function user_logout($location = 'loggedout.php')
{
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout') {
session_destroy();
header("Location: ".$location);
exit;
}
}
// Include Database Config.
// If you just have $username,$password,$host,$dbname here,
// you can skip this if you just add those values into the Connect()
// function as default arguements
include('../cdn/global/db.php');
//Add static function that listens for logout
user_logout();
// If username set (password is also going to be set)
if(!empty($_POST['username']))
// Get true/false for user hit
echo (user_login($_POST['username'],$_POST['password']))? "Welcome ".htmlspecialchars($_SESSION['username']) : "Invalid username and/or password!";
// If there is no session username, show login form
echo (empty($_SESSION['username']))? LoginForm() : '<a href="?action=logout">Log Out</a>';
?>
>
登录
编辑:在这种情况下我将如何做(一般意义上)
/functions/functions.php
>
登录
login.php
session_start();
包括一次(uuu DIR_uuu.'/functions/functions.php');
用户_注销();
?>
您还可以创建一个类来管理您的用户。让我们创建db.php
类
<?php
require_once 'User.php';
$User = new User();
$form = '';
if($User->is_loggedin()){
$User->redirect('private.php');
}else{
$form = $User->display_login_form();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><?php echo $form; ?></div>
</body>
我们将检查用户是否已登录,如果未登录,则显示登录表单
演示
您还可以创建一个类来管理您的用户。让我们创建db.php
类
<?php
require_once 'User.php';
$User = new User();
$form = '';
if($User->is_loggedin()){
$User->redirect('private.php');
}else{
$form = $User->display_login_form();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><?php echo $form; ?></div>
</body>
我们将检查用户是否已登录,如果未登录,则显示登录表单
演示
您缺少会话\u start()
。另外,如果用户有相同的密码怎么办。。。?您的WHERE
子句应该如下-WHERE username=:username和password=:password
。(你忘了检查用户名)谢谢,在每个需要使用会话的脚本顶部添加了一个新的查询,session_start()应该去哪里。因此,基本上添加了它,但看起来仍然没有任何变化。如果(!isset($\u SESSION['username'])&&!isset($\u POST['username'])&&!isset($\u POST['password']){
是ecessive,您应该只检查$\u SESSION
变量,而不是POST变量,这可能会让您感到悲伤。您缺少SESSION start()
。另外,如果用户有相同的密码怎么办…?您的WHERE
子句应该如下-WHERE username=:username和password=:password
(您忘记检查用户名)谢谢,添加了新的查询,会话从何处开始()go?在每个需要使用会话的脚本的最顶端。因此,本质上添加了它,但看起来仍然没有任何更改。这一行如果(!isset($\u SESSION['username'])&&&!isset($\u POST['username'])和&!isset($\u POST['password']){
是个例外,你应该只检查$\u SESSION
变量,而不是post变量,这可能会让你感到悲伤。完全错误!isset应该在那里100%可能你是对的,但我通常是这样做的,而且它总是有效的,顺便说一句,你必须小心地在页面顶部添加完全错误的内容!isset是mea可能你是对的,但我通常是这样做的,它总是有效的,顺便说一句,你必须小心地添加在页面顶部,准备尝试这个。有点困惑,像位置和静态功能,如注销,你能详细说明这些,以及它们是如何工作的吗?你可以按原样运行页面,它应该都能工作。我是仅建议清理页面,移动新页面上的所有函数并包含它们。根据此页面上的内容include('../cdn/global/db.php');
,您可能需要它,也可能不需要它。此外,要重新itertate,您需要使用数据库凭据填充connect函数中的参数,如:function connect($host='myhost'、$username='root'、$password='mypassword'、$dbname='databasename'){..等等。
当您打开函数Connect()时基本上,这就是我的db.php设置的目的。它所拥有的只是关于它的信息。即将开始集成此代码并尝试它。即将尝试此功能。对类似位置和静态函数(如注销)有点困惑。你能详细说明它们以及它们是如何工作的吗?你可以按原样运行页面,它应该都能工作。我只是suggesting清理页面,移动新页面上的所有函数并包含它们。根据此页面上的内容include('../cdn/global/db.php');
,您可能需要它,也可能不需要它。此外,要重新编写,您需要使用数据库凭据(如:function connect)填充connect函数中的参数($host='myhost'、$username='root'、$password='mypassword'、$dbname='databasename'){..等等。
当你打开函数Connect()时,基本上这就是我的db.php设置的目的。它所拥有的只是关于这个的信息。即将开始集成此代码并尝试它。
<?php
session_start();
require_once 'db.php';
class USER {
private $db;
function __construct() {
$this->db = Db::getDb();
}
public function register($uname, $umail, $upass) {
try {
$new_password = password_hash($upass, PASSWORD_DEFAULT);
//create the activasion code
$activation = md5(uniqid(rand(), true));
$stmt = $this->db->prepare("INSERT INTO users(user_name,user_email,user_pass,active)
VALUES(:uname, :umail, :upass,:active)");
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);
$stmt->bindparam(":active", $activation);
$stmt->execute();
$id = $this->db->lastInsertId('memberID');
$this->sendMail($id, $activation);
$this->redirect('sign-up.php?joined');
return $stmt;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function login($uname, $umail, $upass) {
try {
$stmt = $this->db->prepare("SELECT * FROM `users` WHERE `user_name` = :uname AND `user_email` = :umail LIMIT 1");
$stmt->execute(array(':uname' => $uname, ':umail' => $umail));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
//verifying user.
if (password_verify($upass, $userRow['user_pass']) && $userRow['active'] === 'Yes') {
$_SESSION['user_session'] = $userRow['user_id'];
return true;
} else {
return false;
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
private function sendMail($email,$id, $activation) {
//send email to the user for account activation.
$to = $email;
$subject = "Registration Confirmation";
$body = "Thank you for registering at demo site.\n\n To activate your account, please click on this link:\n\n " . DIR . "activate.php?x=$id&y=$activation\n\n Regards Site Admin \n\n";
$additionalheaders = "From: <" . SITEEMAIL . ">\r\n";
$additionalheaders .= "Reply-To: " . SITEEMAIL . "";
mail($to, $subject, $body, $additionalheaders);
}
//check if the user is logged in
public function is_loggedin() {
if (isset($_SESSION['user_session'])) {
return true;
}
}
// redirect the user.
public function redirect($url) {
header("Location: $url");
}
//user log out
public function logout() {
session_destroy();
unset($_SESSION['user_session']);
return true;
}
//display login form
public function display_login_form() {
return "
<form method='POST' action='' class='pure-form' style='color: #000;'>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>'
</fieldset>
</form>";
}
}
<?php
require_once 'User.php';
$User = new User();
$form = '';
if($User->is_loggedin()){
$User->redirect('private.php');
}else{
$form = $User->display_login_form();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><?php echo $form; ?></div>
</body>