I have a loginscript that starts a session containing either admin or any possible other user.
Everything in my script is returned as JSON (messages and what user logged in). But in that same script I also start a session according to what user logged in.
After I get a result I go to a page depending what user logged in, but the session can't be found there. I try to echo its contents but it shows nothing.
What am I doing wrong?
My php script:
session_start();
$conn = new Connection;
$username = $_POST['username'];
$userpassword = $_POST['userpassword'];
if(empty($username) && empty($userpassword)){
$logindata = array(
'userdata' => '',
'message' => 'Vul een gebruikersnaam en wachtwoord in',
);
echo json_encode($logindata);
}else if(empty($username)){
$logindata = array(
'userdata' => '',
'message' => 'Vul een gebruikersnaam in',
);
echo json_encode($logindata);
}else if(empty($userpassword)){
$logindata = array(
'userdata' => '',
'message' => 'Vul een wachtwoord in',
);
}else{
//Both filled in, begin logincode:
$getuser = "SELECT * FROM users WHERE username = '".$conn->real_escape_string($username)."'";
$getusercon = $conn->query($getuser);
$getuser = $getusercon->fetch_assoc();
if($userpassword == $getuser['password']){
if($getuser['rights'] == '1'){
$_SESSION['user'] = 'admin';
$loginresult = array(
'login_result' => 'success',
);
$logindata = array(
'userdata' => $_SESSION['user'],
);
echo json_encode($logindata);
}else{
$_SESSION['user'] = $getuser['username'];
$loginresult = array(
'login_result' => 'success',
);
$logindata = array(
'userdata' => $_SESSION['user'],
);
echo json_encode($logindata);
}
}else{
$logindata = array(
'userdata' => '',
'message' => 'Wachtwoord en gebruikersnaam komen niet overeen',
);
echo json_encode($logindata);
}
}
My AJAX code:
// Login Ajax Code
$( "#content" ).on("submit", "#loginform", function( event ) {
// Stop normal form behaviour
event.preventDefault();
// Retrieve input fields and their values
var $form = $( this ),
$username = $form.find( "input[name='username']" ).val(),
$userpassword = $form.find( "input[name='userpassword']" ).val(),
url = $form.attr( "action" );
// Post above values to the action of the form
var posting = $.post( url, { username: $username, userpassword: $userpassword} );
// Show result in a div
posting.done(function( data ) {
obj = JSON.parse(data);
if(obj.userdata == ''){
$( "#loginresult" ).empty().slideDown('fast').append( obj.message );
}else if(obj.userdata == 'admin'){
window.location.href = "http://www.website.nl/addcompany.php";
console.log('dit is een admin');
}else if(obj.userdata == 'user'){
window.location.href = "http://www.website.nl/index2.php";
console.log('dit is een user');
}
}, "json");
});
In the header that is both on addcompany.php
and index2.php
I try this:
<?PHP echo $_SESSION['user']; ?>test
It shows test but not the session contents.