I am beginning to learn php. I have a question regarding sessions.
Right now, I know that session_start() creates a session variable.
What I don't know is, when I access the session I created, do I need to use session_start() again?
If yes...
Why is this? Because I already created a session and I wonder why it wouldn't last the entire browsing session.
because what i understand from it is, that it is going to create a new session.
No:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
http://php.net/session_start
Each new page you visit is an entirely new context for PHP. session_start allows you to reestablish a previous context/session/data.
The session_start function tells PHP to enable session tracking. It doesn't wipe out the session created by a previous page. You must call session_start() before you'll have access to any variables in $_SESSION.
Because of the manual session_start()
session_start — Start new or resume existing session
the same way you would connect to database every time you want to use it. it will connect to however you're storing your sessions. The session variables are no wiped out.
Also read more here but this should help to understand how sessions work:
When you are working with an application, you open it, do some changes
and then you close it. This is much like a Session. The computer knows
who you are. It knows when you start the application and when you end.
But on the internet there is one problem: the web server does not know
who you are and what you do because the HTTP address doesn't maintain
state.
A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping
items, etc). However, session information is temporary and will be
deleted after the user has left the website. If you need a permanent
storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or
is propagated in the URL.
Session data is stored at the Server side but the reference or id to the session is stored on the client's browser cookie. For the server to know your session id we make a call to session_start() on each page it is required (at the top) so that the first thing done is to get the id from the user and retrieve the session data. It is required on every page whenever you want to access session data.
Here is a video tutorial also. http://blip.tv/step4wd/php-sessions_en-5983086
The answer is yes. You have to do that on every page. If you don't do that you get a undefined index error.
This will work because we include the file
Index.php
<?php
session_start();
//file doesn't have session_start
include "file.php";
?>
No: it is NOT always going to create a new session. It only tells the script that this page wants to start OR maintain an existing session.
A session is nothing more that a STATE AT THE SERVER that you carry from from page to page.
It is NOT accessible from the client (browser).
The only thing the browser must do to keep the session is passing an ID (called default PHPSESSID in PHP).
This ID can be stored in a cookie, GET or POST, as long as you get it transfered to the server with each request you make.
Youve to use session_start(), everywhere you need to work with session like, creating, accessing, destroying.
Unlike cookies, you can't access or work with session unless you initiate the session.
Related
Does it start a current session based on cookies? Got that from the PHP website. How does PHP control the session? If I start a session when a user opens up my login page, what do I even use that session for? Can I use the current session to get info about the logged in user?
The PHP session system lets you store securely data in the $_SESSION global array. A typical example is to store the user's identifier in the session when they type in their password:
if ($user = try_login($login, $password))
$_SESSION['user'] = $user;
Then, you can access that information on all other pages:
if (isset($_SESSION['user']))
// logged in !
echo user_name($_SESSION['user']);
The data is stored on the server, so there is no risk of tampering (on the other hand, mind your disk usage).
Starting the session lets the current request use $_SESSION. If this is the user's first visit, the array will be empty and a new session cookie will be sent for you.
Closing the session merely prevents the current request from using $_SESSION, but the data stays around for the next requests.
Destroying the session throws away all the data, forever. The sessions are destroyed a certain duration after the last visit (usually around 30 minutes).
I assume you want to know what a PHP session means for you, the programmer.
When you do session_start() you are telling PHP that you want to use the session. This is made available to you as an array called $_SESSION. You can use that like any other array with the difference that the stuff you put in there stays there from one page to another (provided you use session_start() at the beginning of each page).
The actual mechanism may vary depending on configuration (php.ini), but a typical installation can use cookies for the session. Let's assume that your webserver is on linux and you're using cookies. You do the following
session_start();
$_SESSION['name']='Bob';
When PHP sees this it creates a text file with a semi-random name (for example sess_a3tfkd5558kf5rlm44i538fj07), sticks the $_SESSION contents in there as plain text and then sends a cookie to the user with the session id, which can be used to find the session file (for example a3tfkd5558kf5rlm44i538fj07).
The next time the user comes back he hands in the session id in his cookie, PHP goes to the relevant file and loads its contents in $_SESSION.
You'll note that the actual information is kept on the server while the user is only given an id. Kinda like handing in your coat in a club and getting a ticket with a number on it.
PHP's session_start starts OR resumes an HTTP session, which is explained fairly well in this article:
http://en.wikipedia.org/wiki/Session_(computer_science)
The concept of an HTTP "session" isn't specific to PHP, it's used in many (all?) server side HTTP frameworks as one way to allow for some state to be stored/associated across different request/responses (since HTTP is stateless). A unique token (which is often, but not always, stored in a cookie) identifies a particular client, and the server can associate the "session."
Here's some more info about sessions and PHP in particular that may help: http://www.php.net/manual/en/book.session.php
Like it says in the Manual
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
If you start a new session at your login page, the session is initially empty. You can store in it whatever you want, for instance, store the user id once the user has logged in. The session data is destroyed when you close the session.
You might want to read all chapters in the Session Extension Manual Pages and also see
what is session and cookies in php and where it stored
You can compare PHP session with the cookie, but session is the much more secure way of storing information. Cookie store data on user's computer, but session store on the server in a temporary file securely.
I have discussed session and how to use it on one of my blog post - How to start a PHP session, store and accessing Session data?
Below is an example code of storing data in PHP session:
<?php
session_start();
$_SESSION["name"] = "John";
?>
Below is the example of retriving the session data:
<?php
session_start();
echo $_SESSION["name"];
?>
The above code will display the name "John".
Source: How to start a PHP session, store and accessing Session data?
Or in PHP in general. I need to check if a user is logged in when accessing a certain page. Tutorials recommend using sessions e.g
$sessionData = array('username'=>$username, 'status'=>1);
$this->session->set_userdata($sessionData);
And for better security they recommend using a db table.
What if I just store username and status in a database and then change status to 0 when people log out?
Whenever they need access to a certain page I just check if the status 1.
When you call session_start() PHP sets a cookie in the user's browser with a randomly-generated ID.
From then on in that file anytime you store a value in $_SESSION will [by default] be stored in a file in session.save_path at the end of the script. This file is identified by the session ID.
On subsequent requests the client sends their session ID cookie back to the server, so when you call session_start() in your script PHP can go and retrieve that session file and restore the contents to $_SESSION.
Literally anything you will write will simply be re-implementing this already-written behaviour, but without the added layers of security contributed over the years to the PHP project.
I'm going to use cookies and sessions to indentify the user. So, sessions will be used only when user chose the 'Don't remeber me' option.
I include the identification file in the top of every page of website.
User's session looks like $_SESSION['user']
And than is my question:
Must I place to the authentication file session_start() instruction? I asked it because new session creates every time I use this instruction.
Update
http://pastebin.com/Nh3zj6mR user identification script
Yes, you have to place session_start() at top of every php page (before any output was generated, no headers must have sent before) to tell php to accept / start session, expect your php.ini is setup, that sessions start automatic.
I asked it because new session creates every time I use this instruction.<<
That is a hint, that your browser ignore (disallow) session cookies
Unless you execute session_start(), PHP's session mechanism will NOT activate. The $_SESSION will be present, you'll be able to read/modify it, but its values will NOT be persisted - e.g... the contents will be lost when the script exits.
If you are running session_start() in every script that uses session data, but the session data is not showing up, then there's probably a misconfiguration causing the session cookie to be lost, and PHP is creating a new session each time.
Related
Sessions - Sessions and Statefullness
Sessions - Sessions are Stateful, PHP user code is not
Sessions - Where to use session_start()
Sessions - Statefullness and Runs
Sessions - vs. Mysql
PHP.net
session_start()
session_id()
session_destroy()
Specefic Two ID issue
Sessions - extra ID created
Sessions - extra ID created - Cookie Location
How can I determine what is the mechanism which causes session_start to create new sessions wrather than resume a previous one?
This is visible in the PHP sourcecode for the session_start function. You need to read the C-code and compare with your usage.
From what I know about sessions, session_start won't start a new session if already one is active. To find out if a session is already active, please see How to tell if a session is active?.
However if a session is started (and it didn't existed earlier) and then closed and you create a new session in the same request, PHP might think that the session does not exists (because the cookie from the browser is still empty). So then a second, also new, session will be started.
If you're unsure what does what, just create yourself a test script where you play around with scenarios.
A possible scenario:
Browser sends request
PHP starts
session_start() is called. No session cookie exists, PHP will create a new session id and will create cookie headers.
you close the session.
session_start() is called. No session cookie exists (in the request), PHP will create a new session id and will create cookie headers.
Two sessions have been created of which one will not be used by the browser for subsequent requests (the session id header for the cookie has been "overwritten" (the last cookie header replaces previous ones for the cookie in question).
To debug things, headers_list can be useful as well as $_COOKIES.
Let me explain how a session work, PHP saves the variables somewhere on the server side (doesn't matter where for the sake of this explanation), and assosiates it with a unique id (i.e. the Session ID), it then gives the session ID to the user in one of two ways:
Via a GET variable in the url (example.com/index.php?sid=acd6e41ac5ae1dc6ae15dec56)
Via a Cookie sent in the headers.
In the next request, PHP will expect to recieve that ID (in one of the two ways mentioned above), and match that against the list of session IDs it has on the server side. Once a match is found, PHP will load the session environment (accessed by the author using the $_SESSION super global).
You describe a problem where PHP does not find a match, and generates a new session ID instead of continuing with an existing one. This means, probably, that there is a problem in the way the client sends the session ID to the server.
That would mean one of two problems:
User has accessed the site without the GET variable that includes the session id: (example.com instead of example.com/index.php?sid=acd6e41ac5ae1dc6ae15dec56).
User has no enabled cookies or has deleted his cookies in between his session.
Check for these two, it is not likely to be a problem in the PHP engine.
Under php.net session_id()
In php version 5.3.2 in my case each time a new session-id was
generated after session_start() but all was working before correctly
in previous versions. So I lost data from my current session (wrong
session-id). There was always a $_POST or $_GET or $_COOKIE available
with the session-name and session-id, so session_start() was taken
this automatically. Now I have to execute session_id(..old id ..)
before session_start() and a session is started for the same id.
Does it start a current session based on cookies? Got that from the PHP website. How does PHP control the session? If I start a session when a user opens up my login page, what do I even use that session for? Can I use the current session to get info about the logged in user?
The PHP session system lets you store securely data in the $_SESSION global array. A typical example is to store the user's identifier in the session when they type in their password:
if ($user = try_login($login, $password))
$_SESSION['user'] = $user;
Then, you can access that information on all other pages:
if (isset($_SESSION['user']))
// logged in !
echo user_name($_SESSION['user']);
The data is stored on the server, so there is no risk of tampering (on the other hand, mind your disk usage).
Starting the session lets the current request use $_SESSION. If this is the user's first visit, the array will be empty and a new session cookie will be sent for you.
Closing the session merely prevents the current request from using $_SESSION, but the data stays around for the next requests.
Destroying the session throws away all the data, forever. The sessions are destroyed a certain duration after the last visit (usually around 30 minutes).
I assume you want to know what a PHP session means for you, the programmer.
When you do session_start() you are telling PHP that you want to use the session. This is made available to you as an array called $_SESSION. You can use that like any other array with the difference that the stuff you put in there stays there from one page to another (provided you use session_start() at the beginning of each page).
The actual mechanism may vary depending on configuration (php.ini), but a typical installation can use cookies for the session. Let's assume that your webserver is on linux and you're using cookies. You do the following
session_start();
$_SESSION['name']='Bob';
When PHP sees this it creates a text file with a semi-random name (for example sess_a3tfkd5558kf5rlm44i538fj07), sticks the $_SESSION contents in there as plain text and then sends a cookie to the user with the session id, which can be used to find the session file (for example a3tfkd5558kf5rlm44i538fj07).
The next time the user comes back he hands in the session id in his cookie, PHP goes to the relevant file and loads its contents in $_SESSION.
You'll note that the actual information is kept on the server while the user is only given an id. Kinda like handing in your coat in a club and getting a ticket with a number on it.
PHP's session_start starts OR resumes an HTTP session, which is explained fairly well in this article:
http://en.wikipedia.org/wiki/Session_(computer_science)
The concept of an HTTP "session" isn't specific to PHP, it's used in many (all?) server side HTTP frameworks as one way to allow for some state to be stored/associated across different request/responses (since HTTP is stateless). A unique token (which is often, but not always, stored in a cookie) identifies a particular client, and the server can associate the "session."
Here's some more info about sessions and PHP in particular that may help: http://www.php.net/manual/en/book.session.php
Like it says in the Manual
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
If you start a new session at your login page, the session is initially empty. You can store in it whatever you want, for instance, store the user id once the user has logged in. The session data is destroyed when you close the session.
You might want to read all chapters in the Session Extension Manual Pages and also see
what is session and cookies in php and where it stored
You can compare PHP session with the cookie, but session is the much more secure way of storing information. Cookie store data on user's computer, but session store on the server in a temporary file securely.
I have discussed session and how to use it on one of my blog post - How to start a PHP session, store and accessing Session data?
Below is an example code of storing data in PHP session:
<?php
session_start();
$_SESSION["name"] = "John";
?>
Below is the example of retriving the session data:
<?php
session_start();
echo $_SESSION["name"];
?>
The above code will display the name "John".
Source: How to start a PHP session, store and accessing Session data?