在 php 和数据库中创建登录和注销会话
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21396905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create login and logout session in php and database
提问by user3242335
I want to create login and logout session
我想创建登录和注销会话
My table in mysql database is looking like this
我在 mysql 数据库中的表看起来像这样
CREATE TABLE members (
id int(10) NOT NULL auto_increment,
username varchar(20) NOT NULL,
password varchar(20) NOT NULL, PRIMARY KEY (id) )
ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
and mysql connection named as loginproc.php
和名为 loginproc.php 的 mysql 连接
<?php
// Inialize session
session_start();
// Include database connection settings
$hostname = 'localhost'; // Your MySQL hostname. Usualy named as 'localhost', so you're NOT necessary to change this even this script has already online on the internet.
$dbname = 'database'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
// Let's connect to host
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
/ Select the database
mysql_select_db($dbname) or DIE('Database name is not available!');
// Retrieve username and password from database according to user's input
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '" . mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
$result=mysql_fetch_array($login);
// Check username and password match
if (mysql_num_rows($result) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['user'];
// Jump to secured page
header('Location: securedpage.php');
}
else {
// Jump to login page
header('Location:career.php');
}
?>
Then created securedpage.php
然后创建securepage.php
<?php
// Inialize session
session_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['user'])) {
header('Location: career.php');
}
?>
<html>
<head>
<title>Secured Page</title>
</head>
<body>
<p>This is secured page with session: <b><?php echo $_SESSION['username']; ?></b>
<br>You can put your restricted information here.</p>
<p><a href="logout.php">Logout</a></p>
</body>
</html>
index.php
索引.php
<html>
<head>
</head>
<body>
<form action="loginproc.php" method="post">
UserName:<input type="text" name="user" >
<p> </p>
Password:<input type="password" name="pass" >
<p> </p>
<input type="submit" value=" Login Here " >
<span class="style30">| New?</span>
<a href="signup.php"><span class="style32">Start Here</span>
</form></body></html>
and finally logout page named as logout.php
最后注销页面命名为 logout.php
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['username']);
// Delete all session variables
// session_destroy();
// Jump to login page
header('Location: index.php');
?>
Now my problem is when i am entering username and password it will stay only at index.php , it is not going to another page. please see this code and tell me when i am doing wrong.
现在我的问题是当我输入用户名和密码时,它只会停留在 index.php ,它不会转到另一个页面。请查看此代码并在我做错时告诉我。
Thanks.
谢谢。
回答by sanjeev
Don't use this line
不要使用这条线
$result=mysql_fetch_array($login);
This will fetch the result into $result as an array, and later own you are using mysql_num_rows() function (which is used for resource , i.e in your case $login)
这会将结果作为数组提取到 $result 中,然后拥有您正在使用的 mysql_num_rows() 函数(用于资源,即在您的情况下为 $login)
You the following code
你下面的代码
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '" . mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
// Check username and password match
if (mysql_num_rows($login) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['user'];
// Jump to secured page
header('Location: securedpage.php');
}
else {
// Jump to login page
header('Location:career.php');
}
回答by Partap
I have a solution for your problem. You have to bit modify your code as mentioned below -
我有你的问题的解决方案。您必须按照下面提到的方式修改您的代码 -
<?php
// Inialize session
// 初始化会话
session_start();
//----***Use variabel to capture start time *****------
// Check, if username session is NOT set then this page will jump to login page
// 检查,如果用户名会话未设置,则此页面将跳转到登录页面
if (!isset($_SESSION['user'])) {
header('Location: career.php');
}
?>
And in logout page add one entry as -
<?php
// Inialize session
// 初始化会话
session_start();
// Delete certain session
// 删除某个会话
unset($_SESSION['username']);
//---****Use end time variable ---------
// Subtract previous start time variable and end time variale
// Delete all session variables
// 删除所有会话变量
// session_destroy();
// session_destroy();
// Jump to login page
header('Location: index.php');
?>
?>
回答by Maxi Capodacqua
You have a problem here:
你在这里有问题:
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '". mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
$result=mysql_fetch_array($login);
// Check username and password match
if (mysql_num_rows($result) == 1) {
your query will always retrieves 1 row on mysql_num_rows($result)because it retrieves the countof users with the condition, if no one match the username and password, the query retrieves
您的查询将始终检索mysql_num_rows($result)上的 1 行,因为它检索具有条件的用户数,如果没有人匹配用户名和密码,则查询检索
|count(*)|
+--------+
|0 |
and it is 1 row
它是 1 行
回答by SMS
index.php
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<style>
.head{
margin:auto;
margin-top: 40px;
margin-bottom: 40px;
width: 500px;
height: 50px;
text-align:center;
}
</style>
</head>
<body>
<div class="head"><h1> <span class="strong"></span></h1></div>
<div style="padding:0;" align="center" class="login-page">
<img src="img/oms.png"><br><br>
<div class="form" >
<form class="login-form" name="frm" action="Logging.php" method="POST">
<input type="text" placeholder="username" name="usrname"/>
<input type="password" placeholder="password" name="password"/>
<button type="submit" onclick="return logincheck()">login</button>
<p class="message"> Forgot Password <a href="forgotpass1.php">Click here</a></p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function logincheck()
{
var x = document.frm.usrname.value;
var y = document.frm.password.value;
if(x =="" || x == null){
alert("Enter the Username ");
return false;
}
else if(y=="" || y == null){
alert("Enter the Password ");
return false;
}else{
return true;
}
}
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
<?php include 'footer1.php';?>
</html>
Logging.php
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<style>
.head{
margin:auto;
margin-top: 40px;
margin-bottom: 40px;
width: 500px;
height: 50px;
text-align:center;
}
</style>
</head>
<body>
<div class="head"><h1> <span class="strong"></span></h1></div>
<div style="padding:0;" align="center" class="login-page">
<img src="img/oms.png"><br><br>
<div class="form" >
<form class="login-form" name="frm" action="Logging.php" method="POST">
<input type="text" placeholder="username" name="usrname"/>
<input type="password" placeholder="password" name="password"/>
<button type="submit" onclick="return logincheck()">login</button>
<p class="message"> Forgot Password <a href="forgotpass1.php">Click here</a></p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function logincheck()
{
var x = document.frm.usrname.value;
var y = document.frm.password.value;
if(x =="" || x == null){
alert("Enter the Username ");
return false;
}
else if(y=="" || y == null){
alert("Enter the Password ");
return false;
}else{
return true;
}
}
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
<?php include 'footer1.php';?>
</html>
Logout.php
<?php
include 'header.php';
include 'footer.php';
session_destroy();
echo "<script>alert('Successfully Logged Out');window.location.href='index.php'</script>";
?>
forgotpass1.php
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<style>
.head{
margin:auto;
margin-top: 40px;
margin-bottom: 40px;
width: 500px;
height: 50px;
text-align:center;
}
</style>
</head>
<body>
<div class="head"><h1> <span class="strong"></span></h1></div>
<div style="padding:0;" align="center" class="login-page">
<img src="img/oms.png"><br><br>
<div class="form" >
<form class="login-form" name="frm" action="validateemail1.php" method="POST">
<input type="text" placeholder="Email" name="email"/>
<table width="100%">
<tr><td align="left">
<button type="submit" name="Back" value="Back" onclick="history.go(-1);" >Back</button></td><td>  </td><td align="left"> <button type="submit" name="submit" onclick="return logincheck()">Send Email</button></td></tr></table>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function logincheck()
{
var y = document.frm.email.value;
if(y=="" || y == null){
alert("Enter the Email ");
return false;
}else{
return true;
}
}
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
</html>
<?php include 'footer1.php';?>
validateemail1.php
<?php
include 'dbConfig.php';
if (isset($_POST['submit'])){
$email=$_POST['email'];
$n=0;
$query=mysqli_query($con,"SELECT * FROM signup where email ='".$email."'");
while($row=mysqli_fetch_array($query))
{
$db_email=$row['email'];
if($db_email==$email)
{
$n++;
$to=$row['email'];
$subject = "Your Password ";
$txtn = '<table align="center" border="0" cellpadding="0" cellspacing="0" width="1000">
<tr>
<td align="center" bgcolor="#2ce0e8" style="padding: 7px 0 10px 0;background:#f55322 ">
<img src="http://saiss.co.in/supreme_oms/img/oms.png" alt="http://saiss.co.in/supreme_oms/index" width="84" height="36" style="display: block;" />
</td>
</tr>
<td bgcolor="#ffffff" style="padding: 20px 0 30px 0"><center>Hi ,'.$row["username"].'<br>
Your password is: '.$row["password"].'<br> <a href="http://saiss.co.in/supreme_oms/index.php">Click to Login</a></center>
</td>
<tr>
<td bgcolor="#f55322" style="padding: 25px 0px 18px 23px;color: #fff;font-size: 12px;">
© <?php echo date("Y"); ?> OMS All RIGHTS RESERVED.
</td>
<td align="right">
</td>
</tr>
</table>';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <OMS>' . "\r\n";
mail($to,$subject,$txtn,$headers);
echo "<script>alert('We Sent Password To Your Email Address');window.location.href='index.php';</script>";
}
}
if($n==0)
{
echo "<script>alert('Your email is Not Matching with our database');window.location.href='index.php';</script>";
}
}
?>
Logging.php
<?php
session_start();
include 'dbConfig.php';
$logname = $_POST['usrname'];
$logpass = $_POST['password'];
if(isset($_POST['usrname'])) {
$name = $_POST['usrname'];
}
if(isset($_POST['password'])) {
$name = $_POST['password'];
}
if($logname != null && trim($logname) !="" && trim($logpass) !="" && $logpass !=null)
{
$getvalue ="";
$sql_query = "Select * from signup where username='".$logname."'and password ='".$logpass."'";
$changepass="";
$result_set = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result_set)==0){
echo "<script>alert('Invalid Username/Password');window.location.href='index.php'</script>";
}else{
while($row=mysqli_fetch_row($result_set))
{
$getvalue = $row[0];
$changepass = $row[3];
}
$_SESSION["usrnam"] = $getvalue;
if($changepass=="Y"){
echo "<script>window.location.href='changepassword.php'</script>";
}else
{
echo "<script>window.location.href='dashboard.php'</script>";
}
}
}else{
echo "<script>alert('Invalid Username/Password');window.location.href='index.php'</script>";
}
?>
回答by vee
I see two problems:
我看到两个问题:
mysql_num_rowstakesresourcetype as parameter. You are passing the result ofmysql_fetch_arraywhich can either be an array or FALSE.- You're using deprecated
mysqlextension. You should be using eitherMySQLiorPDOfor new code.
mysql_num_rows将resource类型作为参数。您传递的结果mysql_fetch_array可以是数组或 FALSE。- 您正在使用已弃用的
mysql扩展程序。您应该使用MySQLi或PDO用于新代码。
To fix the mysql_num_rowsproblem in point 1, use if (mysql_num_rows($login)) {:
要解决第mysql_num_rows1 点中的问题,请使用if (mysql_num_rows($login)) {:
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '" . mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
$result=mysql_fetch_array($login);
// Check username and password match
if (mysql_num_rows($login) == 1) {

