This is simple php code with sessions:
<?php
session_start();
function testSession() {
//global $_SESSION;
var_dump($_SESSION['test']);
}
if (!isset($_SESSION['test'])) {
echo " Nope";
$_SESSION['test'] = " Yeap";
} else {
testSession();
}
?>
The problem is that "$_SESSION" is not a superglobal. "$_SESSION" is undefined in testSession function scope, it is visible only in the main scope. If I uncomment "global $_SESSION" than all will work.
upd:
The error is "Undefined variable: _SESSION" at line var_dump($_SESSION['test']);
upd:
if you write this code:
<?php
session_start();
if (!isset($_SESSION['test'])) {
echo " Nope";
$_SESSION['test'] = " Yeap";
} else {
var_dump($_SESSION['test']);
}
?>
all will work correctly.
Always put your session_start(); at the start of the page.
Try using:
<?php
session_start();
echo "Session test ";
function testSession() {
//global $_SESSION;
var_dump($_SESSION['test']);
}
if (!isset($_SESSION['test'])) {
echo " Nope";
$_SESSION['test'] = " Yeap";
} else {
testSession();
}
?>
Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?php tag.
After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();).
Make sure cookies are enabled in the browser you are using to test it on.
Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
Make sure you didn't delete or empty the session.
Make sure the key in your $_SESSION superglobal array is not overwritten anywhere.
Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
Make sure your file extension is .php (it happens!).
Session variables not working php
Related
I get an error above my students.php
A session had already been started - ignoring session_start() in ...
I have a CRUD wherein I have to notify user if the students have been updated, deleted or created.
The CRUD is working fine, however, if I remove session_start() in server.php, the notification wouldn't show.
students.php:
<?php if (isset($_SESSION['msg'])): ?>
<div class="msg">
<?php
echo $_SESSION['msg'];
unset($_SESSION['msg']);
?>
server.php
if(!isset($_SESSION))
{
session_start();
}
...
$_SESSION['msg'] = "New student saved";
header('location: students.php'); //redirect back to page
$_SESSION['msg'] = "Information updated";
header('location: students.php'); //redirect back to page
redirect.php
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('location: login.php');
die();
}
?>
Should I just change the var $_SESSION['msg'] to another variable? I'm a total beginner in PHP, sorry if it might be a stupid question.
It doesn't look like you have a framework going, so I think there are some general tips to help your script succeed.
1) Have a top-level config file in your site root that you include at the top of all your MAIN pages:
/config.php
<?php
# Create some helpful constants
define('ROOT_DIR',__DIR__);
define('DS',DIRECTORY_SEPARATOR);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
define('BASE_URL','http://www.example.com');
# This includes our function loader (see below)
include_once(FUNCTIONS.DS.'loadFunc.php');
# Load the getSession() function (see below)
loadFunc('getSession');
# Start session here
session_start();
2) Then create some helpful functions (I would learn Object Oriented Programming instead so you can use a framework effectively, but functions are better than nothing):
/functions/loadFunc.php
function loadFunc($name)
{
if(!is_array($name))
$name = array($name);
foreach($name as $func) {
# If the function is already loaded, skip
if(function_exists($func))
continue;
# See if the function file exists
if(is_file($file = FUNCTIONS.DS.$func.'.php'))
include_once($file);
}
}
}
/functions/getSession.php
function getSession($key=false,$clear=false)
{
# If requesting a specific value return that
if(!empty($key)) {
# Get value
$value = (isset($_SESSION[$key]))? $_SESSON[$key] : false;
# If the key is set and clear is set, clear the value
if(isset($_SESSON[$key]) && $clear) {
unset($_SESSON[$key]);
}
# Return session value
return $value;
}
# No key set, return full session
return $_SESSION;
}
/functions/setSession.php
function setSession($key,$value)
{
$_SESSION[$key] = $value;
}
/functions/redirect.php
function redirect($to,$exit=true)
{
header("Location: {$to}");
# You should exit on redirect
if($exit)
exit;
}
3) Now, when you go to create a page, you include this config ONCE at the top of the page:
/students.php
<?php
# Now that you include this, you know session is always set
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Get the key msg from the session and use parameter #2 to clear the session key
$msg = getSession('msg',true);
# It's not empty, write message
if($msg): ?>
<div class="msg">
<?php echo $msg ?>
</div>
<?php endif ?>
/server.php
<?php
# Include config
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Load our two required functions
loadFunc(array('setSession','redirect'));
# You have to determine either message here, not both.
# Using pseudo-code here to demonstrate
if($add) {
# Use function to set session value
setSession('msg',"New student saved");
}
elseif($update) {
setSession('msg',"Information updated");
}
# Since both use the same redirect, you only need it once
redirect('students.php');
So, if you delete all your session_start() in all your files except for the config and then always include the config on the top-level page at the top, you won't run into errors for the session.
This is the code i have at the moment but will not work, displays log out button when logged in only on one page then logs user out automatically ?
<?php
if(!session_is_registered(myusername))
{
echo '<b>Log In</b>';
}
else
{
echo '<b>Log Out</b>';
}
?>
You had forgotten to do session_start() out of many things, and please make sure to share that, on every one of your pages, where you want to enable session protection.
<?php
session_start();
if(!isset($_SESSION['username']) && empty($_SESSION['username']))
{
echo '<b>Log In</b>';
}
else
{
echo '<b>Log Out</b>';
}
?>
session_is_registered is deprecated. Try using $_SESSION instead
if ($_SESSION["isLoggedIn"]) {
// Log out HTML goes here
} else {
// Log in HTML goes here
}
You'll need to include session_start() at the top of all of your files and you can set $_SESSION["isLoggedIn"] just like any other variable: $_SESSION["isLoggedIn"] = TRUE
I get an undefiend variable error when i call another $_SESSION but when i remove this piece of code it shows no errors, I am using $_SESSION in order to pass one variable to another php script, can anyone enlighten me on what may be causing this issue?
I know the variable is defiened but for some reason calling a $_SESSION causes this error?
<div>
<?
if(empty($item_details['trucks'])) {
include_once ('trucks.php');
$_SESSION['runmapapi'] = 'start';
//$runmapapi == true;
echo '<p> Success</p></div>';
} else {
echo '<p>failed</p></div>';
}
?>
<div>
<p>Cars</p>
</div>
</div>
</div></body>
<? } ?>
<? } ?>
<?= $print_footer; ?>
when you are using session variable, you have to initialize the session by using
session_start();
so wherever you use any of the session variable in your page, make sure you first declare the session_start()
so in your page it should be
//initialize session to use session variable
session_start();
include_once ('trucks.php');
$_SESSION['runmapapi'] = 'start';
i am using a session variable to authenticate, acc to my knowledge the session variable is supposed to be stored at the server even when new pages are loaded.
I am using the following code:
<?php
session_start();
echo $_POST['path'];
if($_POST['path']=="index")
{
$_SESSION['rightPath']=1;
if(isset($_SESSION['rightPath']))
echo "it is set";
?>
<script type="text/javascript">parent.location='UI.php'</script>
<?php
}
else
{?>
<script type="text/javascript">parent.location='index.php'</script>
<?php
}
?>
here this isset function tells me that the variable is set but in the next page ui.php is it not giving me the same result.
<?php
if(!isset($_SESSION['rightPath']))
{
echo "it not is set";?>
<?php }
?>
this is the ui.php page snippet. here the if statement is executing.
what am i doing wrong ?
you need to start session here is well
<?php
session_start();
if(!isset($_SESSION['rightPath']))
{
echo "it not is set";?>
<?php }
?>
You are not starting the session in UI.php. The code should be like this, with session_start at the top:
<?php
session_start();
if(!isset($_SESSION['rightPath']))
{
echo "it not is set";?>
}
?>
The session_start() creates a session or resumes the current one. So, while you are creating the session earlier, it is NOT resumed unless you do a session_start() again on every page where you intend to use the session variables.
What is the alternative to the deprecated function session_is_registered() in PHP 5?
Here's my code:
ob_start();
session_start();
if(!session_is_registered(myusername))
{
header("location:main_login.php");
}
ob_flush();
"You need to set and reference $_SESSION variables only." For example:
if( isset($_SESSION[$myusername]) )
From http://www.phpfreaks.com/forums/index.php?topic=263189.0
on a side note, best use $_SESSION['username'] = $myusername;. Using the $_SESSION[$myusername] as a variable may overwrite existing variables in the session.
But if you set anything in the session variable it will display you the protected page:
e.g.,
<?php
session_start();
if(isset($_SESSION[$myusername])){
echo "welcome to protected page.";
}
else {
header('location:login.php');
die;
}
?>
Use session_id()
if (!session_id()) {
// do stuff
}
if there is no session id nothing will be returned. (docs - session_id() )