会话不会保存任何变量
我有一个登录问题,它检查html表单,它的信息是正确的,它会登录到登录页面。我在登录页面上设置用户名和用户ID信息被检查后,但服务器似乎不会保存信息。奇怪的是,如果我注销,然后使用该网站的运作登录上注册,登录我检查信息然后设置用户名到一个变量然后做会话不会保存任何变量
if(empty($_SESSION['username']))
{
echo "Somthing went wrong";
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=logout.php">';
}
的用户名等,但一旦我去这个不会再次触发该网站第一次在一段时间内我需要查看注销页面之前,我可以注销即使我没有登录,当然注销只会破坏会话。
if (isset($_POST["Username"]) && !empty($_POST["Username"])) {
$salt= "";
$username23 = mysql_real_escape_string($_POST['Username']);
$thereusername = strip_tags($username23);
$password2= sha1 ($salt.$_POST["password"]);
$statement = $db->prepare("SELECT * FROM users WHERE username = ? AND password = ? ");
$statement->execute(array($thereusername,$password2));
$count = $statement->rowCount();
/// If usernam and password match we carry on
if ($count == "1"){
$username23 = mysql_real_escape_string($_POST['Username']);
$thereusername = strip_tags($username23);
$statement8 = $db->prepare("SELECT * FROM users WHERE username = ? ");
$statement8->execute(array($thereusername));
$count8 = $statement8->fetch();
$username233 = mysql_real_escape_string($count8['id']);
$_SESSION['userid'] = strip_tags($username233);
$_SESSION['username'] = $thereusername ;
if(empty($_SESSION['username'])){
echo "Somthing went wrong";
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=logout.php">';
}
if(empty($_SESSION['userid']))
{
echo "Somthing went wrong";
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=logout.php">';
}
echo "You are now being logged in";
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=dashboard.php">';
exit;
echo "works";
}
};
?>
。
<form action="login.php" method="post">
<div class="row">
<div class="form-group col-sm-6">
<label for="exampleInputEmail1">Username</label>
<input class="form-control" type="text" value="Artisanal kale" name= "Username" id="Username">
</div>
<div class="form-group col-sm-6">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" name= "password" id="password"placeholder="Password">
</div>
</div>
<div class="row">
<div class="col-sm-4">
<p> <input type="submit" value="Submit" class="btn theme-btn"> </p>
</div>
</div>
</form>
我当然是在页面的顶部使用会话开始后,我登录它带我到登录页面,但不会显示用户名或任何信息香港专业教育学院做了print_r的会议,并得到阵列()我然后去logout.php和登录和所有作品完美的服务器错误或PHP错误?
首先,不要做你自己的密码salt/encrypt,你需要使用password_hash()
来保存密码哈希和password_verify()
(或者等价的bcrypt)来检查哈希密码vs提交的密码。其次,如上所述,您需要专门使用PDO。最后,您需要制作一些课程,以使您的脚本更易于管理并且更容易排除故障。这更复杂,因为有很多部分需要实现,但这是一个基本的例子,您应该在哪里进行登录等。我会建议,如果你不了解大部分内容,你可能应该下载一个框架,因为这种类型的事情很复杂,无法做到这一点。框架有这一切都建立在,你只需要编写脚本的最高层,大部分...
/core/classes/App.php
class App
{
# Storage of global arrays
protected static $GlobalArray = array();
# Returns post trimmed POST array
public function getPost($key=false)
{
if(!isset(self::$GlobalArray['_POST']))
self::$GlobalArray['_POST'] = $this->sanitizeArray($_POST);
if(!empty($key))
return (isset(self::$GlobalArray['_POST'][$key]))? self::$GlobalArray['_POST'][$key] : false;
return self::$GlobalArray['_POST'];
}
# Trims the values
public function sanitizeArray($array)
{
if(!is_array($array))
return trim($array);
foreach($array as $key => $value) {
$array[$key] = $this->sanitizeArray($value);
}
return $array;
}
}
/芯/类/ user.php的
class User extends App
{
private $con;
public function __construct(\PDO $con)
{
$this->con = $con;
}
public function savePassword($username,$password)
{
# Create the password hash
$hash = password_hash($password);
# Prepare the query and store password hash
$query = $this->con->prepare("UPDATE users SET `password` = ? WHERE `username` = ?");
$query->execute(array($username,$password));
return $this;
}
public function validateUser($username,$password)
{
# Prepare the query to get the user
$query = $this->con->prepare("SELECT * FROM users WHERE `username` = ? LIMIT 1");
$query->execute(array($username));
# Assign password
$user = $query->fetch(\PDO::FETCH_ASSOC);
if(empty($user['password']))
return false;
# Match hash to password
if(!password_verify($password,$user['password']))
return false;
# Return the user data
return $user;
}
}
/core/classes/Session.php
class Session extends App
{
public function toSession($array)
{
foreach($array as $key => $value) {
$_SESSION[$key] = $value;
}
}
# Save to errors array
public function toError($array)
{
foreach($array as $key => $value) {
$_SESSION['errors'][$key] = $value;
}
}
# Get error
public function getError($key=false)
{
if(!empty($key))
return (isset($_SESSION['errors'][$key]))? $_SESSION['errors'][$key] : false;
return (isset($_SESSION['error']))? $_SESSION['error'] : false;
}
# Get value
public function get($key=false)
{
if(!empty($key))
return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
return (isset($_SESSION))? $_SESSION : false;
}
public function start()
{
session_start();
}
public function destroy($key=false)
{
if(!empty($key)) {
if(isset($_SESSION[$key])) {
$_SESSION[$key] = null;
unset($_SESSION[$key]);
}
}
else {
session_destroy();
}
}
}
/config.php
# Create important defines
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('CORE',ROOT_DIR.DS.'core');
define('CLASSES',CORE.DS.'classes');
define('FUNCTIONS',ROOT_DIR.DS.'functions');
# A class autoloader is a must...
spl_autoload_register(function($class){
$path = str_replace(DS.DS,DS,CLASSES.DS.str_replace('\\',DS,$class).'.php');
if(is_file($path))
include_once($path);
});
# Include connection
include(FUNCTIONS.DS.'functions.php');
# Create connection
$db = mysqlconnect();
# Start the session
$Session = new Session();
$Session->start();
/login.php
# Add our config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Create application
$App = new User($db);
# Check if submission login
if(!empty($App->getPost("Username"))) {
# Get the user array (returns on validated)
$User = $App->validateUser($App->getPost("Username"),$App->getPost("password"));
# If user is valid
if($User){
$Session->toSession(array(
'userid'=>$User['id'],
'username'=>$User['username']
));
# Redirect & stop
header('Location: dashboard.php');
exit;
}
else {
# Store the error
$Session->toError(array("invalid_login"=>"Invalid username or password"));
# Redirect to error or whatever...
}
}
我还没有真正确认这一点,但我注意到,让你知道什么做什么(或者应该这样做)。您希望始终在每个*页面的顶部包含config.php
以保持一致性。使用print_r($Session->get());
查看会话数组。另外请注意,如果您没有正确保存密码散列,密码检查将不起作用。
1.不要混合'mysql'和PDO。 2.不要编写自己的密码哈希逻辑,而应使用'password_hash()'。 3.用'session_start()'开始你的脚本。 – jeroen
session_start()位于页面顶部:)总是被告知要在所有内容之前将其添加到顶端 – shadow
我觉得奇怪的是我注销/破坏了会话并且所有工作都正常 – shadow