我已经记录了mu用户(在login.php中)并开始会话,然后重定向到另一个页面(accueil.php)/
在login.php中:我的会话存在,我的cookie存在。 在accueil.php中:我的会话存在,我的cookie不存在。
==>我在第二页的顶部开始了我的会话./
==>我试着用不同的方式徒劳地使用位置:
标题('位置:http://localhost/monsite/accueil.php'); /
OR
标题('位置:accueil.php');
==>无论如何:它返回"未定义的索引用户名"。
我不明白。请问有什么想法吗?!
这是我的代码:
Login.php:
$username = $_GET['username'];
$password = $_GET['password'];
$sql = $connection->query("SELECT username, password FROM login WHERE username = '$username' && `password`= '$password';");
while ($result = $sql->fetch()){
$data = array('username' => $result['username'],
'password' => $result['password']);
}
try{
if($data['username'] !== $username && $data['password'] !== $password ) {
throw new Exception('Login incorrect', 500);
}
else{
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
setcookie('maSession', $_SESSION['username'], time()+3600 , '/');
header('Location: http://localhost/monsite/accueil.php');
}
}
catch(Exception $e){
header("HTTP/1.1 500 Internal Server Error");
echo 'error: '.$e->getMessage();
}
Accueil.php: ``
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include_once('accueil.php');
require_once('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);
if(isset($_SESSION)) {
$username = $_SESSION['username'];
echo $username;
}
else{
echo 'no session';
}
}
- > var_dump($ _ SESSION):返回空数组。
- > $ _ SESSION ['用户名']:返回未定义的索引undername。
谢谢!
答案 0 :(得分:0)
<?php
//Check session if not already started, then start it.
if(session_id() == '')
{
session_start();
}
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include_once('accueil.php');
require_once('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);
// Check session 'username' it was not empty
if(!empty($_SESSION['username'])) {
$username = $_SESSION['username'];
echo $username;
}
else{
echo 'no session';
}
}
?>