Is it not mandatory to use session_start() before using any session variables in PHP?
I tried the following piece of code without declaring session_start() at the beginning, it worked fine.
So, now I'm confused. Please help !!!!
Also, I did not use any $_POST or $_GET to pass $uname to home.php, but still how does it work? If we use include 'home.php' then does it treat login.php and home.php as same page?
// code login.php//
<?
require_once 'db_connect.php';
if (isset($_SESSION ['user_id']) && !empty($_SESSION ['user_id']))
{
$u_name = $_SESSION['user_name'];
include 'home.php';
}
else
{
//some stmt
}
?>
/*******home.php file ****/
<?php
require_once 'dbconnect.php';
$_SESSION['username'] = $u_name;
//echo $_SESSION['username'];
//blah blah
?>
You definitely need it, if session.autostart is not set in php.ini. But you would probably know that then.
Do you not call it in db_connect.php? Also, I'm pretty sure you wouldn't get any errors, the session would just be empty.
If you include a file via php, Session keeps active (as any others variables set too). If you would access this file as new request, you would need to set session_start().
This behaviour is because include and require act like moving the code of the included file into the current one, as you would have typed the code into one single file.
Plus: you don't need to require dbconnect.php twice.
edit: you asked about both files used as the same page - the page is the output given after the whole php code is done. The page itself doesn't care about how many files internally are used for generating it.
Use the session_start () is obligatory for every session in php. Being passed through a variable values is not necessary to make POST or GET the same, since there is already the case the value increment. If not ouver value in the same session is null or blank, if you open the page in the same way the condition is wrong.
(!Isset($_SESSION ['user_id']) &&!Is_Null($_SESSION['user_id']))
isset to check if empty this need! before, IF(!isset($_SESSION['user_id']) and in the second case would be to check if it is not null and void, for a session either exists or does not exist and if a value is set inesistente is null. So correct view is this: is_null($_SESSION ['user_id'])
Importantly, in the login page does not include but redirect to the page. in the case with a header.
Or could do everything in a single page, but it would not be legal to display on a page called login page. The default would be the index, ie if the login stay within a folder, you place it inside the index page and the address of the folder.
The reason for the session can still open is that sometimes the webserver does not realize that erased part of the code and loads of it from the system cache.
Related
I have two php pages for updating account, a frontend and a backend.
Front end (important part):
<?php
session_cache_limiter('none');
session_start(); //session gets started
include_once 'includes/db_connection.php';
include_once 'includes/signin.php'; //file that deals with login and creates the session variables
include_once 'includes/updateaccount_process.php'; //back end file
?>
Back end (important part):
<?php
include_once 'db_connection.php';
include_once 'signin.php';
?>
If I add session_start() to the back-end file I get a notice saying session already started. If I don't add session_start() the rest of the php script doesn't execute properly due to the dependency on the session variable.
If I add if(!isset($_SESSION)) { session_start(); }, it works perfectly, and I don't get any notice but I don't understand why.
Hope someone can help.
Thanks.
While PHP can generate front-end content, PHP resides on the back-end, i.e. you have are two server-side files. If your first PHP file starts a session, as long as your code doesn't destroy or otherwise disable that session, the session should exist as long as your browser stays open. When you go to another PHP page, if you run this code:
(!isset($_SESSION)) { session_start()
it will check to see if it makes sense to start a new session. If the session no longer exists, then a new one gets created. Running session_start() without checking for a previously set session will cause this error message to appear if the session still is in effect:
Notice: A session had already been started
This additional session_start() then should resume the current session.
There might be other reasons for session problems occurring. If you're using PHP5.4 or greater, you can call session_status() and its return value can indicate whether a session has been disabled or if none exists. It can also confirm whether one is currently active (see Manual).
Incidentally, the core contributor who devised session_status() was primarily concerned about providing users a way to check whether currently an active session exists. (see bug report.)
On the page you designate as "back end", I suggest redoing the code as follows:
<?php
if (!isset($_SESSION)) || (session_status() !== PHP_SESSION_ACTIVE) ) {
session_start();
}
include_once('signin.php');
include_once('db_connection.php');
You might consider moving include_once("signin.php") and placing it in the if-conditional block, as a statement following session_start(), as long as the included file only creates session variables and previous code doesn't unset them.
One final point, you may wish to use include() instead of include_once() if both of your pages for a fact only include each file once. Include_once() is slower than include(). You should use include_once only if your script has code that would result in an attempt to include the file more than once in a script (see here).
i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.
The function is called on every possible page, and it's something like main function it checks if user is logedin or not, so it's executed before anything. It just check if user is logedin or have cookie set and if it's logedin or have cookie it starts session and set 2 sessions.
But outputting sessions outside function it outputs that sessions are not set, but shows cookie and session.
To explain a bit more if i echo
$_SESSION['user']
$_SESSION['logedin']
It outputs
Undefined variable: _SESSION
But if i do
print_r($_COOKIE);
It outputs
Array ( [PHPSESSID] => 1rane5lksksp7s4u8p8fh0h194 [user] => fe8dc8f2a7e88746fd8586d489646958 )
Which means that both session and cookie are set
But why it shows me Undefined variable when i request a session and also it logout user after first refresh of website.
Is it because session_start is inside a function, if session_start is called inside a function it is called only when that function meets the criteria of else or if statements inside function, and once session_start is called it is remembered in browser or on every page call you need to use session_start to start a session and than you can use sessions that are set. Because if i put session_start outside function it works flawlessly but session is started even if user is not logedin.
A few things:
1) It's better to use require_once('phpfile.php') than require('phpfile.php'). If you require the same file more than once the script will have a fatal error which stops the script from executing. It does the same, except check if the file is already required before.
2) Does it work when session_start() is outside the function? If that's the case just use that.
3) Are you actually setting the session varibales to something?
$_SESSION['user']; //this wont do anything...
$_SESSION['user'] = $user; //This will assign the session variable
4) If it doesn't work, try to to
function userlogin() {
session_start();
$_SESSION['user'] = $user;
$_SESSION['loggedin'] = true;
session_write_close();
}
session_start();
This enforces that the session variables will be set.
Ok so i got a bit more explanation from the guy who knows php a bit more than me and it seems as a pretty logical explanation.
As you asked from me to post the code it's a quite large and split in few pages but ill try to explain best that i can.
When user goes to my website first page that it's loaded is index.php
In index.php at very first line of code i have code that calls header page.
require('header.php');
And so in header.php file at very first line of code i have code that calls functions page
require('functions.php');
Than in functions file first one is function to check user login.
function userlogin() {
if(isset($_POST['login'])){
session_start();
$_SESSION['user'];
$_SESSION['logedin'];
setcookie(stuff);
and other stuff
}
}
And than at very first line in header.php i call userlogin() function
So by this logic it should be the very first code that it's called to be executed on website. At least what i thought. But it isn't.
Why?
Well the answer i got is because it's not the very first code in the file, it doesn't matter if i count something that it's executed for the user or just server side check. session_start() must be always at the very first line of code. it doesn't matter how many files i require or include if i put something in between or before session_start() it just won't work. So
index.php -----↴
header.php -----↴
functions.php
function userlogin() { line 1
if (isset($_POST['login'])){ line 2
session_start(); line 3
Wont work. In other hand:
index.php -----↴
header.php -----↴
functions.php
session_start(); line 1
This works.
At least that's what i understood from explanation.
Once i logged in i set a session variable inside body element(inside login.php) as below:
session_start();
$_SESSION['Username'] = $_POST["Username"];
if(isset($_SESSION['Username']))
$loginTrue = 1;
else
$loginTrue = 0;
and on top every page i have added this
<?php
session_start(); //this was added after seeing many suggestions in stack overflow that session_start() has to be called at the top on each page. Though i tot calling once was sufficient.
if(isset($_SESSION['Username']))
$loginTrue = 1;
else
$loginTrue = 0;
?>
Now whenever i redirect my page after login from login.php $_SESSION['Username'] gets unset, i dont know how. I redirect using a button click as in
onclick execute window.location = home.php
This is not comman
check your code with this code may be some error is on the page
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
?>
And check your php.ini setting for this.
And check your code with different browser.
And any blank output should be on your page before session start.
alright guys i solved it somehow. I dont know how i did but i did. Firstly i created 4 webpages, a small one just to check the if session variables are supported. Once i confirmed this then i did the below and my original webpage started working session start is very important at top of all pages. Also try session activity in different browsers. Also check by closing dreamweaver. Also make sure is used instead of transitional and stuff and also that session start comes before doctype html declaration
Ok, this is starting to annoy me, as it's quite simply and works elsewhere, but on this current task it doesn't, so here I go!
There is a main page which relies on either a session variable being set or not to display certain information.
Let's say this page is located here: http://dev.example.com/some_page.php
e.g.
if (isset($_SESSION["some_var"])) { /* it's set so do whatever */ }
else { /* not set so do whatever else.. */ }
There is an ajax page triggered by jQuery $.ajax() to call and set this session variable to null to change the action of the main page, let's say it's located here: http://dev.example.com/ajax/some_ajax_page.php
It's code looks like so:
<?php
if (!isset($_SESSION)) session_start();
$_SESSION["some_var"] = null;
When the main page is reloaded after the ajax is triggered, the session var "some_var" is still intact, but if it's echoed after the "null" in the ajax page then it is set to "null".
Basically it doesn't seem to write to the global session, only to the local path.
Does this make sense?
Any help please? Also if you want more clarification with anything let me know!
The session_start() function will handle the attempt to create and persist a session for you, as defined by PHP's configuration, or optionally at runtime if you set your own save handler. Make sure you read the documentation here:
http://us2.php.net/manual/en/function.session-start.php
For your code, you want to make sure to call session_start() at the beginning of any page in which you'd like to save or access session variables. So your page above may look like:
<?php
session_start();
$_SESSION['myvar'] = 'some value';
Then in a different page you can try to access that value:
<?php
session_start();
if ($_SESSION['myvar'] == 'some value') {
// do something
}
That should work fine.
Get rid of the check for session. If this is the only file your calling just do this:
<?php
session_start();
$_SESSION["some_var"] = null;
Also, are you using framework that auto-regenerates session ID on each request? If so, you'll might have problems.
If you have a dev machine to play with and permissions to do so, you can manually delete all sessions in the /var/lib/php/session/ directory. As you use your site, only one session file should be created. You can also inspect that file to see what is getting written and when.
Seems that you are using different sessions vars. One for the AJAX call and another for the normal pages calls. This may occur when you do not init both call in the same way (or using the same starting code that initializes the sessions)
Be sure to session_start() both calls using the same session_id.
// try in both calls
session_start();
echo session_id(); // must return the same id in both calls
Why don't you use unset? It is the proper way to do it.
Turns out the application I was working on had it's own session_handler and if it was not included before requesting the session data, it was always invalid, eventhough it was the same session_id.