Http creates session value on each request in php - php

I've created csrf_token and stored in session variable. while the form submission checked post variable with the session variable. It works perfectly in HTTPS but not in HTTP incognito window.
I just figure out this problem it's because of session value is varying each time on the HTTP request.
give me suggestion to solve this issue. Thanks!
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = md5(uniqid());
}
if(isset($_POST['token']))
{
if (($_POST['token'] === $_SESSION['csrf_token'])) {
echo "match";
}
else{
echo "mismatch";
}
}

Related

Put every POST and GET requests on hold except one specific, then continue

I need only PHP answers.
Setup : Apache Server and PHP version 7.4.
I'm working on a CAPTCHA plugin for WordPress. On that purpose, I thought I'd validate the CAPTCHA field before validating any other request.
This means I want to perform the CAPTCHA POST request before any other $_REQUEST is complete.
These other requests can be multiples, and I won't be able to handle their scripts.
I thought I'd detect if a POST or GET request has been made, then maybe call sleep() and perform my POST meanwhile.
The problem is : sleep() pauses the whole script whereas I only want the other POST and GET requests to be paused...
if ($_SERVER['REQUEST_METHOD'] === 'POST' OR $_SERVER[‘REQUEST_METHOD’] === 'GET' AND $_POST["myRequest"]) {
// Pause every POST and GET requests apart from $_POST["myRequest"] until $_POST["myRequest"] is performed
} else {
continue;
}
You could use session and keep track of the request and save the request if $_POST['myRequest'] is not present, than load the previous request from session or a file. Like this:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST' OR $_SERVER[‘REQUEST_METHOD’] === 'GET') {
// POST myRequest has been done before
if(isset($_SESSION['.my-request.lock'])) {
// If present remove it
unset($_SESSION['.my-request.lock']);
if(isset($_SESSION['my-data.json'])) {
$my_prev_request = json_decode( $_SESSION['my-data.json'] );
unset($_SESSION['my-data.json']);
}
// Process other requests
} else {
if(isset($_POST['myRequest'])) {
$_SESSION['.my-request.lock'] = true;
// Do your own thing
} else {
// No myRequest and no file, save request data to load it after POST myRequest
$_SESSION['my-data.json'] = json_encode( $_REQUEST );
}
}
} else {
// Display Error ?
continue;
}

Json Syntax Error on Session Expire

I'm working with Slim Framework and I would like to redirect the user to the login page if the user has lost his session but I'm always getting a SyntaxError : Unexpected token < at position 0.
My session validation code in php is this:
private function _validaSessao() {
$user = $this->userData['IdUser'];
if(null === $user || trim($user) == '') {
header("Location: http://192.168.0.9/", true, 301);
die();
}
}
I've tried that and all the following:
header('refresh:5;url=http://192.168.0.9/');
echo '<script>window.location.href = "http://192.168.0.9/";</script>';
return('<script>window.location.href = "http://192.168.0.9/";</script>');
echo json_encode('<meta HTTP-EQUIV="REFRESH" content="0; url=http://192.168.0.9/">');
I've tried them all and I'm always getting
200 ---- SyntaxError: Unexpected token < in JSON at position 0
The only piece of code that worked for me was:
echo json_encode(array(
'SemSessao' => true
));
But the above code makes me checking on every single call on JavaScript and I would like a solution that PHP will redirect me. This way I wouldn't need to keep checking on every single JS call (which are a lot) and each time a php object was instanciated it would check for session and redirect the user without the use of JS.
Update 1 - Include JS code (lovely downvotes everywhere :D)
getDadosPlaneamento: function() {
var req = {Rota: '/planeamento/getDados/AUTO'};
var dfd = $.Deferred();
$.when(App.gajax(req)).done(function(d) {
On.Planeamentos = d.Planeamentos;
dfd.resolve();
});
return dfd.promise();
},
The above code is what refers to my php route and then:
$onapp->get('/planeamento/getDados/:tipo/', function($tipo) {
if ($tipo == 'AUTO') {
$P = new MongoApi\Planeamento();
$ret = array(
$P->getAllMongo();
);
}
echo json_encode($ret);
});
And when I do $P = new MongoApi\Planeamento(); I check if the user has a valid session on the constructor using _validaSessao();
The server cannot redirect a client from an AJAX call. The AJAX call is a background HTTP request. Whether that HTTP requests gets redirected or not is irrelevant to the browser. The browser will return the request response to the AJAX client, and if that response is "your request has been redirected" then that's that. Again, a redirect doesn't redirect "the browser", it redirects the HTTP request. Or more precisely speaking, it tells the HTTP client that it should retry its request somewhere else; nothing more.
If your AJAX requests can fail due to a session timeout and whenever that happens you want to present the user with a login page, you will have to do that client side. In order to not repeat that same code every time, you make a function/object/service out of that. E.g. something along the lines of:
function makeAJAXRequest(url, data) {
return fetch(url)
.then(response => {
if (response.status == 403) {
window.location = '/login';
throw new Error('Forbidden');
} else {
return response;
}
});
}
Here the server is expected to respond with a 403 Forbidden status code for unauthorised requests. If you make all your AJAX requests through this function, it will automatically handle that case by redirecting to the login page.
Remeber that header() must be called before any output is generated. you can use ob_start() and op_end_flush() to avoid output previous to your header.
ob_start ();
header ("Location: http://192.168.0.9/", true, 301);
ob_end_flush ();

PHP session not reinitializing after logout logic

I have a problem with a session variable, I have used it well up until now but after implementing the logout logic, after relog I am unable to store my session variable again.
For the log in I use an ajax request that looks like this:
if ($row['password'] == $entered_password) {
if (!isset($_SESSION['user_email'])) {
$_SESSION['user_email'] = $entered_email;
} else {
unset($_SESSION['user_email']);
$_SESSION['user_email'] = $entered_email;
}
echo "login_validated";
exit;
} else {
echo "invalid_password";
exit;
}
and the request is:
$.post('php/login.php', {
emailLogin: emailLogin,
passwordLogin: passLogin
}, function (responseText) {
if (responseText === "invalid_username") {
alert ("Username is invalid! Please check it again or make sure you have already registered first!");
} else if (responseText === "invalid_password") {
alert ("Given password is incorrect! Please try again.");
} else if (responseText === "login_validated") {
window.location.href = "php/pages/expenses.php";
} else {
console.log(responseText);
alert ("A problem occured at te server level, please try again later! If problem persists, please contact us!");
}
});
But after implementing and using the following logic for the log out, my session variable value it's not saved and displayed anymore:
$(document).ready( function (event){
$('#logoutButton').click(function (event) {
event.preventDefault();
var user_response = confirm("Are you sure you want to logout? Your current session will be closed!");
if (user_response === true) {
<?php
if (isset($_SESSION['user_email'])) {
unset($_SESSION['user_email']);
}
session_destroy();
?>
window.location.href = "../../index.php";
}
});
});
I mention that I've first tried to use a separate file for the logout with header redirect, but was blocked by my built in adblocker similar ad-blocker error. I have supposed that maybe on my previous login actions I have made too many session variables, and proceeded to clean all my cookies. It did not had any effect. Also, read other posts and the documentation and still have no clues what I have done wrong.
Also, regarding being sure to clean all previously stored session vars, I have called once the function: http://php.net/manual/ro/function.session-unset.php session_unset. Again, no improvement seen so far. I've kept trying to read the documentation but nothing seems wrong with my code, and in aother similar forum posts I have not found anything useful. Thank you in advance!
EDIT: Short mention about the password - yes, currently they are stored in plaintext, but it is just a personal project, and upon finishing I will also implement a salt and pepper encryption on passwords.
Many thanks to you #Syscall! Almost crazed about this :) Kept everything the same, just modified the php script inside the front end to an ajax request:
`var user_response = confirm("Are you sure you want to logout? Your current session will be closed!");
if (user_response === true) {
$.ajax({url: "../logout.php", success: function(result){
console.log(result);
window.location.href = "../../index.php";
}});
}`
also added a session_start(); in the logout file. Now all the logic works, logging in, logging out, trying on different users and so on.

Problems with deleting $_SESSION in PHP

I'm having a problem with deleting the session. It's stored in the cookies, and whenever I click on the log out button, nothing happens.
HTML
<input id="log_out_button" onclick="logout()" type="button" value="Log Out">
AJAX
function logout() {
// Create request object
var request = new XMLHttpRequest();
// Create event handler that specifies what should happen when server responds
request.onload = function() {
// Check HTTP status code
if(request.status == 200) {
document.getElementById("error_messages").innerHTML = "";
}
else
alert("Error communicating with server: " + request.status);
}
// Set up request with HTTP method and URL
request.open("GET", "php/log_out.php");
//Send request
request.send();
}
PHP
<?php
//Start session management
session_start();
//Remove all session variables
session_unset();
//Destroy the session
session_destroy();
?>
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
so if you want to close user session, you also need to clear cookies
setcookie(session_name(), false, -1, '/');
http://php.net/manual/en/function.setcookie.php
http://php.net/manual/en/function.session-start.php

cookie is not working

I set cookie in php by sending values through post but on redirect cookie, it showing that cookie is not set.
//username is just stored here for an example, it is not a good process to store credentials in cookie.
$('.loginDialogBtn').click(function() {
$usernameLogIn = $('#usernameLogIn').val();
var $passwordLogIn = $('#passwordLogIn').val();
$.post('authorizationAdmin.php', {
usernameLogIn: $usernameLogIn,
passwordLogIn: $passwordLogIn
}, function(data) {
var response = JSON.parse(data);
if (response['done'] === $usernameLogIn ) {
location.href = 'http://foodinger.in/Admin/home.php?restUsername=' + $usernameLogIn;
}
else {
$('.loginError').html('Incorrect Username and password');
}
});
});
php
if(isset($_POST['usernameLogIn']) && !empty($_POST['usernameLogIn']) && isset($_POST['passwordLogIn']) && !empty($_POST['passwordLogIn'])) {
$Username=strip_tags(trim($_POST['usernameLogIn']));
$password = strip_tags(trim($_POST['passwordLogIn']));
setcookie('username',$username, time() + (83600*30), "/Admin/", '.foodinger.in');
setcookie('restaurantId',$restId, time() + (83600*30), "/Admin/", '.foodinger.in');
}
after click on login button i can see cookie is being set in my browser but i can't fetch it using $_COOKIE.
is there any server setting which could make it wrong ?
update -- i was using "walkme" which created the problem, once i removed walkme and deleted all the cookies, it worked. Can anyone please
tell me why "walkme" is creating problem in fetching my cookie
variables
Thanks in advance
Try this to debug your cookie :
// Print an individual cookie
echo $_COOKIE["username"];
echo $HTTP_COOKIE_VARS["username"];
// Another way to debug/test is to view all cookies
print_r($_COOKIE);

Categories