对于我正在做的项目,我正在使用PHP,我仍然很新。当用户登录或登录时,他们将被定向到主页,我在其中使用$_SESSION
将其登录。通过让会话存储其用户名来使用$_SESSION['user']
。但是,当我尝试从主页切换到配置文件页面时(通过点击他们的名称来执行),它会将我发送回登录屏幕,有效地将其记录下来,就好像他们没有会话一样了。我查看了我的代码,我不知道我做错了什么,或者不做。有人可以告诉我出了什么问题,以及如何在导航其他页面时让我的用户登录?
这是我的signup.php:
<?php
session_start();
/**
* Include ircmaxell's password_compat library.
*/
require 'lib/password.php';
/**
* Include our MySQL connection.
*/
require 'connect.php';
//If the POST var "register" exists (our submit button), then we can
//assume that the user has submitted the registration form.
if(isset($_POST['signUp'])){
//Retrieve the field values from our registration form.
$firstName = !empty($_POST['firstName']) ? trim($_POST['firstName']) : null;
$lastName = !empty($_POST['lastName']) ? trim($_POST['lastName']) : null;
$userName = !empty($_POST['userName']) ? trim($_POST['userName']) : null;
$email = !empty($_POST['email']) ? trim($_POST['email']) : null;
$password = !empty($_POST['password']) ? trim($_POST['password']) : null;
//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Now, we need to check if the supplied username already exists.
//Construct the SQL statement and prepare it.
$sql = "SELECT COUNT(Username) AS num FROM users WHERE Username = :username";
$stmt = $pdo->prepare($sql);
//Bind the provided username to our prepared statement.
$stmt->bindValue(':username', $userName);
//Execute.
$stmt->execute();
//Fetch the row.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
if($row['num'] > 0){
die('That username is already in use.');
}
//Hash the password as we do NOT want to store our passwords in plain text.
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (firstName, lastName, Username, email, Password) VALUES (:firstName, :lastName, :username, :email, :password)";
$stmt = $pdo->prepare($sql);
//Bind our variables.
$stmt->bindValue(':firstName', $firstName);
$stmt->bindValue(':lastName', $lastName);
$stmt->bindValue(':username', $userName);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':password', $hash);
//Execute the statement and insert the new account.
$result = $stmt->execute();
//If the signup process is successful.
if($result){
//What you do here is up to you!
echo 'You are registered.';
$_SESSION['user'] = $userName;
// return $userName;
// //die('debug');
header('Location: home.php');
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sign Up</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Index Custom CSS -->
<link href="css/signup.css" rel="stylesheet">
<!-- Animate.css -->
<link href="css/animate.css" rel="stylesheet">
<!-- Custom styles for this website -->
<link href="css/custom.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<h1 id="loginPrompt">Sign Up</h1>
</div>
</div>
<form class="form-horizontal" role="form" method="post"
action="signup.php">
<div class="form-group">
<label for="inputName" class="col-md-2 col-md-offset-2 control-label">First
Name</label>
<div class="col-md-4">
<input type="text" class="form-control" id="inputName2"
name="firstName" placeholder="John">
</div>
</div>
<div class="form-group">
<label for="inputName2"
class="col-md-2 col-md-offset-2 control-label">Last Name</label>
<div class="col-md-4">
<input type="text" class="form-control" id="inputName2"
name="lastName" placeholder="Doe">
</div>
</div>
<div class="form-group">
<label for="inputUserName"
class="col-md-2 col-md-offset-2 control-label">Username</label>
<div class="col-md-4">
<input type="text" class="form-control" id="inputUserName"
name="userName" placeholder="JDoe">
</div>
</div>
<div class="form-group">
<label for="inputEmail3"
class="col-md-2 col-md-offset-2 control-label">Email</label>
<div class="col-md-4">
<input type="email" class="form-control" id="inputEmail3"
name="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3"
class="col-md-2 col-md-offset-2 control-label">Password</label>
<div class="col-md-4">
<input type="password" class="form-control" id="inputPassword3"
name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-2">
<button type="submit" name="signUp" class="btn btn-default">Sign Up</button>
</div>
</div>
</form>
<div class="container">
<div class = "col-md-8 col-md-offset-2">
<h3 id="signUpMessage"></h3>
</div>
</div>
</body>
</html>
的login.php:
<?php
// if(isset($_POST['submit']))
// {
// $Username = $_POST['email'];
// $email= $_POST['email'];
// $Password = $_POST['password'];
// if($user->login($Username,$email,$Password))
// {
// $user->redirect('home.php');
// }
// else
// {
// $error = "Your Credentials Are Incorrect.";
// }
// }
//login.php
/**
* Start the session.
*/
session_start();
/**
* Include ircmaxell's password_compat library.
*/
require 'lib/password.php';
/**
* Include our MySQL connection.
*/
require 'connect.php';
//If the POST var "login" exists (our submit button), then we can
//assume that the user has submitted the login form.
if($_POST){
//Retrieve the field values from our login form.
$userName = !empty($_POST['userName']) ? trim($_POST['userName']) : null;
$passwordAttempt = !empty($_POST['password']) ? trim($_POST['password']) : null;
//Retrieve the user account information for the given username.
$sql = "SELECT UserID, Username, Password FROM users WHERE Username = :username";
$stmt = $pdo->prepare($sql);
//Bind value.
$stmt->bindValue(':username', $userName);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if($user === false){
//Could not find a user with that username!
//PS: You might want to handle this error in a more user-friendly manner!
echo 'The username does not exist.';
} else{
//User account found. Check to see if the given password matches the
//password hash that we stored in our users table.
//Compare the passwords.
$validPassword = password_verify($passwordAttempt, $user['Password']);
//If $validPassword is TRUE, the login has been successful.
if($validPassword){
//Provide the user with a login session.
$_SESSION['user'] = $userName;
// return $user['Username'];
// return true;
//die('debug');
//Redirect to our protected page, which we called home.php
header('Location: home.php');
} else{
echo 'The user credentials do not match.';
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="Landing Page">
<meta name="author" content="Jordan C. McRae">
<link rel="icon" href="images/favicon.ico">
<title>Login</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Login Custom CSS -->
<link href="css/login.css" rel="stylesheet">
<!-- Custom styles for this website -->
<link href="css/custom.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'>
</head>
<body class="body">
<div class="container">
<div class="col-md-8 col-md-offset-2">
<h1 id="loginPrompt">Log In</h1>
</div>
</div>
<form class="form-horizontal" role="form" method="post"
action="login.php">
<div class="form-group">
<label for="inputUserName" class="col-md-2 col-md-offset-2 control-label">Username</label>
<div class="col-md-4">
<input type="text" class="form-control" id="inputUserName" name="userName" placeholder="JDoe">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-md-2 col-md-offset-2 control-label">Password</label>
<div class="col-md-4">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-2">
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-2">
<button type="submit" name="login" class="btn btn-default">Log in</button>
</div>
</div>
</form>
</body>
</html>
home.php:
<?php
session_start();
require 'connect.php';
/**
* Check if the user is logged in.
*/
// if(!isset($_SESSION['user_id']) || !isset($_SESSION['logged_in'])){
// //User not logged in. Redirect them back to the login.php page.
// header('Location: login.php');
// exit;
// }
if(!isset($_SESSION['user'])){
header("Location: login.php"); }
$sql = "SELECT firstName, lastName FROM users WHERE Username = :username";
$stmt = $pdo->prepare($sql);
//Bind value.
$stmt->bindValue(':username', $_SESSION['user']);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
/**
* Print out something that only logged in users can see.
*/
echo 'Congratulations! You are logged in!';
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>My Closet</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Login Custom CSS -->
<link href="css/home.css" rel="stylesheet">
<!-- Custom styles for this website -->
<link href="css/custom.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a href="profile.php" class="navbar-brand animated fadeInLeft"><?php echo $user['firstName'], " ", $user['lastName'];?></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right animated fadeInRight">
<li><a href="home.php">My Closet</a></li>
<li><a href="shoe.php">Post Shoes</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Help</a></li>
<li><a class="logout" href="index.html">Logout</a><?php session_destroy();?></li>
</ul>
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Find Shoes">
</form>
</div>
</div>
</nav>
<div class="col-md-10 col-md-offset-1 home">
<h1 class="home-header">My Closet</h1>
<?php
?>
<div class="row placeholders">
<div class="col-xs-6 col-sm-3 placeholder">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
<h4>Shoe</h4>
<span class="text-muted">Size</span>
</div>
<div class="col-xs-6 col-sm-3 placeholder">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
<h4>Shoe</h4>
<span class="text-muted">Size</span>
</div>
<div class="col-xs-6 col-sm-3 placeholder">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
<h4>Shoe</h4>
<span class="text-muted">Size</span>
</div>
<div class="col-xs-6 col-sm-3 placeholder">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
<h4>Shoe</h4>
<span class="text-muted">Size</span>
</div>
<div class="col-xs-6 col-sm-3 placeholder">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
<h4>Shoe</h4>
<span class="text-muted">Size</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</body>
</html>
and profile.php:
<?php
session_start();
require 'connect.php';
/**
* Check if the user is logged in.
*/
// if(!isset($_SESSION['user_id']) || !isset($_SESSION['logged_in'])){
// //User not logged in. Redirect them back to the login.php page.
// header('Location: login.php');
// exit;
// }
if (! isset ( $_SESSION ['user'] )) {
header ( "Location: login.php" );
}
$sql = "SELECT firstName, lastName FROM users WHERE Username = :username";
$stmt = $pdo->prepare ( $sql );
// Bind value.
$stmt->bindValue ( ':username', $_SESSION ['user'] );
// Execute.
$stmt->execute ();
// Fetch row.
$user = $stmt->fetch ( PDO::FETCH_ASSOC );
/**
* Print out something that only logged in users can see.
*/
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Profile</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Login Custom CSS -->
<link href="css/home.css" rel="stylesheet">
<!-- Custom styles for this website -->
<link href="css/custom.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Fugaz+One'
rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Fjalla+One'
rel='stylesheet' type='text/css'>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a href="profile.php" class="navbar-brand animated fadeInLeft">
<?php echo $user['firstName'], " ", $user['lastName'];?>
</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right animated fadeInRight">
<li><a href="home.php">My Closet</a></li>
<li><a href="shoe.php">Post Shoes</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Help</a></li>
<li><a class="logout" href="index.html">Logout</a> <?php session_destroy();?></li>
</ul>
<form class="navbar-form navbar-right">
<input type="text" class="form-control" placeholder="Find Shoes">
</form>
</div>
</div>
</nav>
<div class="col-md-10 col-md-offset-1 profile">
<h1 class="profile-header"><?php echo $user['firstName'], " ", $user['lastName'];?></h1>
<div class="col-md-8 col-md-offset-2">
<h3><?php echo $user['address']?></h3>
<h3><?php echo $user['city'], ", ", $user['state'], "", $user['zip']?></h3>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
window.jQuery
|| document
.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')
</script>
<script src="../../dist/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
正如我所说,我还是PHP的新手,在发布我之前我已经查过类似的问题,但我仍然感到困惑和困惑。任何事情都会有所帮助。谢谢你。
更新:
我在Stack Overflow上看了另一篇关于某人如何为用户提供12小时会话的帖子,我尝试实现与我的代码类似的东西,但PHP一直告诉我会话已经启动,但仍然记录当我尝试其他页面的时候我就出去了,所以我仍然想弄明白,但我仍然没有取得任何成功。
答案 0 :(得分:1)
问题在于您的home.php
和profile.php
:
<li><a class="logout" href="index.html">Logout</a><?php session_destroy();?></li>
在呈现页面时执行对session_destroy()
的调用,因此每次都不会在用户按预期点击链接时执行。您需要删除对session_destroy()
的呼叫。而是链接到不同的特定页面以进行注销。