首页 > 解决方案 > PHP SESSION 未定义变量

问题描述

在此处输入图片描述晚上好,我正在做一个小型的 uni 项目。我正在创建一个网站,人们可以使用 PHP 发布他们用过的物品以出售它们或与另一个对象交换它们(一种 ebay,但简单 100000 倍),这对我来说是新的。为简单起见,在填写连接表单 (connexion.php) 后,用户将被重定向到他自己的个人资料 (profil.php),其中出现了他的用户名和电子邮件(从数据库中获取它们之后)。如下所示:

//////////connexion.php : //////////

<?php
session_start(); 
try
{
    $bdd = new PDO('mysql:host=localhost;dbname=espace_membre;charset=utf8', 'root', '');
}
catch (Exception $e)
{
        die('Erreur : ' . $e->getMessage()); //message d'erreur au cas où la connexion échoue
}

if(isset($_POST['formconnect']))  //vérifie que le bouton pour se connecter est enclenché 
{
  $mailconnect = htmlspecialchars($_POST['mailconnect']); 
  $mdpconnect = sha1($_POST['mdpconnect']);
  if(!empty($mailconnect) AND !empty($mdpconnect))
  {
     $requser=$bdd->prepare("SELECT * FROM membres WHERE email = ? AND mdp= ?");  
     $requser->execute(array($mailconnect,$mdpconnect));
     $userexist=$requser->rowcount(); 
     if($userexist==1)
     {
          $userinfo=$requser->fetch();
          $_SESSION['id']=$userinfo['id'];
          $_SESSION['pseudo']=$userinfo['pseudo'];
          $_SESSION['email']=$userinfo['email'];
          header("Location: profil.php?id=".$_SESSION['id']);
     }
     else
     {
      $erreur="password or mail not valid" ; 
     }
  }
  else
  {
    $erreur =" please complete all inputs " ; 
  }
}
 ?>

连接后,用户被重定向到他的个人资料,名为profil.php,如下所示:

<?php
session_start();

 
//tentative de connexion à la base de donnée 
try
{
    $bdd = new PDO('mysql:host=localhost;dbname=espace_membre;charset=utf8', 'root', '');
}
catch (Exception $e)
{
        die('Erreur : ' . $e->getMessage()); //message d'erreur au cas où la connexion échoue
}


if(isset($_GET['id']) AND $_GET['id'] > 0)
{
  $getid=intval($_GET['id']);
  $requser= $bdd -> prepare('SELECT * FROM membres WHERE id= ?');
  $requser->execute(array($getid));
  $userinfo=$requser->fetch();


[the table where my users infos are stored. membres means members in french][1]

<html>

<head>
    <title>Profil de <?php echo $userinfo['pseudo']?></title>    
    <meta charset='utf-8'>
</head>

  <div align="center">
         <h3>profil TROKI</h3>
        <br/>
        
        
      <h3>les annonces de <?php echo $userinfo['pseudo']?> </h3>
          pseudo = <?php echo $userinfo['pseudo']?> <br/> //this one works
           mail = <?php echo $userinfo['email']?> <br/>  //this one works too

           <?php 
            if (isset($_SESSION['id']) AND $userinfo['id']==$_SESSION['id']) 
            {
             ?>
              //everything here is visible only when the user is logged in 
             <h>Bienvenue dans ton profil <?php echo $userinfo['pseudo']?> </h2> 
             <a href="editionprofil.php"> éditer mon profil</a> 
             <a href="modifiermdp.php">modifier mon mot de passe</a>
             <a href="deconnexion.php"> se déconnecter</a>
             <a href="formulaireajout.php"> ajouter une annonce</a>
            
             <?php 
            }
           ?>
    </div>

 <?php    
  }
   else
   ?>
</html>

每当我想打印类似的东西时

  <h2>welcome to your profile,<?php echo $userinfo['pseudo']?> </h2>

变量 $userinfo['pseudo'] 变成了我用户的昵称,这就是我想要的。

但是,由于我不知道,我无法让这些变量在任何其他页面上工作,并且我不断收到此错误:

** 注意:未定义变量:第 64 行 C:\wamp\www\projet2\formulaireajout.php 中的用户信息**

我为用户创建了另一个页面来填写表格以发布内容

 <?php
session_start();
try
{
    $bdd = new PDO('mysql:host=localhost;dbname=espace_membre;charset=utf8', 'root', '');
}
catch (Exception $e)
{
        die('Erreur : ' . $e->getMessage()); //message d'erreur au cas où la connexion échoue
}

// ////////////////////////////////////////////////////////////////////////////////////////////////
if(isset($_SESSION['id']))
{   echo "ok"; // I'm getting "ok" so this condition is verified
 }

else
{
  //echo "lol";
  header('location:connexion.php');
} 
if(isset($_GET['id']) AND $_GET['id'] > 0)
{
  $getid=intval($_GET['id']);
  $requser= $bdd -> prepare('SELECT * FROM membres WHERE id= ?');
  $requser->execute(array($getid));
  $userinfo=$requser->fetch();
}

<!DOCTYPE html>
<html>
<head>
    <title>Ajouter une annonce</title>
</head>
<body>
    <h3>You can post your things here,<?php echo $userinfo['pseudo']?></h3> // here, $userinfo generates an undefined variable error ! 
    <div align="center">
    'some extra code deleted'

</body>
</html>

好吧,我的问题是,如果我的 $userinfo 是在 profile.php 页面中定义的,为什么它会在我正在创建的所有其他页面中生成错误?我究竟做错了什么 ?(这个项目大约占我学期分数的 60%,所以我遇到了麻烦,我无法解决它)

感谢您的阅读,祝您有美好的一天!

标签: phpmysqlsessionphpmyadmin

解决方案


在连接页面上,您将 URL 中的 id 传递给配置文件页面,如下所示:header("Location: profil.php?id=".$_SESSION['id']);配置文件页面上正在查找要设置的 $_GET['id'] 的函数得到满足,因为在 URL 中设置了 id。

但是,如果我是用户并单击和这些链接:

  • 版本配置文件.php
  • 修饰符mdp.php
  • 断开连接.php
  • 公式reajout.php

id 没有在 URL 或页面请求中传递,但您的代码仍在寻找要在这些页面上设置的值,以及下面的代码片段:

if(isset($_GET['id']) AND $_GET['id'] > 0)
{
  $getid=intval($_GET['id']);
  $requser= $bdd -> prepare('SELECT * FROM membres WHERE id= ?');
  $requser->execute(array($getid));
  $userinfo=$requser->fetch();
}

因为 $_GET['id'] 没有设置,所以这个变量$userinfo没有被定义为以后在你的代码中使用。仅当 $_GET['id'] 已设置且大于 0 时才会设置。

My advice is, since you already set the user ID in the session, call the $_SESSION variables instead on other pages. So as long as you continue to start the session as you are now at the top of the file and you don't end or destroy the session, you should be able to access the values of the $_SESSION array on other pages:

      $_SESSION['id']=$userinfo['id'];
      $_SESSION['pseudo']=$userinfo['pseudo'];
      $_SESSION['email']=$userinfo['email'];

For the values you already set in the session, just echo out these values later in your code on other pages. So calling this should work on other pages:

<?php echo $_SESSION['pseudo']?></h3>

If course you want to destroy the session and/or unset the values when the user "logs out". Additionally since the values are in the session, you don't need to do a database lookup on every page for the same values unless they are going to change or you are looking for new data not already stored in the session.

Hope this helps.


推荐阅读