Session value changes on ajax page when using a random value - php

I am trying to prevent users from accessing my POST/AJAX files directly. I have decided to create a random token I call it "nonce_key". This key is created using a SESSION and then I pass it via POST. If the SESSION key is the same as the POST then I allow access. The problem is that sometimes it does not work.
Here is my workflow:
I have a single select on my index.php that when the user changes its value it calls "change_status.php" via ajax.
For some reason the SESSION key set on index.php is not the same value as the SESSION key on change_status.php.
I have the following code in my functions.php file
function nonce_key()
{
return hash('crc32b', time());
}
Then in my index I have
session_start();
require_once 'functions.php';
$_SESSION['nonce_key'] = nonce_key();
echo '
<script type="text/javascript">
$"#change_status").bind("change",function() {
var form_data = {
nonce: "'.$_SESSION['nonce_key'].'",
id: $("#id").val(),
};
$.ajax({
type: "POST",
url: "change_status.php",
data: form_data,
success: function(result) {
$("#message").slideDown("slow").html(result);
}
});
});
</script>'
;
Finally in my change_status.php file I have
session_start();
require_once 'functions.php';
if(isset($_SESSION['nonce_key']) && isset($_POST['nonce']))
{
if($_SESSION['nonce_key'] == $_POST['nonce'])
{
change_app_status($_POST['id']);
} else echo 'Nonce Invalid';
} else echo 'Not Allowed';

check that $_POST has the hash. And you have no need in require_once 'functions.php'; in change_status.php. And you can make one if less by using ===

Related

$_SESSION Variable not available after setting

Click on a button executes this Ajax request
$.ajax({
type: "GET",
url: "json-responses.php?fct=validationCode&userMail=" + userMail,
success: sendValidationCode()
});
if successfull the sendValidationCode() function is invoked which executes another Ajax request
function sendValidationCode()
{
$.ajax({
type: "GET",
url: "json-responses.php?fct=sendValidationCode&userMail=" + userMail,
success: function()
{
location.replace("reset-forgotten-pw?user=" + userMail);
}
});
}
Here is the code from the json-responses.php file :
if ($_GET['fct'] == 'validationCode')
{
$_SESSION['v_Code'] = random_str(6, '0123456789');
$result = createValidationCode($connectionObject, $_GET['userMail'], do_crypt($_SESSION['v_Code']));
echo $result;
}
if ($_GET['fct'] == 'sendValidationCode')
{
$volTo = $_GET['userMail'];
$volAckString = $image . "<h1>Password assistance</h1><p>To verify your identity, please use the following code:</p>".$_SESSION['v_Code'].;
unset($_SESSION['v_Code']);
}
I was assuming that as the 'validationCode' part is called before the $_SESSION['V_Code'] variable would be set and available when the second file invokes 'sendValidationCode' file. However the mail the user receives does not contain any validation code. Now if I restart the process (means the session remains open during the 'validationCode' part I get a new $_SESSION variable and in the 'sendValidationCode' part the "old" $_SESSION['v_Code'] is sent to the user. (Besides the unset.... does not have any effect.)

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.

Check db and then redirect using Ajax

So it's my first time handling or rather using ajax and it still rattles my mind. I made this ajax function so when everytime I push a button it checks the value of something on db and if it's true then it should redirect. It works fine or rather redirect when I refresh the webpage but that isn't what I was expecting, I was expecting that if the value on the db being checked is "EQUAL TO" or True then it should redirect without me having to refresh the page just so it can do it's stuff. Hoping for some insights, thanks!
My home.php has this:
<script src="js/ajax.js"></script>
My Ajax JS:
$.ajax
({
url: "testjax.php",
type: "post",
data: $('#Button').serialize(),
dataType:'json',
success: function (data)
{
if (data.status=='SUCCESS')
{
window.location="/anotherdirectory/";
}
else
{}
},
error: function (e) {
console.log('error:'+e);
}
});
Testjax PHP
<?php
session_start();
require_once('path/sql.php');
require_once('path/who.php');
$userID = Who::LoggedUserID(); //Found in who.php
$userData = Who::GetUserData($userID);
$userPoints = $userData['points'];
if ($userPoints==0.00)
{
$tent='SUCCESS';
}
else
{
$tent='ERROR';
}
$ary=array("status"=>$tent);
echo json_encode($ary);
?>

jQuery AJAX - Set PHP Session variable

I am looking to store a variable across an entire session so that when a user closes a promotional bar it stays closed and doesn't pop back up every time they navigate to a new page.
On page load I have the following:
$.ajax
({
url: 'promo.php',
type: 'post',
data : formData,
success: function(result)
{
alert(result);
}
});
The formData isn't too important right now as it isn't used.*
promo.php:
<?php
if (isset($_SESSION['promoBar'])) {
echo $_SESSION['promoBar'];
}
else {
$_SESSION['promoBar'] = "closed";
echo "does not exist";
}
?>
The idea is that on page load it will check if the $_SESSION['promoBar'] variable exists, and if it does, return it's value. Otherwise set a value.
Currently the alert always displays does not exist. I was expecting it to display does not exist the first time and then closed each time I navigate to a new page.
What have I done wrong?
Try this...
Use "session_start" before check
session_start();
if (isset($_SESSION['promoBar'])) {
echo $_SESSION['promoBar'];
}
else {
$_SESSION['promoBar'] = "closed";
echo "does not exist";
}
?>

update .text() using ajax auto refresh

When I set the session in a file called signin.php:
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'array.php',
type: 'post',
data: {'user': $user}
});
";
In another file (index.php), I want to get:
<?php
session_start();
echo "log in as <span id=\"user\"></span><br/>";
$user = $_POST['user']
echo "
<script>
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
</script>
";
?>
I know I completely messed up with the code. What I want is that when the session is set in the signin.php file, I want $user in the content in "log in as $user" automatically updated without refresh the page, any help will be greatly appreciated!
First, work on diligently formatting your code more effectively. That code you posted was all over the place. This is a bad practice to get in and leads to errors, bugs, and other effects which can be difficult find due to the formatting.
If I follow what you're doing, when someone logs in and then hits the index.php page, you want to be able to load a user's information from another file that will give back the user data asynchronously?
signin.php
Your code is confusing in what it appears to be doing; you simply have not told us enough both in code and explanation to understand what the workflow entails.
For instance, in signin.php, you're echoing a <script> tag that does an $.ajax() request, but who/what get's this code? Is this part of the signin.php content, if the user successfully logs in? Does this mean the signin.php will load the page to use the $.ajax() here, or is that meant to run from the $.ajax() on success?
If it's the latter, you need to return regular Javascript with no markup (like a <script> tag wrapped around it) and use dataType: 'script' in the options.
Also, I would at least use a more descriptive word than array.php; if you're getting user data from it, name that file something like userdata.php.
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
dataType: 'script',
data: 'json=' + jQuery.serialize({user: '$user'})
});
";
Then in userdata.php, you can access it with $_POST['json'].
index.php
This honestly makes no sense:
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
);
Why is the setInterval() in an anonymous function that's run while setting $.text()? This is one of those What? moments, where I'm not even sure what you're trying to accomplish.
Before that though, you have:
$user = $_POST['user'] <<< Note here, you need a ; at the end
Why is this a $_POST? Does the signin.php use $_POST to log a user in? Here, I believe you want $_SESSION (I think, hope, ??), since that's where you stored the username when the user logged in using signin.php.
This is my best guess as to what you're trying to do (assuming you're returning JSON-formatted data):
<?php
session_start();
$user = $_SESSION['user'];
echo "log in as <span id=\"user\"></span><br/>";
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
data: 'json=' + jQuery.serialize({user:'$user'}),
dataType: 'json',
success: function(data){
$('#user').text(data.fullname);
}
});
</script>
";
?>
Try the following:
<?php
$user = 'john';
$_SESSION['user'] = $user;
?>
<script type="text/javascript">
$.ajax({
url: 'array.php',
type: 'post',
data: { 'user': <? echo json_encode($user) ?> }
});
</script>

Categories