PHP会话变量不会持久化

时间:2014-06-06 21:58:01

标签: php session cookies session-variables session-cookies

我正在创建一个使用会话存储登录详细信息的网站 - 我知道这是一个糟糕的安全措施,但稍后会处理;现在我只需要解决这个问题。第1页从登录表单获取登录详细信息并将其存储在会话中。第2页用于显示这些变量,但在尝试访问变量时出现这些错误:

Notice: Undefined index: email in /customers/0/4/0/my-domain.com/httpd.www/upload-photo.php on line 10
Notice: Undefined index: password in /customers/0/4/0/my-domain.com/httpd.www/upload-photo.php on line 11

这是代码 - 我已经不相关的部分: 第1页

session_start();
var_dump($_SESSION);
ini_set('display_errors',1); 
error_reporting(E_ALL); 

// Just logged in
if($_POST["email"] != "" || $_POST["password"] != ""){
$email = strtolower($_POST["email"]);
$password = md5($_POST["password"]);

$_SESSION["email"] = $email;
$_SESSION["password"] = $password;

//echo "setting details from http post";
}else{
// Just redirected to this page
$email = $_SESSION["email"];
$password = $_SESSION["password"];  
}

第2页,我收到上述错误:

session_start();

ini_set('display_errors',1); 
error_reporting(E_ALL); 

var_dump($_SESSION);

$_SESSION["advert"] = $_GET['id'];
echo $_SESSION["email"];
echo $_SESSION["password"];

我搜索了SO并确保在session_start();之前没有空格或其他内容 顺便说一下,如果它帮助我正在使用的域名公司是One.com

3 个答案:

答案 0 :(得分:1)

$_SESSION["email"]$_SESSION["password"]if中设置,因此在跳过的情况下,您会得到此未定义的索引错误(因为此索引的元素之前未定义过)。要删除此Notice,您可以使用isset()函数(也可以使用它来验证$_POST用户输入)。示例:

echo isset($_SESSION["email"]) ? $_SESSION["email"] : 'There is no element with key "email"';

P.S。验证您的POST输入:

if(isset($_POST["email"]) && isset($_POST["password"])){}

答案 1 :(得分:1)

将条件更改为:

if(isset($_POST['email']) && isset($_POST['password'])){
  //do login
}
else {
    echo " Plese enter email and password";
}

完整:

的login.php

<?php
//here must be totaly clear, nothing can't be here
session_start();

if(isset($_POST['email']) && isset($_POST['password'])){
   $_SESSION['email'] = $_POST['email'];
   $_SESSION['password'] = $_POST['password'];
}
else {
   echo "Please enter email and password";
}

//here must be form to login

Logged.php:

<?php
//here must be totaly clear, nothing can't be here
session_start();

if(!isset($_SESSION['email']) && !isset($_SESSION['password'])){
   header("Location: Login.php?err=Please login to use members area");
}
else {
   echo "You are logged in as:". $_SESSION['email'];
}

答案 2 :(得分:0)

我解决了这个问题。当我在一个页面上时,我在www.domain.com/page1上,但当我在另一页上时,没有www - domain.com/page2。这意味着会话变量不会持久存在。对于狐狸来说,如果网址中没有www,我需要编辑htaccess文件以重定向到www。