db table not getting updated when forcing logout using ajax - javascript

As stated in the title, db table trace_users is not getting updated when no activity happens for 30 mins but its get updated when its 6 mins.
The following code (both JS and PHP) is inside the same php file mno.php.
I am storing the last activity of user through this line let lastActivity = <?php echo time(); ?> ; present in the script below.
<?php
session_start();
if (isset($_GET['action']) && $_GET['action'] == "logout")
{
session_destroy(); // destroy session data in storage
!isset($_SESSION['admin']);
$open = "false";
$write = "0";
$stmt = $connect->prepare("UPDATE trace_users SET open=?, write=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : '';
$stmt->bind_param('sss', $open, $write, $usname);
$stmt->execute();
}
?>
<script>
jQuery(document).ready(function($) {
let lastActivity = <?php echo time(); ?> ; // storing last activity of user
let now = <?php echo time(); ?> ;
let logoutAfter = 360;
let timer = setInterval(function() {
now++;
let delta = now - lastActivity;
console.log(delta);
if (delta > logoutAfter) {
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/abc/mno.php",
type: 'GET',
data: {
action: 'logout'
}, // Line A
success: function(data) {
console.log(data); // Line B
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
}, 1000);
});
</script>
Problem Statement:
I am wondering what changes I should make in the code above so that when no activity happens for 30 mins (1800 seconds) then the db table should also get updated.
Case1 (Not Working) : 1800 seconds (page logs out, db doesn't update)
Case2 (Working) : 360 seconds (page logs out, db gets updated)
The values inside session.gc_maxlifetime are 1440(Local Value) 1440(Master Value)
This is what I have tried/debugged:
On the network tab, I am getting Request Method GET when session timeout is set 6 mins and 60 mins.

You need to pass to the javascript some sort of permanent UID that identifies the user even after the session expires.
For the sake of simplification, I'm using user_name that already exists in your code. But you can also assign an UUID for each user, so that one can't guess another user's name and can't modify their stats.
First, you'll pass the $_SESSION['user_name'] from PHP to the JS closure.
let userName = "<?php echo $_SESSION['user_name']; ?>"; // don't forget to wrap the JS string value in quotes or apostrophes
Then, you'll pass it in the AJAX request payload.
data: {
action: 'logout',
user_name: userName // added param
},
Finally, you'll overwrite the value that is sent to DB (if it's sent with the payload)
$usname = !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : ''; // original line
if (isset($_GET['user_name']) && !empty($_GET['user_name'])) {
$usname = $_GET['user_name'];
}
$stmt->bind_param('sss', $open, $write, $usname); // original line
Complete updated code:
<?php
if (isset($_GET['action']) && $_GET['action'] == "logout")
{
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
$open = "false";
$write = "0";
$stmt = $connect->prepare("UPDATE trace_users SET open=?, write=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : '';
if (isset($_GET['user_name']) && !empty($_GET['user_name'])) {
$usname = $_GET['user_name'];
}
$stmt->bind_param('sss', $open, $write, $usname);
$stmt->execute();
}
?>
<script>
jQuery(document).ready(function($) {
let lastActivity = <?php echo time(); ?> ; // storing last activity of user
let now = <?php echo time(); ?> ;
let logoutAfter = 10;
let userName = "<?php echo $_SESSION['user_name']; ?>";
let timer = setInterval(function() {
now++;
let delta = now - lastActivity;
console.log(delta);
if (delta > logoutAfter) {
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/abc/mno.php",
type: 'GET',
data: {
action: 'logout',
user_name: userName
}, // Line A
success: function(data) {
console.log(data); // Line B
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
}, 1000);
});
</script>
Few notes at the end:
It's bad practice to combine PHP, HTML and JS altogether in one file.
There are some parts of your code that are not easily reproducible and I had to guess from the context (e.g. i guessed that the session is already set, jQuery is used but there's no <script src="...jquery.js">, there's a DB query but no separate SQL import to try it quickly). Please read and apply the knowledge from How to create a Minimal, Reproducible Example in your next question, so that more people are able or willing to help you with it.

The problem is that you are not changing anything that will prevent the session from expiring after N seconds, you are just coding your script in a way that it will destroy the session after this time. The session gc (garbage colector) executes periodically and deletes old sessions and when that happens, $_SESSION['LAST_ACTIVITY'] will be deleted as well.
You must either try to prevent the gc from deleting sessions or change the logic in your application.

PHP process does not sit indefinitely and does not have program structure as a loop ala Node.js server, which won’t allow you to react to session expiry since it’s not a process that invalidates it, but rather a simple timestamp associated with session that is checked every time you attempt to work with it.
The solution I offer is a simple script that is ran every N minutes to perform a comparison of last user activity timestamp (which, I assume is updated on the request for that user) against expiry period (in you case it is 30 minutes). You can also set session expiry to 30 minutes, though strictly it’s not necessary. If the time difference will exceed 30 minutes, you update the timestamp for the user in your table, and invalidate their session if necessary. The script can be ran through cron or its alternatives and go through all users you require to perform a check.
Do not forget to handle the case when user is logged out on the server but client does not know about it and may continue sending logout requests - raising alert box is rather unclear (it is better to return HTTP Unauthorized code and handle it differently - redirecting to login screen, for example)

There are two things you need to fix.
1). Set the ajax request to be async:false.
$.ajax({
url: "/abc/mno.php",
type: 'GET',
async: false, // <---- ADDED ASYNC FALSE
data: {
action: 'logout'
}, // Line A
success: function(data) {
console.log(data); // Line B
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
2). Destroy the session after performing the SQL Query.
<?php
session_start();
if (isset($_GET['action']) && $_GET['action'] == "logout")
{
!isset($_SESSION['pageadmin']);
$open = "false";
$write = "0";
$stmt = $connect->prepare("UPDATE trace_users SET open=?, write=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : '';
$stmt->bind_param('sss', $open, $write, $usname);
$stmt->execute();
session_destroy(); // destroy session data in storage <---- DESTORY AT THE END
}
?>

Related

Ask db information every tot seconds

I'm trying to refresh data on my web page according to the data stored in the database, so every 2 seconds I call with an ajax request a php file. The called php script is this:
session_start();
.....Connection to the db.......
$prova = pg_query($connect, "SELECT * FROM maxdistance");
$prova2 = "";
while ($row = pg_fetch_row($prova)) {
$prova2 = $prova2.$row[0].$row[1].$row[2];
}
$_SESSION['prova'] = $prova2;
And this is the code in javascript:
var intervalId = window.setInterval(function(){
newPositions();
}, 2000);
function newPositions(){
$(document).ready(function(){
$.ajax({
type: "POST",
url: "realTimePosition.php",
success: function(msg){
provaaa = <?php echo ($_SESSION[prova]); ?>;
}
})
});
The problem is that, when I refresh the page the code run and in the variable provaaa is stored the value 20 (the actual value in the db) but if I modify the value in the db, the value of the variable is the same, why is this happening?
you cant mix JS and PHP like this
problem part
provaaa = <?php echo ($_SESSION[prova]); ?>;
solution
your PHP script have to send back REPLY with "echo"
echo json_encode([ 'data' => $prova2]);
then y have to catch server response inside your "success" callback dunction where param is RESPONSE from server so
success: function(res){
provaaa = JSON.parse(res).data;
}

update database table on session timeout in php

I have a php code as shown below in which session timeout happen after 60 mins when there is no activity. The following code is inside the file /mno.php. My login and logout code is also in the same file /mno.php.
/mno.php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
header('location: /mmo.php');
exit();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
The table trace_users in the code keeps the track of all logged in users. In that table, there are two columns user_name and open. The value is set to true/false when any user log in/log out.
I have included sql query in which I am trying to update a table when there is no activity but unfortunately the column value is not getting set to false for that particular user when no activity happens for 60 mins.
This is what I have tried:
After doing some research, I think I have to run a timer (js/ajax). In the javascript shown below I have calculated the difference between the Last Activity and the Current time.
If its more than 60 mins, then it will update a db table. This is what I have tried but I believe more need to be done in order to update a table in db.
<script>
let x = setInterval(function() {
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>
let now = <?php echo time() ?>;
let difference = now - lastActivity;
if (difference > 3600) {
clearInterval(x);
}
}, 1000
);
</script>
Problem Statement:
I am wondering what changes I should make in the js (or php) code above so that when there is no activity for 60 mins, it should update the column open to false (in the table trace_users) for that particular user.
Edit 1:
My login code and session history code is in the same file /mno.php. I have placed everything in the same file /mno.php.
I think Vineys and jo0gbe4bstjbs answer is wrong because of when user close browser until 5 seconds, it can't update table after 60 mins and session too. Session deletes just after time in where set in php.ini configuration file.
And Do you mind requesting every 5 seconds is it good way to solve this? It is worst for performance.
If you want solve this problem with professionalism, you should add "last_request" column and delete "open" column from the table and after every request you should update last_requests value to current unix timestamp. And where getting users you should write:
$time = time() - 3600;
"SELECT * FROM `users` WHERE last_request > $time" //active users
"SELECT * FROM `users` WHERE last_request <= $time" //inactive users
And instead of ajax request every 5 seconds you should write setTimeout with 3600 second delay time which run window.location.href= '/mmo.php'; code.
Its way good if you want best performance and exactly result with 60 minute logout
I suppose you realize that this code
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
//...
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
runs on every request and only when a request arrives
Imagine I visit your website and then go out shopping keeping the browser open. What do you think will happen?
NOTHING - because there will be no new request sent to you (assuming you haven't implemented any periodic ajax polling / Websocket mechanism)
So the server won't bother about me until I come back from shopping and refresh the page, only then would the server realize "Hmmm..This guy's LAST_ACTIVITY is older than an hour let me update my trace_users table and set open as false for him"
Coming to your proposed solution, it looks good and avoids the complications of websockets/periodic ajax requests
Just need some minor corrections, follow here for a basic demo
<script>
var lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
var now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server
// but later on it will be incremented by javascript to act as counter
var logoutAfter = 5; //I set 5 sec for demo purposes
var timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
}
}, 1000);
</script>
Here the lastActivity will hold the timestamp when the page was sent by server to browser it will be never changed by scripts on the browser,
now is your counter that you will use to track how much time passed since page was loaded on the browser, you'll increment it every second and check if a given amount of time has been crossed
If true do a ajax request (or simply redirect to logout.php) where you would destroy session and update the trace_users table to mark the user as closed
UPDATE
So ajax will be like
$.ajax({
url: "/close.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
window.location.href= '/mmo.php';
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
and
close.php
<?php
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
// I'm not sure whether the below if condition check is required here or not
// because we have already checked (whether to timeout or not ) in our javascript
// and we call close.php only when it's affirmative
// I encourage you to test and find out :)
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Page.php
<!-- CODE TO INCLUDE IN HEADER.PHP -->
<?php
session_start();
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
<!-- CLOSE -->
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
</body>
<script>
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
let now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server+
// but later on it will be incremented by javascript to act as counter
let logoutAfter = 5; //I set 5 secs for demo purposes
let timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/mmo.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("I am inside error");
alert(textStatus);
}
});
}
}, 1000); //<-- you can increse it( till <= logoutAfter ) for better performance as suggested by #"Space Coding"
</script>
</html>
mmo.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name'])?$_SESSION['user_name']:'';
$stmt->bind_param('ss', $open, $usname );
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
This is a simple time validation for web page:
$modified_on = isset($SERVER['HTTP_IF_MODIFIED_SINCE']) ? $SERVER['HTTP_IF_MODIFIED_SINCE'] : null;
$current_time = time();
if (!is_null($modified_on) && ($current_time - strtotime($modified_on)) > 3600) {
session_destroy();
...
}
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $current_time).' GMT');
...

Why successful ping $link returns nothing on query (ajax)

I'm trying to implement a "like" button with ajax so I don't have to reload the page to update the database, but no query done through ajax works.
I have it stripped down to just checking if the user already liked this project or not and I still don't manage to make it work.
I have validated:
-The $link is good (through mysqli_ping())
-The query itself is good (through phpMyAdmin)
-The ajax seems good too (replacing echo $val to echo 1 or echo memberId alert the good value).
code.js:
$("#likebtn").click(function(){
//check if already liked
$.ajax({
type:"POST",
url:"extra/projectpagefunctions.php",
data: {func: 'existsLinkProject', Table: 'projectLikes'},
success : function(result){
alert(result);
},
error : function(error){
console.log(error);
}
});
});
projectpagefunctions.php:
<?php
session_start();
$TestLink = mysqli_connect('localhost', '*******', '******', '******');
function existsLinkProject($Table){
$query = "SELECT * FROM `".$Table."` WHERE `memberId` = ".$_SESSION["account"]["memberId"]." AND `idProject` = ".$_SESSION["project"]["idProject"];
$result = mysqli_query($TestLink, $query);
$val=0;
if(mysqli_num_rows($result)>0){
$val=1;
}
echo $val;
}
if(isset($_POST["func"]) && mysqli_ping($TestLink)){
if($_POST["func"] == "existsLinkProject"){
existsLinkProject($_POST["Table"]);
}
}
else{
echo "error";
}
?>
I would expect the function to return 1 if already liked, and 0 if not.
But I only get 0 no matter what is in the database.
(on loading of the page I check it and set the color of the button accordingly and this already works)

Get and set session using PHP and angular.js

I need one help session store using PHP and Angular.js . i have one login app.When user will logged in successfully the session will store and when user will redirect to next page the session data will be fetched.I am explaining my code below.
login.php:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user_name=$request->user_name;
$user_pass=$request->user_pass;
$connect = mysql_connect("localhost", "root", "*****");
mysql_select_db('go_fasto', $connect);
$selquery = "SELECT * FROM db_Admin_Master WHERE user_name='".$user_name."' and password='".$user_pass."'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0){
$result=mysql_fetch_array($selres);
$_SESSION["user_name"]=
$_SESSION["user_type"]=
$_SESSION["email_id"]=
$result['msg'] = 'Login successfull...';
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg'] = 'You entered wrong username/password';
}
echo json_encode($result);
?>
In this page i need to set up the session data(i.e-user_name,email_id,user_type).The user will redirect to the next page after successful login and the controller file of that redirected page is given below.
dashboardController.js:
var dashboard=angular.module('Channabasavashwara');
dashboard.controller('dashboardController',function($scope,$http){
$http({
method: 'GET',
url: 'php/Login/session.php',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
})
In this page the user will get the respective session data inside success function and if session data is not present some message will return to error call back function.Please help me.
I think you need to create one separate function for that.
For example
$selquery = "SELECT * FROM db_Admin_Master WHERE user_name='".$user_name."'
and password='".$user_pass."'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0){
$result=mysql_fetch_array($selres);
getSession($result);
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg'] = 'You entered wrong username/password';
}
/*May be in separate function file.*/
function getSession($result){
if (! isset ( $_SESSION )) {
session_start ();
}
if( isset($result['user_id'])){ //or Whatever
// Declare your session and return variable
}
}
And call getSesson() function wherever you need to check session.

Ajax getting a value from php?

I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}

Categories

Resources