php session variable problem when unset - php

i have made a function to set a session variable $_SESSION['flash'] in order to store a message between page
function setFlash($string,$type="info") {
switch ($type) {
case "warning":
$_SESSION['flashtype'] = "warning";
break;
case "error":
$_SESSION['flashtype'] = "error";
break;
case "info":
$_SESSION['flashtype'] = "info";
break;
default:
$_SESSION['flashtype'] = "info";
break;
}
$_SESSION['flash'] = $string;
}
and a function to print this message
function printFlash() {
echo $_SESSION['flash'];
unset($_SESSION['flash']);
}
i call this function at the top of every page (naturally after session_start)
the problem is that it doesn't print nothing, but if I comment " unset($_SESSION['flash']);" it prints the message in every page.
how can i solve?
Solved sorry my fault.
my page is something like this
include "func.inc.php"
session start
function editSomething {
that call setFlash()
}
include "template.php" (where printFlash() is called)
now i put printFlash directly in my page and works..bah strange...what's my mistake?

On every page this is what happened:
Make a session
Display flash
Delete flash
Create 'flash' with value
You have to move Create before display.
(it's also not very usefull because you do not transmit 'flash' (it's delete right after been created)

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

PHP SESSION variable troubles

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?

Content of class property gets cleared out before outputting to browser

I have this inside a class named site among other harmless stuff:
private
$notice_type = '',
$notice_msg = '';
public function setNotice($type,$msg){
$this->notice_type=$type;
$this->notice_msg=$msg;
}
public function notice($what){
switch($what){
case 'type': return $this->notice_type; break;
case 'msg': return $this->notice_msg; break;
}
}
public function clearNotice(){
$this->notice_type='';
$this->notice_msg='';
}
I've set this class to a session like this:
$_SESSION['site'] = new site();
Here's a scenario of how I use it:
After submitting a form; I set the notification like this : $_SESSION['site']->setNotice('success','success message');, or error if that's the case and redirect the user somewehere using header().
Then I output the message like this on the landing page:
echo $_SESSION['site']->notice('msg');
$_SESSION['site']->clearNotice();.
But; When I use the clearNotice()-function - the contents of both $notice_type and $notice_msg is cleared out before it gets outputted to the browser.
I need for it to stay untill the user navigates away from the page somehow. What am I missing here?
I don't know what happend. But somehow this script started to work as expected.
I've rewritten the code over and over for a while now, and as far as I know it's just about the same as before. But anyway; This is what works now:
site()-class:
This class controlls notifications as well as settings set by the user - like preffered sorting direction of data and selections worth remembering for better user experience and such.
<?php
class site {
private
$notice_type = '',
$notice_msg = '';
public function newNotice($type,$msg){
$this->notice_type=$type;
$this->notice_msg=$msg;
}
public function notice($what){
switch($what){
case 'type': return $this->notice_type; break;
case 'msg': return $this->notice_msg; break;
}
}
public function clearNotice(){
$this->notice_type='';
$this->notice_msg='';
}
}
?>
I have a document where I configurate the entire site by setting a couple of variables to Yes or No - As in this case : $_SITE_CLASS_site.
<?php
# check to see if session is started
if(!isset($_SESSION)){session_start();}
//
// check if site()-class should be activated for this site
if($_SITE_CLASS_site=='Yes'){
# if Yes; prevent resetting the class if it has already been started.
if(!isset($_SESSION['site'])){$_SESSION['site']=new site();}
//
}
//
?>
I've created a template where I have this code before the page content is outputted:
basically it just checks if there is any message to display
<?php if ($_SITE_CLASS_site=='Yes'&&$_SESSION['site']->notice('msg')!=''): ?>
<div id="site-notice-<?=$_SESSION['site']->notice('type')?>" class="grid_12"><p><?=$_SESSION['site']->notice('msg')?></p></div>
<?php endif; ?>
Then I load the page content, and at the end I have this:
the notice should be viewable untill the user closes it, or leaving the page. I don't want, or need, to keep the message
<?php
if ($_SITE_CLASS_site=='Yes'&&$_SESSION['site']->notice('msg')!=''):
$_SESSION['site']->clearNotice();
endif;
?>
Now; Whenever I need to give the user a feedback on their actions - after submitting a form successfully for example - I can just do this at the end of the script:
$_SESSION['site']->newNotice('success','<b>Success!</b> Your request was submitted successfully...');
header('Location '.$_SERVER['HTTP_REFERER']);
exit;
It works like a charm...

calling ajax from within a php function having a switch ($this->method)

when creating an XMLrequest in a php file having a code which goes something like this... I am using a MVC ( model-view-controller structure ) and this is a controller php file..
Controller_Institute extends Controller_Default{
function register(){
try {
$this->requireLogin();
switch($this->method){
case 'GET':
$content = $this->render('institute_registration_confirm');
break;
case 'POST':
$result = mysql_query("SELECT * FROM password WHERE pass='".mysql_real_escape_string($_POST['pass'])."'");
$num=mysql_num_rows($result);
if($num==2)
{
$content = $this->render('institute_registration');
}
else
{
$content = $this- >render("message",array('msg'=>'Your password is incorrect'));
}
break;
}
$institute = R::dispense('institute');
$institute- >import($_POST,'name,latitude,state,longitude,address,phone,year,url');
$id = R::store($institute);
}
catch(exception $e){
//If there was an error anywhere, go to the error page.
$content = $this->render('error',array('exception'=>$e));
}
$page = $this->render('default',array('content'=>$content));
return $page;
}
i am sending the ajax request from within the function ... so when the ajax sends back the request , it gets caught in the switch case... and then the response text becomes the function return value replacing the actual text... any idea how to prevent the xml response from getting into the switch case...? the institute_registration is the view file and i am including that file in my framework and then triggering the ajax function from within that file to check whether the password ( to enable registration form ) is correct or not...
Given the limited information and pseudo-code, I recommend setting up a stand-alone page called say... "ajax.php" that is stand alone and doesn't base it's return value on the request method. The pages that use AJAX will need to either POST or GET from this page depending.
If you determine whether or not regular output vs AJAX output is returned via request method, then you are limiting yourself in 2 ways. The first is you will not be able to do 1 or the other on your web pages (GET vs POST) instead of both. Also, the second, when it comes to the AJAX, you will not be able to run GET & POST AJAX requests, and yes, you can do both with AJAX: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

php var isset, ?data=menu

I have script where some url leads to index.php?data and the page opens
how can I use that to use the url open an "subpage" like index.php?data=menu or so?
the code I use with the first one is
if(isset($_GET['palvelut'])){ echo "this is a sample"; }
You have the right idea, but allow me to elaborate at little on this. You need to check if $_GET['data'] is set, by doing isset($_GET['data']), and if that is set, checking to see if it has a given value, "menu" in this case. You can do that like this $_GET['data'] == "menu". Putting it all together, you get this:
if (isset($_GET['data']) && $_GET['data'] == "menu") {
/* Menu code goes here */
}
If you would like to have this work for multiple values for data you can do the following:
if (isset($_GET['data'])) {
switch($_GET['data']) {
case "Possible_Value_1" :
/* Code for this condition appears here */
break;
case "Possible_Value_2" :
/* Code for this condition appears here */
break;
/* etc... */
default :
//Just as a precaution...
echo "Invalid 'data' value supplied!";
break;
}
}
Hope that helps.
If I understand your question (which I don't), you've answered it already.
Your URL is: http://www.mydomain.com/index.php?data=something
Your code would be:
if (!isset($_GET['data'])) {
//do something because no data argument was passed
} else {
switch ($_GET['data']) {
case "homepage":
header("location: homepage.php");
die;
break;
case "someotherpage":
header("location: someotherpage.php");
die;
break;
//and so on
}
}
Obviously instead of using a header redirect, you might just require() or include() a file, or do something else entirely.

Categories