php session_start with include files - php

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.

Related

How to access a variable from one PHP page to another, without a form, link, or button?

TLDR:- What is a good way to pass contents of a variable from one PHP file to another without involving a form, link or a button.
Question:-
So there is a form in a page/file called question_edit_form.php and its action attribute is already set to another file called question.php. The variable of interest is being read-in from the user in question_edit_form.php and is then obviously being sent to question.php using $_POST.
Now, there is a third file, named renderer.php, and which is not linked to the other two files. I want to use that variable of interest in this file. So how can I access that variable which is set in question.php from inside renderer.php?
first file -
session_start();
$_SESSION['your_variable'] = 'value';
other file -
session_start();
$var = $_SESSION['your_variable'];
this may help.
It sounds like you are using Moodle, in which case renderer.php is not an independent file; it contains the class definition for the renderer object used by question.php.
So... there is no need to pass the parameter between the scripts. If you really must access the form value directly from the renderer, just use the standard methods from the Moodle framework: required_param($name, $type) or optional_param($name, $default, $type).
Generally there are two methods available for you to pass on the value
Cookies
Sessions
How to use cookies:-
setcookie(name, value, expire);
e.g.
setcookie("user", "Alex Porter", time()+3600);
Access it using echo $_COOKIE['user'];
Second is Sessions. Here is how to use sessions:-
session_start();
$_SESSION['varname']=value;
Accessing page:-
session_start();
echo $_SESSION['varname'];
Additional info if required:-
Make sure you use session_start() at top of your page if not you may face with an headers already sent error / warning which again can be fixed by output buffering ob_start()
You can store the variables in the session.
http://www.w3schools.com/php/php_sessions.asp

Trouble with calling session_start() at the start of all PDO pages

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();
?>

php authentication best practice...?

I have a simple login page that checks credentials against database and then every page includes auth.php that verifies $_SESSION['logged'] is set and that session isn't expired.
Problem is that every page also includes another page tab.php (something like a menu), which I also need to restrict access to, but including auth.php inside tab.php makes the inclusion occur twice. If I don't include the auth.php in tab.php, though, anyone can access tab.php directly bypassing authentication check and possibly retrieve private information.
Any best practice to solve this situation?
EDIT:
And I forgot to ask, but what path you use to make it relative to site root? As both auth.php and tab.php are in folder and the index.php which includes tab.php is in root - the include function gives an error for either index.php or tab.php according to what path I use ('./includes/auth.php' OR './auth.php') - If you know what I mean. I tried '/includes/auth.php' but that doesn't work.
Use include_once instead of include in your files (or require_once and require). This will insure that your auth.php file will only be included once in the lifetime of the script.
include_once and require_once will definitely assure that you don't have the same file included more than once (at the same time make sure you're authenticated).
What I would do, however, is add your includes in a "include" folder and forbid access - to people who would type in the path manually - through an htaccess file. This way you could keep your includes in one place (whatever your header includes might look like) and keep your include files clean and still out of reach. If you were to do this you'd only have to do what Jan. mentioned in the answer above and check if your $_SESSION['logged'] is set (and whatever other checks you need)
Just check in tab.php if the session is initialized and $_SESSION['logged'] is true. This will work fine, if auth.php is loaded first.
What about using require_once("auth.php");? This makes sure, that auth.php is included (otherwise application will stop) but only includes the file once which seems to be your goal.
Try include_once(). See ( http://php.net/manual/en/function.include-once.php )

Unable to access session variable in php script called using ajax

Consider the following scenario. I have three php files, file1.php, file2.php and file3.php located on my server.
file1.php starts a session and sets a session variable say,var.
I am able to access var using $_SESSION['var'] in file2.php. file3.php is called using jquery ajax functionality, but im unable to access $_SESSION['var'] in file3.php. if i do a gettype($_SESSION['var']) in file3.php it returns NULL.
What could be the problem here ?
Please help
Thank You
From my tests it should work. What could be happening is if you do not have sessions set to use cookies and they are being appended to the url, you would need to pass the session hash via GET, using the proper name set in the php.ini, to the uploadify script.
But there are a bunch of inconsistencies, especially in that pastie, you do not necessarily have to rename every part of your code, just need to post the relevant sections.

PHP: Sessions across includes

I am needing to use sessions for my php page, so, on my index.php page, I add session_start(); right after the opening php tag.
But, this page has some includes, inside of which have other includes. So, deeper down, when I want to call a $_SESSION var, it is not working.
How can I access a session var even deep down into .inc files?
session_start() works across includes. Your problem must be somewhere else:
#file1.php
var_dump($_SESSION['somevar']);
#base.php
session_start();
include 'file1.php';
//the contents of $_SESSION['somevar'] will be dumped

Categories