Passing a $_SESSION failed when creating the $_SESSION within Ajax function - php

I have a simple registration form and the new comers will be registered with an ajax function. There I create a $_SESSION['is_logged'] when the registration is finished.
On var_dumb I get that the var is set. But when redirect on another page it is empty (I have included already the session_start() on the both pages...
I have read somewhere in the net that:
"Sessions are ONLY written on a page load/refresh".
Is this the case, or I have to look for some other issues within my code.
the ajax:
$.ajax({
url:"../controllers/register.php",
type:"POST",
data:res,
success: function(responce){
if (responce==1) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>It seems that you have already submited the form. Click to "+
" <a href='login.php'>log-in</a> or to <a href='register.php'>register</a>.</p>");
}
else if (responce==2) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>You have successfully created account. Click to "+
" <a href='start.php'>welcome</a> to start your .</p>");
$('.menu').append("<li><a href='logout.php'>Log out</a></li>")
}
else{
$('#msg').text(responce);
}
},
error: function(){
$('#msg').text("Opss, try again");
}
});
the register.php file:
if (isset($_SESSION['submited'])) {
echo 1;
exit;
}
include_once('../models/functions.php');
// Give the post parametters to another var
$arr=$_POST;
// function for uploading
$reg = registerMe($arr);
if ($reg === true) {
$_SESSION['submited']=1;
$_SESSION['is_logged']=1
echo(2);
}
else{
echo($reg);
}
exit;
The session_start(); is included in the header of the first page where from the ajax is started.And the second page - where the $_SESSION['is_logged'] is lost, again the session_start(); is part of dc_header(); function. start.php:
<?php
dc_header("Речник|Регистрация");
if (!isset($_SESSION['is_logged'])) {
#header("location: ../views/login.php");
var_dump($_SESSION);
}
?>

add
session_start();
to the top of register.php
You need to specify session_start, so your server who was commanded to execute "register.php" (either from ajax, direct call, browser scripts, cron job or whatever possible you-name-it) will handle the execution and the setting of $_SESSION variables in reference to the connected clients session. Server won't guess by itself that this is an "ajax call from an already session_start page". You need to specify that whatever is done in register.php is done in the current client's session.

Related

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.

Stop $_GET being processed after reload

I'm creating a link which appends a $_GET variable to the end of it for use of deleting files / other PHP tasks.
Delete file
Part of my PHP code looks for the variable and if it exists, it runs the unset function to remove the file, but when I reload the webpage, it obviously tries to remove the file again. Is there any way to remove the $_GET after it has been run once to stop the processing after a refresh?
<?php
if (isset($_GET['delete_file'])) {
if (file_exists($full_path.$_GET['delete_file'])) {
unlink($_GET['delete_file']);
} else {
echo "File ".$full_path.$_GET['delete_file']." doesn't exist";
}
}
?>
Delete file
You can use ajax to remove files so it won't refresh.
Delete file
<script>
function deletefile(filename){
var data = {delete_file:filename };
$.ajax({
url: 'delete.php',
type: 'post',
data: data,
success: function(response) {
// .. do something with response ..
// you can use window.location to refresh page
// or if you have js method to refresh page. you can call it here
}
});
}
</script>
In php file you can retrive with post
<?php
if (isset($_POST['delete_file'])) {
if (file_exists($full_path.$_POST['delete_file'])) {
unlink($_POST['delete_file']);
} else {
echo "File ".$full_path.$_POST['delete_file']." doesn't exist";
}
}
?>
But as the commenters say this is open to potential security issues. You need to take care of security if you use this approach in production.

php browser back after post

I have php page where I used a form to submit messaage. It submits to itself :
action="<? php echo $_SERVER['PHP_SELF'];?>"
Then it sends email, and I have a javascript function that uses jnotify, to alert whether message is sent successfully or not. This function checks if php variable $sent=='yes' then notify about sucessful message else notify about error.
The problem is that when user sends message and goes to another page and comes back by using browsers back button, it is displaying notification. I want it to show notification once only and forget about notification when browsers back or refresh used.
What is the best solution for it?
Try something like this:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (form_is_valid()) {
$_SESSION['form_success'] = true;
} else {
$_SESSION['form_success'] = false;
}
header('Location: ' . $_SERVER['PHP_SELF'];
exit;
} else if (isset($_SESSION['form_success'])) {
if ($_SESSION['form_success'])) {
// insert success javascript
} else {
// insert failure javascript
}
unset($_SESSION['form_success']);
}
// display_form
This should make it so they only see the success/failure message once, and if they use the back button at a later time, they will not receive a warning about re-submitting post data, and they also won't see a success/failure message twice. The only time that javascript should show is if they just submitted the form in the last request.
You can use ajax request to send your form.
$.ajax({
type: 'POST',
url: processor.php,
data: $('#form_id').serialize(),
success: function(data){
if(data==0){ alert('message sent'); }else{ alert('message not sent'); }
}
});
I think the Zend Helper Flash messenger might be what you're looking for.
"This means that the message will be available for retrieval on the next request, but unavailable on the request afterwards."
additional documentation

Redirecting to a new page based on an AJAX call

I am using ajax with jQuery to make a request from a page on my site. Now if the login failed (or the call failed for a different reason), I return an error message and put it in a label. But if the call succeeds, I want to navigate to another page. My issue is that if the call succeeds, I end up with the text of the new page in my label.
Here's my Javascript:
$.post("chklogin.php", { username: username, password: password }, function(data) {
$('#msg').html(data);
});
And here's the PHP that it calls:
if(mysql_num_rows($result)==0) {
$msg="<h3>Enter valid Username and Password.</h3>";
echo $msg;
} else {
$row=mysql_fetch_assoc($result);
$_SESSION["userid"]=$row["pgmail"];
header("location:user.php");
}
Well this issue could have been clearer, and I would encourage you to check your spelling and code before you post again.
The issue is that you haven't sent the page to redirect, you have sent the page being called to redirect.
To fix this issue:
Firstly, get rid of the header redirect on your PHP code and replace with:
echo 'SUCCESS';
Secondly, change your AJAX code to the following:
$.post("chklogin.php", { username: username, password: password }, function(data) {
if(data=='SUCCESS'){
window.location.href = "user.php";
}else{
$('#msg').html(data);
}
});
This will make the page redirect, not the page called by AJAX.

returning php session to ajax

I am having trouble getting jQuery ajax to recognise a session. I am creating a php session from a login script, but what is happening is that when ajax loads the authenticated page, the session is always unset. For example, in the secure page, if I refresh the page, the session id changes each time. I have session_start(); in each page. Can someone please show me the correct way to handle sessions with ajax and php? I have spent 2 days and have used google so much, I will probably get an invite to there xmas lunch :-) I have included the relevant code and would be grateful for any help. Thanks
PS. If it makes any difference, I am trying to develop mobile app using jquery mobile.
login html js
$(function() {
$("#kt_login1").click(function() {
var user = $('#user').val();
var pass = $('#pass').val();
if (user == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=user]').addClass("label")
return false;
}
else if (pass == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=pass]').addClass("label")
return false;
}
else $('label[for=user]').removeClass("label");
$('label[for=pass]').removeClass("label");
//alert(user + pass + ok);
data = 'user=' + user + '&pass=' + pass;
$.ajax({
type: "POST",
url: "testajax.php",
cache: false,
data: data,
success: function(data) {
if (data == 'authenticated') {
//alert(user);
document.location = 'secure.php';
}
else $('#login_message').html('You are not authorised');
//$(ok).val('Logged In');
//$("#login").get(0).reset();
//$("#form").dialog('close');
},
error: function(xhr, ajaxOptions, thrownError) {
jAlert('There was an exception thrown somewhere');
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
});
testajax.php
<?php
// test wether the user session is already set
$username = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string(md5($_POST['pass']));
mysql_connect('localhost', 'root', '');
mysql_select_db('sample');
//now validating the username and password
$sql="SELECT * FROM user_usr WHERE username_usr='$username' and password_usr='$pass'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0) {
session_start();
$_SESSION['u_name']=$row['name_usr'];
/*
echo '<pre>';
print_r( $_SESSION['u_name'] );
print_r( $_REQUEST );
echo '</pre>';
exit;
*/
echo 'authenticated';
}
else
{
echo 'Unknown User';
}
?>
+++++SOLUTION+++++
Changed form input from submit to button and voila. All ok
you have to call session_start() each time working with a session (not only when creating it)
see: http://php.net/manual/en/function.session-start.php
There are a whole load of reasons this might be the case - but you're code is upside down! This may well be the cause (or a contributory factor).
You should not treat the existence of a session as evidence of authentication (the contents of the session is another thing altogether). Call session_start() at the top of your script - not conditionally, half-way through.
As to why your session data is not available...that's an FAQ here - have a look at some of the previous answers for potential causes / how to investigate.

Categories