PHP Session is being created for every page - php

So problem is as the title says php session is being created for every page. So when I want to get a variable from session like this
session_start();
echo $_SESSION['error'];
It says "undefined index".
The problem is, in fact 'error' index defined but not in the current session since php creates new session for every page.
How can I solve this?
Note: I put session_start(); to every pages' first line, and before header("location:error.php") I put session_write_close(); and after the header there is die(); method too. I'm working on localhost. Using Latest version of WAMP and JETBRAINS PHPSTORM.
EDIT---------------------
This is where I define my session for error(this is from login.php page)
session_start();
$_SESSION['error'] = "Enter both username and password";
header('Location:error.php');
exit;
When the code above run, a session named "sess_amvrseubtusk0dpuo4fs35r0q1" is created and it has this line in it
error|s:32:"Enter both username and password";
And this is where I want to read session (this is from error.php page)
session_start();
echo 'SESSION: ' . $_SESSION['error'];
When the code above run, a session named "sess_m08lf25stbhg75gj2h0n0vose0" is created and it is empty.
I have all two of the created session files in my Session directory so 1 session file for each page.
EDIT 2----------------------------------
Here my php.ini file
http://pastebin.com/JNsPdzjH
EDIT 3----------------------------------
New php.ini file with changes "c:/wamp/tmp" to "C:/Users/nerzid/PhpstormProjects/Deneme/Session"
http://pastebin.com/Zaz37UPC

This posted as per your originally posted question should people wonder.
You may not have defined anything to $_SESSION['error'], least not with what you posted for code:
session_start();
echo $_SESSION['error'];
You would first need to assign something to it.
For example:
session_start();
$_SESSION['error'] = "Error.";
echo $_SESSION['error'];
Then on subsequent pages, you check if the session is set => isset() and/or empty => empty() or not.
I.e.:
if(isset($_SESSION['error']) && !empty($_SESSION['error'])){
echo $_SESSION['error'];
}
else{
echo "Session is not set";
// set a new one
}
If session is set from a variable example:
session_start();
$_SESSION['error'] = "Error.";
$error_x = $_SESSION['error'];
echo $error_x;
Also, when using header, add exit;
header("location:error.php")
exit;
always.
Sidenote:
Since you're working off of localhost, make sure the folder is writeable.

Related

PHP session variable set on page (verified) does not exist after redirect or page change

PHP 7.1.7 on Windows Server 2008 Enterprise
... I noticed there were 5 other questions here just like this with no answer. I'm getting frustrated trying to do something that's always been so easy to accomplish in other languages for me. I just want to set a session variable and then read it on another page after a redirect. That should be simple basic functionality and I do not get why I've been sitting here for 2 hours trying everything I can think of and I still can't figure it out.
Each page of my application starts with: session_start();
I have a form edit processing page I'm starting with, where on a successful edit, the user is redirected back to the index page. Before the redirect, I'm setting a session variable ('success'). At this point, the session variable is set. If I comment out the header and exit() lines and echo the session["success"] variable.
$_SESSION["success"] = "The record was inserted successfully.";
header( 'Location: index.php');
exit();
}
Register Globals does not exist in my PHP.ini file (register_globals). I tried adding "register_globals=0;" to the PHP.ini file and restarting the server but I still doid not see a "register_globals" listing on the PHP info page.
No matter what I have tried, after the redirect to the index.php page, that session variable does not exist after the redirect ($_SESSION["success"]). I'm staying inside the same domain (same folder on the server really)
After setting the session variable ('success') and proving that it is set by echoing it on the edit proccessing page followed by an exit, I can not figure out how to get the session variable to persist after a redirect or page change:
If I try and echo that 'success' session variable after a redirect, I get this:
Notice: Undefined index: success
I'm not understanding why this is so difficult? What else could I try?
Thanks for any help.
Test whether the session cookie is set properly.
$_SESSION["success"] = "The record was inserted successfully.";
// header( 'Location: index.php');
echo session_name() .': '.session_id(); // print session cookie name & value
echo '<pre>' . print_r(session_get_cookie_params() ) . '</pre>';
exit();
What do you see? Open your browser's dev tools and look at cookies set when the server echoes the info above. If there is no cookie with the name (typically PHPSESSID) and session ID value above, then either your browser is not accepting cookies or the server isn't setting them. Either one will break cookie-based sessions.
If these seem to work ok, then re-establish your redirect. On the next page (index.php in your example), take a look at which cookies are received:
// Notice: this won't work on the page setting the cookie.
// Cookie should show up on the next page
echo '<pre>' . print_r($_COOKIE) . '</pre>';
Does the session id cookie exist?
If all this works, I would then look at whether PHP is actually storing session files properly. Session data is serialized and saved to files in a folder on the server's hard drive. Take a look at your php.ini, where you should see something like:
session.save_handler = files
session.use_cookies = 1
; where on server the files should be stored. the folder should be
; readable/writeable to the PHP process. Maybe '/tmp'?
session.save_path =
If you edit your php.ini, remember to restart the server.
Update
From your comments, everything seems to be setup correctly. Remove all other code. and just have this:
page1.php
<?php
session_start();
$_SESSION = []; //start with an empty array
$_SESSION['success']= 'record saved';
$_SESSION['id'] = session_id();
header('Location: index.php');
exit;
index.php
<?php
session_start();
var_dump($_SESSION);
if(isset($_SESSION, $_SESSION['id'])):
echo 'Session ids ' . ($_SESSION['id']===session_id()? 'match' : 'do not match');
endif;
What gets var-dumped in index.php after you get redirected from page1.php?

PHP Sessions issue - Sessions won't initialize?

So, I'm using a simple login-script for a few pages, using sessions to identify the user, by putting the users name in a $_SESSION variable and then checking if the variable is set on each page. This worked fine when I ran the script locally through a WAMP-server - but when I uploaded it to a webhotel I ran into a weird issue.
The login-script, which sets the $_SESSION variable if the username and password matches up with information from a MySQL-database, somehow won't start the session. I have session_start(); at the top of every page, including the login-script, so I don't understand why it wont start.
Now, I found a script on here that is used to check for session-support:
<?php
// Start Session
session_start();
// Show banner
echo '<b>Session Support Checker</b><hr />';
// Check if the page has been reloaded
if(!isset($_GET['reload']) OR $_GET['reload'] != 'true') {
// Set the message
$_SESSION['MESSAGE'] = 'Session support enabled!<br />';
// Give user link to check
echo 'Click HERE to check for PHP Session Support.<br />';
}
else {
// Check if the message has been carried on in the reload
if(isset($_SESSION['MESSAGE'])) {
echo $_SESSION['MESSAGE'];
}
else {
echo 'Sorry, it appears session support is not enabled, or you PHP version is to old. Click HERE to go back.<br />';
}
}
?>
The really weird thing is that this script tells me that session-support is enabled - and after running it, it suddenly works across all the pages.
So I have to run this script (in its own file) every time I access the site, because the login-script won't set the $_SESSION variable without running this script first.
JUST TO MAKE SURE: I am NOT asking how to check if session-support is enabled or not; the issue is why sessions are not enabled untill AFTER I run the script above.
Why is this happening, and how do I fix it?
Session is automatically started when session_start() function runs. To check if a session is set, you do not need that long code. Try this.
if(session_start())
{
echo session_id();
}
If session is started, session id will be printed. Else, it won't.

Session variable clears itself (PHP)

As a part of a very simple login script, I create a session variable (or at least that is what I think it's called) with the username, and use that as a check of whether or not a user is logged in. The variable is set in the login script, using the following code:
if($count==1) {
session_start();
$_SESSION['ed_user'] = $ed_user;
header("location:main.php");
} else {
echo "Incorrect user or password, please try again.";
}
I know that the first part of this if-statement is run, since I am not presented with the error message. On the page it directs to (main.php) the first lines of code should check if $_SESSION['ed_user'] is set, and return to index.php, if this is not the case. This is done with the code:
if(!$_SESSION['ed_user']){
header("location:index.php");
}
However, it seems to always return me to index.php after login. I have tried to check if the variable exists, using the following line:
<p><?php echo"Current user: ".$_SESSION['ed_user'];?></p>
Which indicates that the variable is empty. What am I doing wrong here?
You need to call
session_start();
On every page.
On your main.php file...
session_start();
if(!isset($_SESSION['ed_user'])){
header("location:index.php");
}
You need to call session_start() to access session variables.

php sessions not working correctly

Hello i am having problems holding sessions from page to page, code worked on my previous servers running php5 but not on my recent server, i am wondering whether its a bug?
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
ANy ideas? session is held on first page but not on the second.
In case you missed it, make sure you do a session_start() at every page you're using the $_SESSION variable.
You should check your php.ini file and see what's going on.
Make sure session.use_cookies = 1 and session.save_handler = files.
Use this test page to see whether it's a general PHP problem or just your code.
<?php
session_start();
if(isset($_SESSION)){
echo "Session variable exists<br/>";
if(!isset($_SESSION['test'])){
$_SESSION['test'] = "Success!";
echo "Variable has been set, refresh the page and see if stored it properly.";
}else{
echo $_SESSION['test'];
}
}else{
echo "No session variable has been created.";
}
?>
If that worked, then it's got to do with your code.
If you're setting your session variable to $_POST['session'] am I to assume you submitted a form with an input with the name session?
This setup should work.
index.php
<form action='page0.php' method='POST'>
<input type='hidden' name='session' value='SPAAAAACE' />
<input type='submit' />
</form>
Page0.php
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
Page1.php
<?php
session_start();
echo "Good morning" . $_SESSION['session'];
?>
For completeness and debugging purposes
In case you are using cookie-less sessions, you have to manually add the SID (session id) to the header redirect like this
header("location: www.mysite.com/page.php?".htmlspecialchars(SID));
If the problem still persists, it could be a permission issue.
Maybe you're not allowed to read the session file stored on the server?
Update: OP commented that it was a permission issue and the problem is now resolved
Turn on error reporting temperately with:
error_reporting(E_ALL) This may spit out an error related to your problem. Most likely an undefined index session notice.
You should always have a check in place on Super Globals.
<?php
session_start();
$_SESSION['session'] = (isset($_POST['session']))?$_POST['session']:null;
header("Location: www.mysite.com/page1.php");
die;
?>
Your code seems correct though I'm pretty sure $_POST['session'] is empty.
You should try this :
<?php
session_start();
$_SESSION['session'] = 'John Doe';
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
To see if this works or not. I guess it will.
IF not, take a look at your cookies, maybe they are disabled.
Then, if it works, I probably because $_POST['session'] is null or empty, are you sure you posted something like <input type="text" name="session" /> ?
You need to pass the session id with the redirect.
Also make sure you use session_start() at the top of EVERY page that needs a session
First try using
<?php session_start();
instead of
<?php
session_start();
If the problem still exists, then open your script in Netbeans editor and see whether any unexpected characters found at very beginning of the the script.
In addition, please make sure that $_POST['session'] has a value to assign in $_SESSION['session'].
You will have to call
session_start();
on the first line of every page you want to retain the session in

PHP Session not Saving

I have this written at the very first line on every page of my website.
include("restd.php");
and restd.php contains the following lines :
#session_start();
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
The problem i'm facing is that when ever i click or do something on my website. it logs me out and takes me to index.php.
im sure its something to do with the session. ive tried every single thing to avoid this problem but i ahve used restd.php because i dont want anyone to copy the url of someone and paste and get into the website.
anyone who is logged in only can view other's pages. if they arent logged in then they'll be redirected to index.php
EDIT : and guys a confusing thing is that all this is working fine on my testing server which is easyPHP-5.3.8.0 but this problem is coming up when i upload all the files to my server.
Your session directory (probably /tmp/) is not writable.
Check with session_save_path() if it is writable.
if (!is_writable(session_save_path())) {
echo 'Session path "'.session_save_path().'" is not writable for PHP!';
}
Do you actually set $_SESSION['id'] on a page...
What you are trying to do here is:
Start a session and load the $_SESSION from the session handler
Check if $_SESSION contains key 'id'
Redirect to index.php if $_SESSION['id'] is not set
Do you actually do this in index.php?
session_start();
$_SESSION['id'] = something;
you need declare $_SESSION['id'] :
file1.php
session_start();
$_SESSION['id'] = '123'
file2.php
include 'file1.php'
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
In my case I forgot that I had the PHP flag session.cookie_secure set to on, while the development environment was not TLS-secured.
More information about Session/Cookie parameters.
I know this is an old thread, but the following helped me with the same problem after hours of despair. Found on: http://php.net/manual/de/function.session-save-path.php
I made a folder next to the public html folder and placed these lines at the very first point in index.php
Location of session folder:
/domains/account/session
location of index.php
/domains/account/public_html/index.php
What I placed in index.php at line 0:
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
?>
Hopefully this will save you time.
Check maybe your session path does not exist
so you can save PHP session path using:
ini_set(' session.save_path','SOME WRITABLE PATH');
Couple things:
your include file doesn't have the <?php ?> tags, so the content will not be evaluated as PHP
Session_start must be called before you start outputting anything. Is that the case?
You still don't even answer where you SET $_SESSION['id']. $pid = $_SESSION['id'] does not set the session variable. session_start() comes before ANYTHING session related, it's not shown before your include.
I had the same problem and found a work-around for it. If anybody can explain why the session is not read even when the cookie is there, please let me know.
<?php
// logged.php
// The PHP session system will figure out whether to use cookies or URLs to pass the SID
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) && authenticationRoutine(/* Returns true if succesfully authenticated */) ) {
session_id(uniqid("User--"));
session_start();
$_SESSION['id']=session_id();
}
?>
<?php
// Insecure restd.php (The user can forge a stolen SID cookie or URL GET request, but that is inherent with PHP sessions)
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) {header('Location: index.php')}
?>
.
[EDIT]
Even though the cookie was there and I prevented starting a new session, the session had not been read and started, so no session variables were available. In this case I check if the session has been started first (not using session_status() because it doesn't exist in PHP 3.5, which for some reason is the most widespread among hosts). If no session has been started within PHP, I check if it had been started before by testing the cookies and GET variables. If a session ID was found, the script resumes the session with that ID. If no ID is available, the user gets redirected to the index.
<?php
// restd.php
if(empty(session_id())) {
if(isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) {session_id($_COOKIE['PHPSESSID']);}
elseif(isset($_GET['PHPSESSID']) && !empty($_GET['PHPSESSID'])) {session_id($_GET['PHPSESSID']);}
else {header('Location: index.php'); exit(0);}
session_start();
}

Categories