PHP SESSION variable troubles - php

I'm sorry to trouble you, I have tried my best to solve this but I am not sure where I am going wrong and I was wondering if someone out there would be willing to help!
Basically, I am having some issues with $_SESSION variables; I would like for each occasion that a visitor came to the page that they would be shown a different content message.. The below code, when first landing on a page will seem to skip the first "content1", and will display "content2" instead, then "content3" after another revisit. I've put in an unset call, which eventually sends it there, am I not using _SESSIONS correctly?
I'm not sure how the session variable was assigned to 1, for it to land correctly in the if===1 statement without it first returning the original "content1"
if (empty($_SESSION)) {
session_start();
}
if (!isset($_SESSION['content'])) {
$content = "content1";
$_SESSION['content'] = 1;
return $content;
}
elseif ($_SESSION['content'] === 1) {
$content = "content2";
$_SESSION['content'] = 2;
return $content;
}
elseif($_SESSION['content'] === 2) {
$content = "content3";
unset($_SESSION['content']);
return $content;
}
Apologies for babbling or whether this was a simple fix / misunderstanding on my part. It's caused quite a headache!
Many thanks.
-edit-
This is a function that is called from within the same class, it has not gone through a loop anywhere either..

You are only calling session_start(); if the session has not been created.
What about the other times, when it's 1, or 2?
Call session_start(); regardless of your if (empty($_SESSION)) { statement

You should always use the session_start() function. If a session exists, it will continue it, otherwise it will create a new session.
Your code can then be simplified to the following:
// Start/Resume session
session_start();
// Get content
function display_message()
{
if ( ! isset($_SESSION['content']))
{
$_SESSION['content'] = 1;
}
if ($_SESSION['content'] == 1)
{
++$_SESSION['content']; // Increment session value
return 'Content #1';
}
elseif ($_SESSION['content'] == 2)
{
++$_SESSION['content']; // Increment session value
return 'Content #2';
}
elseif ($_SESSION['content'] == 3)
{
unset($_SESSION['content']); // Remove session value
return 'Content #3';
}
}
// Display content
echo display_message();
However, if someone visits your page a fourth time, they will be shown the first message again (because the session value is no longer tracking what they've been shown).
Perhaps this sort of functionality might be handled better with by using a cookie to track this information?

Related

Undefined index when user returns in same session

I have a simple login system with sessions. The user is being redirected to a page when the user succesfully logs in.
The problem is when the user leaves my site and comes back later to index.php (the same session) the user will get "Undefined index" because there's no parameter supplied when the user enter my site and is still logged in.
I use php switch to control my pages.
I have this code first in my index.php:
require_once('function.php');
session_start();
if (!is_user()) {
redirect('signin.php');
}
?>
My file with switch looks like this:
<?php
$p=$_REQUEST['p'];
if (isset($p)) {
switch ($p) {
case "vine":
include "vine.php";
break;
}
?>
Obviously $_REQUEST['p'] is undefined.
If you want your script to still know the p parameter when a user returns, you must somehow save it for further requests. This could be done like this in index.php:
<?php
session_start();
$p = isset($_REQUEST['p']) ?
$_REQUEST['p'] : (
isset($_SESSION['p']) ?
$_SESSION['p'] :
false
)
);
if ($p !== false) {
$_SESSION['p'] = $p;
switch ($p) {
case "vine": include "vine.php";
break;
}
} else {
die ('Unknown category ....');
}
?>
The code looks for an explicitely given parameter p and takes this if available. Otherwise it looks for a session parameter p.
Else it sets p to false to indicate that no value is avaible.
If a value for p is given, the session variable $_SESSION['p'] is set. And, of course, sesssion_start() must be called at the top of the script to make session variables available.
I assume the 'Invalid index' comes from $p=$_REQUEST['p'];. You want to check whether that array element exists.
if (isset($_REQUEST['p'])) {
What about this:
if (isset($_REQUEST['p']))
{
$p = $_REQUEST['p'];
// ...
}
But notice this: http://php.net/manual/en/function.array-key-exists.php#example-5520

Echo (or display errors) after page reload

My latest idea which didn't seem to work was to store the array in a session,
include_once "scripts.php"
.........
//some code later
$errorlog .= "a random message<br/>";
$_SESSION['errorlog']=$errorlog;
reloadPage();
And then if 'errorlog' wasn't empty then display it,
[code]
<div class="randomclass">
<?php
displayErrors('errorlog');
?>
</div>
//here are the functions
function reloadPage(){
Header('Location: '.$_SERVER['PHP_SELF']);
}
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION['valuename'])){
echo $_SESSION['$valuename'];
unset($_SESSION['$valuename']);
return true;
}else{
return false;
}
}
[/code]
scripts.php
<?php
if(!isset($_SESSION)) session_start();
........
I have included scripts.php which starts with if(!isset($_SESSION)) session_start();.
I'm new to php, still making my first webpage (or actually, preparing scripts for it). I can't seem to successfully find bugs in my scripts because I don't know how to show the errors after a page reload is needed.
What I want, is a way to store strings like in this $errorlog and display it just like an echo(in div or whatever) after the page was reloaded
I don't get any errors with headers, the page reloads correctly but the problem is that no text is displayed after the page reloads, so I don't see why I shouldn't be using them unless you know another way to reload the page after script is done
surely this way is not the best one, but I think that the problem is very easy..
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION['valuename'])){ // here you must put a variable $valuename instead a simple string 'valuename'
echo $_SESSION['$valuename'];
unset($_SESSION['$valuename']);
return true;
}else{
return false;
}
}
You must change the session key at this row whit: $_SESSION[$valuename]
if(!empty($_SESSION['valuename'])){
The correct function is the follow:
function displayErrors($valuename = "errorlog"){
if(!empty($_SESSION[$valuename])){
echo $_SESSION[$valuename];
unset($_SESSION[$valuename]);
return true;
}else{
return false;
}
}
Bye!
Marco

ModX: 2 snippets on same page interacting with each other

I have 2 snippets (below). The issue is the if statemnt if ($loggedin != NULL){ in the 2nd snippet doesnt pass even if the variable is not null. Its like the $loggedin variable in the 1st snippet doesnt apply to it. If I combine the 2 snippets into 1 they work fine.
Does anyone know how to make 2 snippets 'talk' to each other?
(ps, running Revo 2.1.3)
<?php
$loggedin = "";
if (!isset($_SESSION['user_id'])) {
// redirect to login page
}
else {
$loggedin = "true";
}
2nd:
<?php
if ($loggedin != NULL){
echo "logged in";
}
else {
echo "error";
}
First off, you are not passing the $loggedin variable to the second snippet, do this normally with a post or session variable.
Second, there is an easier way to check, these are straight out of Bob's guides.:
There are various methods. One easy method is to use this code:
if ($modx->user->get('username') == '(anonymous)') {
/* user is not logged in */
}
Here is the official method for seeing if the user is logged in
to the current context:
if ($modx->user->hasSessionContext($modx->context->get('key'))) {
/* user is logged in */
}
If you know the name of the current context (e.g., web),
you can use this method. The name of the context is required:
if $modx->user->isAuthenticated('web') {
/* user is logged in to web context */
}
that is if you need to roll your own authentication for some reason. ~ Otherwise, the login/register extra will do all of this for you.
*UPDATE***
Two pass variables from one snippet to another in the same resource you can set/get placeholders:
<?php
// snippet one
$modx->setPlaceholder('output','Place holder set!');
<?php
// snippet two
$myvar = $modx->getPlaceholder('output');
echo 'this is the value of "output": '.$myvar;

cookie won't set

This is a question regarding an old one of mine: cookie won't unset:
cookie wont unset
where I had problems unseting the cookie (but it was set 'properly'),
Now that the problem is solved; the cookie doesn't seem to SET
cookie 'set': (does not work)
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
cookie check: (seems to work)
function sesion(){
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else{ return false;
}
}
cookie unset: (works)
function cerrar_sesion(){
session_start();
$_SESSION['logueado']= false;
$_SESSION['id']= NULL;
session_unset();
session_destroy();
setcookie("id",false,time()-3600,"/");
setcookie("alias",false,time()-3600,"/");
unset($_COOKIE['id']);
unset($_COOKIE['alias']);
}
What happens is that login is working only through $_SESSION so after 30 minutes of no activity the user is no longer logged in,
Any idea what I'm doing wrong? Thanks a lot!
As stated above you cannot read a cookie from the same page as it is set. I see you have tried tricking this using ajax but i do not believe that would be a valid trick as Ajax calls do not change the state of the page you are still on. so you can either do a full refresh or redirect OR at the same time you use setcookie you can also define the values you need in $_COOKIE so its available on the same page. like this:
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
$_COOKIE['id'] = $data['id'];
$_COOKIE['alias'] = $data['nombre'];
set cookie lines work fine with me.
as for }else if(isset($_COOKIE['id']) && i
since you return if you remove the else here is still okay, if there was no return above you would have to keep the else here in order not to evaluate this block
generally speaking I am not sure that elseif is the same with else if in all cases
The way the function session is build will act like this:
On the first load it will show: no cookie, no session because you cannot see a cookie until reload (which I guess you already know).
-On second load you will see cookie alive session set.
-after the second load you always see session is set.
All I want to say that session works exactly as expected to work, so I don't really see any problem.
<?php
$data='Hello';
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
session_start();
function sesion()
{
if(isset($_SESSION['id']) && isset($_SESSION['logueado'])
&& $_SESSION['logueado'] == true)
{
echo 'SESSION IS SET<br>';
return true;
}
if(isset($_COOKIE['id']) && isset($_COOKIE['alias']))
{
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
echo 'COOKIE is alive and session set'.$_SESSION['alias'].'<br>';
return true; //THIS IS NEVER RETURNING TRUE
}
else
{
echo 'NO SESSION, NO COOKIE YET, WAIT UNTIL REFRESH<br>';
return false;
}
}
sesion() ;
?>
Try removing the path parameter from your setcookie() calls, maybe that's the issue.
Also, did you check that $data actually contains any data?
Propably you have really known problem with setting cookies and you have disabled error reporting about warnings.
Just try:
error_reporting(E_ALL);
You will propably see at your page something like "Cannot modify headers. Headers already sent". That because you need to SET cookies before you display anything on your page. So solution to resolve your problem is to implement your code to SET cookies at the bottom of your page or use ob_start/ob_clean.
Let me know if it helps :)
According to the "setcookie()" implementation in PHP, the cookie value check will not work until you move the control from the page that you are creating the cookie. So, your "SET" will create the cookie in one page and "sesion()" should be called from other page to check the value of the cookie that you set. Try it and hope it helps!
Try the following approach (please refine this as per your need). What I am trying here to refresh the page itself after setting the cookie and the "sesion()" function is a dynamic function that may or may not have any arguments. So, when you pass any argument to it, the the cookie will be set, otherwise it will be checked for existence. An accompanying function with func_num_args() is func_get_args(). It will help you to sanitize the expected arguments in the function.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);
session_start();
function sesion(){
// func_num_args() number of arguments passed to the function
if (func_num_args() == 0) { // if no arguments were passed, means the page is refreshed and cookie won't be set further
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else {
return false;
}
}
else { // if number of args > 0, means you need to cookie here and refresh the page itself
global $data; // set this to global as the $data will be available outside of this function
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
/**
* refresh the page by javascript instead of header()
* as header already being sent by the session_start()
*/
echo '<script language="javascript">
<!--
window.location.replace("' . $_SERVER['PHP_SELF'] . '");
//-->
</script>';
die();
}
}
sesion(1); // passed an argument to set the cookie
?>
I think you will face issue with the JavaScript section, as it will change the page URL and I guess you are trying to include this script into the pages. So, I will take the help of call_user_func() and the final "else" part after the setcookie() lines will be changed with the following line:
call_user_func("sesion");
Hope this will make sense now.

PHP How to implement flash messages

I'm working on a small custom CMS and would like to implement flash messages. I have searched for hours, but I can't find anything that behaves the way I want. And I can't seem to make anything work.
I want to be able to pass a variable (via $_SESSION) to another page and, on that next request, it will be removed. I want to be able to use a keep_flash function, in case I don't want the message to be removed with the next server request.
Can anyone send me in the right direction? I can't really make anything work.
Thanks.
EDIT: Here is some code I am playing with. It sort-of works. When you first visit the page, it sets the $_SESSION and everything is fine. But if you refresh, now it deletes the $_SESSION. If you refresh again, it adds it back...etc. So, if you were to visit the page, refresh, then go to another page the flash message wouldn't be in the $_SESSION. So how can I fix this?
class flash
{
private $current = array();
private $keep = array();
public function __construct()
{
if (isset($_SESSION['flash'])) {
foreach($_SESSION['flash'] as $k=>$v)
{
$this->current[$k] = $v;
}
}
}
public function __destruct()
{
foreach ($this->current as $k=>$v)
{
if (array_key_exists($k,$this->keep) && $this->keep[$k] == $v) {
// keep flash
$_SESSION['flash'][$k] = $v;
} else {
// delete flash
unset($_SESSION['flash'][$k]);
unset($this->current[$k]);
unset($this->keep[$k]);
}
}
}
public function setFlash($key,$value)
{
$_SESSION['flash'][$key] = $value;
}
public function keepFlash($key)
{
$this->keep[$key] = $this->getFlash($key);
}
public function getFlash($key)
{
if (array_key_exists($key,$this->current)) return $this->current[$key];
return null;
}
}
basic idea is to have script always check specific variable in session (usually called 'flash') for content - if not empty display and delete it from session. When message is needed just place is same variable in session and next check would pick it up....
keep_flash in your case would not proceed with delete, or move to other place based on your needs.
for implementation just google it - usually it wrapped in some kind of class - I personally like phpclasses.org or part of framework

Categories