My php $_SESSION is not saving - php

I'm starting with PHP, so I have no idea what's going wrong. I'm trying to update some value in my $_SESSION var using a function, but is not working.
First of all, I started the session and set a default value to the session if it is "undefined" in my header.php:
<?php
session_start();
if (!isset($_SESSION["locale"])) {
$_SESSION["locale"] = 'pt_BR';
}
?>
Then I have some ajax which calls my PHP function.
$('#change_locale_br').click(function() {
$.ajax({
type: "POST",
url: "i18n/i18n_functions.php",
data: { action: "changelocale", new_locale: "pt_BR" },
success: function() {
}
});
});
After in the php file, I have the following code:
<?php
function changelocale($l) {
$_SESSION["locale"] = $l;
}
if(isset($_POST['action']) && $_POST['action'] == 'changelocale'){
$l = $_POST['new_locale'];
changelocale($l);
}
?>
So the changelocale function is being called with the different values (pt_BR, es and etc), but after called it doesn't really change the $_SESSION["locale"] value.
I made a lot of research and NONE of the suggestions made here or in the PHP documentation page worked. Does someone knows what could be done in this case?
Thanks in advance.

You need to include session_start() at the top of your page, which you intend to set or access $_SESSION information.

Here is the solution: I called session_write_close(); (which is used to assure session data will be "unlocked", since php doesn't allow concurrent writes) right after setting the default values for the session in my header.php:
<?php
ini_set('session.cookie_domain', 'localhost');
if(!isset($_SESSION)) session_start();
if (!isset($_SESSION["locale"])) {
$_SESSION["locale"] = 'pt_BR';
}
session_write_close();
?>
Then in my changelocale.php I called the session_start() and at the end called the session_write_close(). It's like this now:
<?php
if(!isset($_SESSION)) session_start();
function changelocale($new_locale) {
$_SESSION["locale"] = $new_locale;
}
if(isset($_POST['action']) && $_POST['action'] == 'changelocale'){
$l = $_POST['new_locale'];
changelocale($l);
}
session_write_close();
?>

Related

How can update my session using ajax?

I'm using a session for setting language
if(!isset($GLOBALS['lang'])){
$GLOBALS['lang'] = 'en';
}
Then I'm using ajax to update this:
var lang = 'no';
$.ajax({
type: "POST",
url: url,
data: {
lang : lang
},
success: function (data) { (...) }
});
The file being called looks like this:
global $lang;
if(strlen($_POST['lang']) == 2 ){
$lang = $_POST['lang'];
$result = array('lang_set' => $lang);
echo json_encode($result);
}
But my global session is not changed. I'm guessing this is due to the fact that lang.php uses another session instance.
I'm using Wordpress so I'm looking into if I can use some of the built in functions for this purpose. But I'm wondering if I can use PHP sessions for keeping track of selected language? Or do I have to use another method like adding selected language to my url?
UPDATE
Thanks to Ghost, I made it work. If you are using Wordpress, I'm doing the following in functions.php:
// Initialize session
if(session_id() == '') {
session_start();
}
// Set lang session with default language
if(!isset($_SESSION['lang'])){
$_SESSION['lang'] = 'no';
}
//globals
$GLOBALS['lang'] = $_SESSION['lang'];
If you want them to persist on the entire application, use sessions:
session_start();
if(!isset($_SESSION['lang'])){
$_SESSION['lang'] = 'en';
}
Then on the other:
session_start();
if(strlen($_POST['lang']) == 2 ){
$_SESSION['lang'] = $_POST['lang'];
$result = array('lang_set' => $_SESSION['lang']);
echo json_encode($result);
}

PHP log out with AJAX call

I have a logout function that looks like this.
if ($_GET["argument"]=='logOut'){
if(session_id() == '') {
session_start();
}
session_unset();
session_destroy();
$host = $_SERVER['HTTP_HOST'];
$extra = 'index.php';
header("Location: http://$host/$extra");
exit;
}
My problem is that, If I inspect the page and look at the Network preview and response, it looks 'fine'.
There are two php files listed that was processed.
http://localhost:5000/inc/mainScripts.php?argument=logOut
which is where the function is located.
and http://localhost:5000/index.php
Which is where i would like to be redirected.
The Response tab in the Network of the inspect page area in chrome
contains the full login html page login.php but in the browser it remains in the same place. Like the header command has never been called.
What Am I doing wrong?
HTML AJAX call to this function:
$("#logout_btn").click(function() {
$.ajax({
url: './inc/mainScripts.php?argument=logOut'
})
});
SOLUTION
AJAX
$("#logout_btn").click(function() {
$.ajax({
url: './inc/mainScripts.php?argument=logOut',
success: function(data){
window.location.href = data;
}
});
});
PHP
if ($_GET["argument"]=='logOut'){
if(session_id() == '') {
session_start();
}
session_unset();
session_destroy();
$host = $_SERVER['HTTP_HOST'];
$link = "http://$host/index.php";
echo $link;
}
Try this instead.
if( isset($_GET['argument']) && $_GET['argument'] == 'logOut' && !empty( session_id() ) ) {
session_destroy();
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/index.php");
exit;
}
Edit: If you're using AJAX, it'd be easier to send the url from your php script back to your javascript and redirect from there.
You are probably running into the same common problem that many people run into when people first start to program in PHP.
Calls to header() only works when there are NO previous HTML output generated. If there are any HTML output generated, even just a single space, calls to header() will fail. To get around this problem, use functions such as ob_start() and ob_end_flush().

Passing PHP variable with jQuery

I need an assistance on how to transfer this value $row[COMPONENT] in my class1.php into another page process_class.php with jQuery using post method.
i did this but it seems doesnt work ,
$('.cuttingCheckbox').change(function() {
if (this.checked) {
$.post('process_class.php',
{ comp : $($row[COMPONENT]).val(), comp_id : $($row[ID]).val() },
function(response) {
this.setAttribute("disabled", true), alert(comp,comp_id); });
}
});
Does anyone willing to help me ?
you can save that $row[COMPONENT] into session like this:
$_SESSION['row_component'] = $row[COMPONENT];
and in your next page, you just retrieve it:
$row = $_SESSION['row_component'];
As Jonast said (thanks dude), you should initiate the session first at the top of your php file: session_start();

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

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.

Session value changes on ajax page when using a random value

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 ===

Categories