Most of my pages use Sessions, but I'm switching to PDO and calling session_start() at the start of every page is causing problems with passing headers. I've done several hours of research and am still unclear what to do about it.
Edit - What I've been doing: The 1rst line of the sign up/sign in documents as well as auth.php is session_start();, and the 1rst line of all pages the user visits subsequent to sign up/sign is require_once('auth.php');
I'm currently passing the user id to every page with $_SESSION['SESS_USER_ID']
When they sign up/sign in I connect it like this:
$member = $stmt_user->fetch();
$_SESSION['SESS_USER_ID'] = $member['user_id'];
And on every subsequent page I call it like this:
$user_id = $_SESSION['SESS_USER_ID'];
As per the manual
As of PHP 4.3.3, calling session_start() after the session was
previously started will result in an error of level E_NOTICE. Also,
the second session start will simply be ignored.
Does this mean that I no longer need to call it on every page and can just call it once when the user commences a session?
If not, what is the simplest way to do deal with this issue?
If you are using a framework, you likely just need to call it once in that framework. If each of your requests go to different php pages, then you need to make sure it gets called at least once per request (preferably as soon as possible).
You need to make yourself a bootstrap file.
A file with all common operations performed on the every page - session start, connect to database, set global variables, etc.
And then include this file into every script called.
So, you'll be sure that you have everything you need, yet called everything once.
Though I don't understand what does this question to do with PDO (as well as a previous one).
PDO is just a database driver and have not a slightest relation to headers, sessions and the like.
You can use ob_start and ob_end_flush to buffer your outputs, so you can actually do this:
<?php
ob_start();
echo '42';
session_start(); // still works because output is buffered
ob_end_flush();
?>
Related
I am working with three PHP files. Two serve as web pages and the other in an external server side script. The server side script is included in both web pages files and what I want to do is have some buttons on the first page and depending on which one is clicked, populate the second page with data and then redirect to it.
With the code below, the idea was to pick up the button click, figure out which button was clicked, and then call the function to run the proper query and set the needed variables. I don't understand why the variable is not getting set.
Thanks to anyone looking at this!
First page's button (index.php):
<input type="submit" id='details' name='details' value='Submit'/>
Second page where variable is undefined when page is loaded:
<h4><?php echo $selected_button; ?></h4>
External script:
function detailBuilder(){
$selected_button = "Option One";
//header('Location: details.php'); if this is here, the page still redirects but the variable doe not get set
//More will happen here once it works
}
if(isset($_POST['details'])){
detailBuilder();
header('Location: details.php');
}
As several people have pointed out previously, you redirect to another file. At that point, all locally defined variables are gone - you no longer have access to them.
Look into PHP sessions in PHP's documentation. Sessions will allow you to transfer these variables from request to request. However, sessions will only work if you are running some form of webserver.
UPDATE: Also to note, as other people (once again) have pointed out, $selected_button = "Option One" will ONLY apply inside the "scope" of the function detailBuilder. So calling detailBuilder() creates a variable called $selected_button inside the function, and then immediately discards it.
UPDATE 2.0: Sorry for so many updates. Here's an example of setting a session:
Update 3.0: updated code slightly
First things first. Make sure you start the session.
session_start();
You're going to have to call session_start() at the start of any php script! That means that the first file that executes every time should have session_start() at the top.
External Script:
$_SESSION["selected_option"] = "Option One";
Script where originally it was undefined:
$selected_details = $_SESSION["selected_option"];
?>
<h4><?=$selected_details?></h4>
I have two shared host.
my problem is realated with calling session_start().
In my localhost and one of my shared host. session start works well with user notice that : cannot call header. then i used to write the below code:
<?php
if(! isset($_SESSION)){
session_start()
}
?>
But in another host, it still echo message that "Notice: cannot start session()..."
also my problem that session doesn't starts in first visit. When I refresh my browser window again then starts session. what is relation between client and server side. again what is wrong with my session_start() ? please help me.
May anyone tell me that what is the proper way to calling a session_start() which will never fail. and where should I call. very top of the page or anywhere in the configuration file. a little example will help me surely.
Two simple things:
1. Always call session_start unconditionally.
2. Always call session_start before you output anything on the page.
So you should do it like this:
<?php
session_start();
// and now anything else
In particular, be aware that you can violate directive #2 in many different ways, e.g. by:
Explicitly printing anything yourself with echo etc.
Having any characters at all in your PHP script before the <?php tag
Inlcuding other scripts that do the above
There are lots and lots of questions here on SO that describe point #2 and how to solve it.
i learned a lot about session start from my previous question. Now i'm wondering how session locking occurs when files are included in other files. Lets say i have:
page.php
include('header.php');
...some html content....
include('sub_page.php');
...more html....
header.php:
session_start();
..save session vars...
..print web page header...
sub_page.php
session_start();
...use session vars....
..print page content...
When i open page.php, does the session become unlocked as soon as header.php is done? or is it live for the whole page.php life, so sub_page's session is blocked? Is the session_start in sub_page necessary? Would it be better practice if I session_write_close every time i'm done with session data? (Though that would mean session_starting everytime i'd like to use a session variable).
You should start session only one time. In your example, just need session_start() at the first line of page.php
session_start() will generate E_NOTICE if session was previously started. You can use #session_start() to ignore it.
It also generates E_NOTICE if you use session_start() after you output HTML code.
I would recommend creating a session.php file that you would include once, at the first line of each page. That way, the session is handled in ONE file, in case you need to change validation or session settings (and don't need to worry about your question).
Due to the answers above talking about errors if session already started, I just wanted to point out you can do:
if (!isset($_SESSION))
{
session_start();
}
Then if the $_SESSION is already started (set) it wont perform the start function.
Although there's nothing better than a well structured file and folder layout with a good framework setup. Even if just a simple framework structure which separates business logic from presentation.
This way, you'd have something similar to a config folder with initialisation scripts, or at the very least have include files in some folder which are included in all pages/scripts.
Then you simply have your session_start() in (depending on your setup) either the very first include file, or in a separate include file and then include that session file when needed in a specific area of the script.
Either way, you then don't need to call it in any other files, as you know it's simply not required based on your design structure.
If you do not have a file which is always included, then at least use the isset() check.
As of PHP 4.3.3, calling session_start() after the session was previously started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.
As long as you are not accessing or creating session variables you do not need to worry about session_start(). You only really need to worry about session_start if the script you are running will create session variables, or relies on accessing session variables to function.
If file1 is not accessing or creating variables for use by other scripts then don't call it. If file2 that is included by file1 is creating or relies on variables in the session then file2 should call session_start(). File2 will be included in the session and will be able to access all session variables, but file1 will not.
If you call session_start() in file1, then file2 will be able to access all session vars as if it called session_start().
Hope this clarifies the situation a bit more.
Great tip from James re using isset. This will prevent attempting a pointless session call.
Also check your php.ini file for the session.auto_start var. If this is set to 1 then all files will be run as if they made a session_start() call. Set it to 0 in the php.ini file if you want to control it yourself.
I am making a simple Dynamic Website using PHP, where i allow the user to login and then access specific pages. So here's what i have done so far.
The logged in values are taken though $_POST variables in a php script where it fetches values from database for registered users. If the user is found i do the following:
session_register('userid');
$_SESSION['userid'] = $username;//this is taken from $_POST
$_SESSION['accesslevel'] = $access;
at the beginning of the php script i have put session_start();
Now here comes my problem.
At every page now i have to check if the user is allowed to view that page or not, if he ain't then he must be redirected to login.php, if he is then the page load must continue.
Now so far what i have learnt is that only way to maintain values across php pages is to use $_SESSION variables, and which ever page i am using Session Variables i must write session_start() on each page as the first line, else i will be getting Headers Already Sent error..
Strangely i exactly have done that but still get erros with the "headers already sent".
SO i want to what is the best way to design a website, where i have to use Session variables across most of the pages, and keep these common checks at a common place..
Can i use include() feature some how?
Are sessions only way to communicate data across php pages.
What is a better way?
I have the following code :
<?php
session_start();
if(!isset($_SESSION['user']))
{
$_SESSION['loc'] = "adminhome.php";
header("location:ettschoollogin.php");
exit();
}
?>
Which resides on top of every page which wants to check if the user has logged in.
And this is teh script to check for login
<?php
session_start();
include("connection.php");
$userid =$_POST['userid'];
$userpwd =$_POST['userpwd'];
$query="Select UNAME,UPASSWORD,SCHOOL,uaccess from schooluser where uname = '$userid'";
$result=mysql_query($query) or die("couldn't execute the query");
$row=mysql_fetch_array($result);
$useraccess = $row["uaccess"];
$school =$row[2];
if(($row[0]==$userid)&&($row[1]==$userpwd))
{
session_register('userid');
$_SESSION['userid']=$userid;
$_SESSION['school']=$school;
if($useraccess =="admin")
{
header("Location:adminhome.php");
}
if($useraccess !="admin")
{
header("Location:school_main.php");
}
}
else
{
header("Location:ettschoollogin.php?err=1");
}
?>
i was aware of the common error of having extra spaces after "?>", BUT I STILL GET IT.
Thanks guys, i missed out and the "connection.php" file actually had extra spaces after "?>" i had removed it before, but some how the file got rewritten again.Thanks a lot.
Yes, you can use include. Put all your common functions in a separate php file and "include" it at the top of each file.
You can use cookies to store information (typically just an id that you use to look up additional information in the PHP page). Normally, PHP sessions are handled using cookies though. See setcookie in the docs.
You are probably getting the error messages due to stray characters outside of a <?php ?> block. A common error is to have an extra blank line at the end of an include file, after the ?>. That blank line will be output and your headers will have been sent. If that isn't the problem, you will just need to make sure you move the session related code above any code that might generate some output (eg by using print or echo).
•Can i use include() feature some how?
Yes. You can do whatever you want before your session_start() call, only, you must not have outputted anything, not even a single space or character. Probably you have already outputted something, maybe on an automatic inclusion or apache prepend.
•Are sessions only way to communicate data across php pages.
•What is a better way?
Other ways are cookies, post and get parameters. But sessions are the only way to securely pass data among pages without sending them to the client and back (which may pose security risks)
Write ob_start(); at the top of your code and then you dont get the error of "headers already send"
It seems that a static variable declared in a function is re-initiated whenever the function is called, how can I use the function in a way that re-calling the function will re-use the static parameter?
I defined the function 'testStatic' in static.php
here is static.php:
<?php
function testStatic()
{
static $staticV = 0;
echo $staticV;
$staticV;
}
?>
I am calling 'testStatic' from index.php
here is index.php:
<?php include "./static.php";?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3c.org/TR/html4/strict.dtd">
<?php
testStatic();
?>
<html>
.
.
.
<html>
When index.php is executed for the first time testStatic will echo with '0' however in the next times index.php is executed testStatic continues to echo with '0'.
It seems that the static variable 'staticV' of 'testStatic' is re-initiated whenever index.php is execute.
please advise.
that index.php
Every time you execute a PHP script, the environment is re-created. There is no state between HTTP requests or script calls.
The first time you point your web browser at index.php, a new PHP environment is initialized, and $staticV becomes 0.
The next time you point your web browser at index.php, the exact same thing happens.
If you want to persist $staticV between web requests, then you need a different approach. Sessions are often used to handle this problem.
HTTP is a stateless protocol, so no state is maintained on each call to a web page. The variable will be static, only for the duration of the PHP processing of index.php, the next time you load index.php it will not have remembered any state from the previous time you ran index.php, including the static variable.
To do that you will need to use some method of data persistence. Store the variable in a file, a database, as a session variable, etc. Storing it in a session is probably the best option here. There's a tutorial on sessions if you need it.
A quick example,
<?php
session_start();
if(isset($_SESSION['staticV']))
$_SESSION['staticV']++;
else
$_SESSION['staticV'] = 0;
echo $_SESSION['staticV'];
?>
you are confusing things. static variable stays static within (!) the script execution. once the script finished, php engine doesn't know anything about the variables or the script...
you should use cookies or database (or php session options) to keep values during session.
hmmmm variables in php are volatile in what concerns different calls. every time you start a php-script, the variables are reset. if you want persistence over multiple calls, you need to use a persistent storage like a file or a database. sessions / cookies are a way, too.
regards
This occurs because every time the page executes all old information (other than what is stored in superglobals like $_SESSION) are reset. This includes the function, which gets defined anew every time. The code you are using would do what you expected if you were to execute it multiple times in the generation of that page. Separate page loads can essentially be considered separate instantiations of the program, so you would need to use an alternative location to store the information. DB, text file, a superglobal... Choose one that suits your purpose and use that for the information.
Be aware that if you want this number to be in sequence not for a particular user, but for all users, you will have to do extra work to handle synchronization.