PHP Variable in session not getting updated instantly - php

In two different php file one sets variable in session and other reads from it. while updated the second file gets the old value immediately after.
I have two consecutive jQuery ajax call from my page.
Tokens that fetch access token from remote server and set it in $_SESSION[token]. If it already finds a valid token in session does nothing.
/makeReq which calls another api with the token from $_SESSION[token]
I check if a session gets expired considering it's grant time and expiry. When it's expired it fetch and sets the new token in $_SESSION[token] but in the second call when reading from $_Session[token] it gets the old value.
These are two separate jQuery ajax call from a single page.
Below is the code for my token endpoint.
$current_time = time();
$get_new_token = true;
$request_token = null;
if (isset($_SESSION['token'])) {
$request_token = $_SESSION['token'];
$last_token_expire_time = $request_token['grant_time'] + $request_token['expires_in'] -600;
$get_new_token = $last_token_expire_time < $current_time ? true : false;
}
if ($get_new_token) {
$request_token=get_token();
$request_token['grant_time'] = time();
$_SESSION['token'] = $request_token;
}
Below is the code for my makeReq endpoint
$header=array(
'Content-Type:application/json',
'authorization:'.$_SESSION["token"],
'x-app-key:'.APP_KEY
);
Below is the code from where I am making the request
jQuery.ajax({
url: "'.plugin_dir_url( __FILE__ ) . "token.php".'",
type: "POST",
contentType: "application/json",
success: function (data) {
}
});
jQuery.ajax({
url: "'.plugin_dir_url( __FILE__ ) . "makeReq.php".'",
type:"POST",
data: {formData: postData},
success: function(data) {
}
});

Sounds like a cache issue.
Try to eliminate anything that may interfere with cache. If you are on a wp dedicated hosting, such as WpEngine, please note that they encourage not to use sessions at all.
Also, make you code with only the essential parts, just to see if you lose the session.

Related

Display notification only once - PHP - Codeigniter - JS

There is an ajax function, which displays a notification on the home page, however, every time I enter thehome page, or refresh the F5 page, the notification is displayed again.
How to fix this?
Is there any way to do this, using js jquery or PHP?
Below the code I have:
Controller
public function get_message()
{
$notification= array();
$notification['message'] = 'message test';
$notification['type'] = 1;
echo json_encode($notification);
}
Javascript
/*** variable ***/
var enum_toastr_type = {
success: 1,
info: 2,
warning: 3,
error: 4
}
/*** PageLoad start ***/
$(document).ready(function() {
toastr.options = {
closeButton: true,
positionClass: 'toast-bottom-right',
timeOut: '20000'
}
get_message_ajax();
});
/*** PageLoad end ***/
function show_message_toastr(mensagens) {
$(mensagens).each(function() {
switch (this.tipo) {
case enum_toastr_type.info:
toastr.info(this.message);
break;
case enum_toastr_type.success:
toastr.success(this.message);
break;
case enum_toastr_type.warning:
toastr.warning(this.message);
break;
case enum_toastr_type.error:
toastr.error(this.message);
break;
}
});
}
/*** Ajax start ***/
function get_message_ajax() {
$.ajax({
type: 'GET',
async: false,
contentType: 'application/json; charset=utf-8',
url: "helper/get_message",
success: (function(data) {
//console.log(data);
_obj = JSON.parse(data);
show_message_toastr(_obj);
}),
error: (function(erro) {
handle_ajax_error(erro);
})
});
}
/*** Ajax end ***/
For doing this you will need to set cookies in the browser to track if user has visited this page already. This would also prevent this on page reloads. You can use local storage to store any data in the browser.
// on page load check if user has not already visited this page
var visited = localStorage.getItem('visited');
if(!visited) {
// call your ajax function which displays message
get_message_ajax();
// lets set visited to true so when user loads page next time then get_message_ajax() does not gets called
localStorage.setItem('visited', true);
}
If you need something like; what if user logs out of the system, then you can clear the local storage on logout. Maybe you can add click listner on logout button and can clear local storage.
localStorage.clear(); // this will clear all website data in localStorage
// or you can update visited key;
localStorage.setItem('visited', false);
Or if you want something more advance like even user does not logs out and still you want to show message lets say if user visits after 1 day. Then you can store timestamp with key and parse it back when checking if user visited.
var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));
When accessing the key you can do something like this;
var object = JSON.parse(localStorage.getItem("key")),
dateString = object.timestamp,
now = new Date().getTime().toString();
// here you can compare two time strings and decide to show message.
For different implementation and ideas on how to manipulate time here is some help;
https://developer.mozilla.org/en-US/docs/Web/API/Storage
When do items in HTML5 local storage expire?

php click out logged user with ajax

good afternoon from gmt+8 timezone.
I had built a login/system , now I want to implement a function that will click out users , so i make a status column in the db ,
2 types of values , lock => lock , active => not lock.
I can use crud method to update the status and output in a table. surely i cam lock the user , and status change to lock, that is working fine, but the problem is the locked user still has access the to system , since the session still valid , she/he has to close the browser or their session is terminated.
on the login page I check if user is lock then can login.
since the user still has access when the session still valid , I want to input ajax call the server to check the status on setInterval.
on backend php: check if user is lock , terminate the session , give alerts box and redirect.
but the issue now is my code is not working, here are my ajax call , if I un-comment //console.log('success');, success will be kept in console.log , meaning the call is success.
<script>
function getUserStatus(){
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
});
}
setInterval(function(){
getUserStatus();
},3000);
</script>
on my ajax.php page , I make sure connection to db is working,
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$admin_username = check_input($_POST['username']);
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clicked out');window.location.href='../index.php';</script>";
}
}
function to check user is lock
function isLocked($username){
global $connection ;
$query = "SELECT status FROM table where name = '$username' ";
$result = mysqli_query($connection,$query);
confirm($result);
while( $row = fetch_array($result)){
if($row['status'] == 'locked' ){
return true;
}else{
return false;
}
}
}
if i directly access ajax.php with the log user , below action is working .
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clickedout');window.location.href='../index.php';</script>"; }
not sure what is wrong with my codes and how to fix it ?
any assistance/suggestion would be highly appreciated .
your ajax.php echos something, that may be data, a json or in your case a js script.
The ajax calls ajax/ajax.php, if the http request succeeds it enters
success:
function(response){
//console.log('success');
}
so the variable response holds the output of that call to ajax/ajax.php. if you use
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
dataType: "script",
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
the value of "response" will be executed if it is a working script.(without tags)
further information you can find here:
http://api.jquery.com/jQuery.ajax/
without dataType: "script",in the call you could do something like that:
function(response){
//console.log('success');
$('#somediv').html(response);
}
that will insert the result in a div, if it is a well formated js script, it will be executed.

Ajax reset session php

I use my own Framework, in localhost all works perfectly fine but not on the server.
I'm logged, so I've a session id.
On a ajax request, the php script doesn't keep my session, if I return the session, the session are empty but me in my side, I keep the session.
It's like if the server thinks the ajax request is a new user.
I don't know where to look and I can't post all the framework code here...
Yesterday I already have this issue (at work) then at home, I retested and all worked great...
I don't get it...
$(document).on('click', '.edit', function(){
$.ajax({
type: "POST",
url: ROOT+"list",
data: {id:id},
headers: {
Accept : "application/json; charset=utf-8"
},
cache: false,
success: function(data){
console.log(data.sess.ROLE);
if(data.status == "error"){
//error
}else{
//ok
}
}
});
});
Controller:
public function editAction(){
//if(!$this->ROLE('tokayn')){ $this->redirectUrl('thread_index'); }
if(Request::POST()){
if(is_int($_POST['id'])){
$user = $this->batiments->findById($_POST['id']);
if($user->id_proprio == $_SESSION['id']){
$data = array('status'=>'ok', 'message'=>$user);
Request::renderJson($data);
}else{
Request::renderJson(array('sess'=>$_SESSION));
//$data = array('status'=>'error', 'message'=>'error');
//Request::renderJson($data);
}
}else{
$data = array('status'=>'error', 'message'=>'error');
Request::renderJson($data);
}
}else{
//$this->redirectUrl('thread_index');
}
}
If a user is not logged, the session role is 'visitor' but if he's logged, the session role is 'connected'.
I've a echo before the ajax form and it's 'connected'.
Then, on submit the ajax form, the ajax request return 'visitor' but if I refresh, I keep the 'connected' echo...
I've faced this issue for me the problem was I was using
https://server:1234/somecontroller
while i was requesting from ajax as
http://server:3344/somecontroller
and session was not shared between https and http so double check if this apply for you.

How to send data between ajax and php in secure way?

I have index.php, ajax.js and process.php (where I get my AJAX data).
I am using AJAX this way:
var = $('user_id').val();
$.ajax({
url : "somefile.php",
method : "GET",
data : {'user_id' : user_id},
cache : false,
success : function(data) {
// do something with "data"
}
);
User_id I receive from PHP file:
<input value="<?php echo $user_id; ?>" id="user_id" />
What do I need to do for increasing security?
Following can be added, just for increasing security measures,
In PHP code
<input value="<?php echo base64_encode($user_id); ?>" id="user_id" />
In JS Code:
var = $('user_id').val();
$.ajax({
url : "somefile.php",
method : "POST",
data : {'user_id' : user_id},
cache : false,
success : function(data) {
// do something with "data"
}
);
In "somefile.php"
for getting the file use the $_POST method, if will only accept the variable posted by using POST method. This can be used:
if(isset($_POST['user_id']))
{
$user_id=$_POST['user_id']
$user_id=base64_decode($user_id);
//all functionality here
}
else
{
//shoot error message
}
I'd recommend you don't provide the userid to the client. Can you store it in a session variable instead?
If this user_id is being used to retrieve some confidential information related to the logged in user then that sounds like a security flaw.
You should be getting the user_id from a session variable
I think is not an good idea to put 'user_id' in client HTML and send back to server. You need to do more validation with data that sent from client (do some checking and filtering).
I recommend to use session instead of sending it to client, But you will have problem if editing two or more data at same time (multi tab), So you need to use session and some trick.
With this example your real user_id will never sent to the client.
index.php:
session_start();
$edit_session_id = md5(uniqid() . microtime(true));
$_SESSION['edit_' . $edit_session_id] = $user_id;
ajax.js:
var edit_session_id = $('#edit_session_id').val();
$.ajax({
url : "process.php",
method : "POST",
data : {'edit_session_id' : edit_session_id},
cache : false,
success : function(data) {
// do code
}
);
process.php:
session_start();
$edit_session_id = $_POST['edit_session_id'];
if(!isset($_SESSION['edit_' . $edit_session_id]))
{
die('Invalid edit session, please go back & refresh');
}
$user_id = $_SESSION['edit_' . $edit_session_id];
// Do something with user_id
//Clear the editing session
unset($_SESSION['edit_' . $edit_session_id]);
You should use POST instead of GET and you should also use ssl so that yuor urls sart with https instead of http.Now you are secured enough but you can increase security by adding extra encryption layer.

Posting data with curl - actually refreshing to the next page

I'm trying to send post data between pages with Post. Not a form - like I may be passing validation error between pages or something (using it in several places).
The cURL is executing fine, but it's just tacking on the new page at the bottom. How can I execute a cURL Post and load the following page?
So my goal is to send data between pages. I do not want to use GET or cookies as I do not want to rely on the user, and I'd prefer not to use $_SESSION as it is not so much directly about a session as sending private data between pages.
Thanks
$ch = curl_init($some_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'myvar=something');
curl_exec($ch);
curl_close($ch);
I doubt the code has any relevance, as it's about performing a task not code syntax (there may be one in this example but you'll have to trust me it's not the code that's buggy as it's retrieving fine).
You could separate your $_SESSION superglobal into arrays describing both the current user/session and any errors that your form has created. For instance,
$_SESSION = array(
'user' => array(), // user data goes here
'errors' => array() // validation data goes here
);
if (!$_POST['myvar'] == 'something') {
$_SESSION['errors']['myvar'] = 'You must specify a value for <code>myvar</code>';
}
You would then be able to output errors on subsequent pages using a call something like this:
if (isset($_SESSION['errors'])) {
foreach($_SESSION['errors'] as $error) {
echo '<li>' . $error . '</li>';
}
}
Why are you using cURL? Why not just use AJAX:
$(function() {
// Send data asynchronously
$.ajax({
url: '/path/to/your/script.php',
type: 'POST',
data: 'var1=value1&var2'=$('input.some_class').val(),
success: function(data) {
// Send the user to another page
window.location.href = '/to/infinity/and/beyond';
}
});
});
Using ajax for exec
$(function() {
/
data: 'var1=value1&/ Send data asynchronously
$.ajax({
url: '/path/to/your/script.php',
type: 'POST',var2'=$('input.some_class').val(),
success: function(data) {
// Send the user to another page
window.location.href = '/to/infinity/and/beyond';
}
});
});

Categories