Reputation: 67
I have logged mu user (in login.php) and start session, before redirect to another page (accueil.php)/
In login.php : My Session exists, my cookies exists. In accueil.php : My Session exists, my cookies doesn't exists.
==> I started my Session at the top of my second page./
==> I tried different way to use Location in vain :
header('Location: http://localhost/monsite/accueil.php');/
OR
header('Location: accueil.php');
==>Anyway : it returns "undefined index username".
I don't understand. Have you any ideas please?!
Here is my code :
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) : returns empty array.
->$_SESSION['username'] : returns undefined index undername.
Thank you !
Upvotes: 1
Views: 3284
Reputation: 734
<?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';
}
}
?>
Upvotes: 0