is a PHP session automatically created for all visits - php

When a visitor or a search bot is visiting my website.
Does PHP automatically create a session? if so. where is it stored and how can I see it, and what kind of information is stored about the session...
Thanks!

Sessions are not automatically created for visitors or bots. A session must be started using the
session_start() call (http://php.net/manual/en/session.examples.basic.php).
PHP sessions save session files at some path on the server by default, this path is specified by session.save_path. To set or get session variables, use PHP's $_SESSION superglobal. php.net has great examples of gettting started with using sessions.

This is answered in Sessions Introduction
When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

Related

Do I need to use sessions in Codeigniter?

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.

php PHPSESSID exists but session destroyed

I am trying to login an user for 2 weeks if user login with remember me check then i have set some variables in session and cookie set for 2 weeks. It is set correctly i have printed it and got the value session_cookie_lifetime = 1209600 and session_gc_maxlifetime = 1209600. I also print session and got correct value in $_SESSION.
After login in my site when i shut down my computer and reopen my site it seems that it is working (it is keeping me as login user). But when i shut down my computer and next day when i open my browser it is not working and it is showing that i am not login on my site. I have printed $_COOKIE and $_session . It shows that in cookie there is :
[PHPSESSID] => svikos35bgclmebk2cqraiddt2
But session is empty.
I got this form modx stuff:
MODx automatically starts and ends sessions with each request made to the site. You can simply save values into the $_SESSION array and they will be saved in between requests so you can use them on subsequent pages (so long as you have the same user session). Not really any magic to it other than don’t call the session functions yourself to start, end, or otherwise manipulate the session configuration—that can all be done via settings in MODx.
I am using modx revo. It is a bit descriptive question. let me know you need something else.
Anything that may help me (blog link,any settings, any suggestion ) will be highly appreciated.
Thanks in advance
This only happens after a day?
Could tmpwatch be deleting session files from the server?
session_cookie_lifetime and session_gc_maxlifetime doesn't garantee you, that session will be saved for a week. GC kill unused sessions. Check PHP documentation about this parameters and you see, that you can't be sure, that your session will be on the server and you don't be sure, that your sesssion will be destroed after this time. GC is async.
You need to recreate $_SESSION after login (and autologin) if it doesn't exists.
Check this article (in russian, try google translate:
PHP GC: unexpected behavior
The basic idea behind SESSION is that, When you create or call session_start() method your server generate a session id and store it on server memory. Also the server create a cookie on your client machine that cookie contains an id that is related to your server side session id. When you call session_destroy() method server delete that id on server side but the client side cookie doesn't. That is why your session id still shown. You can also check by cache and cookie clearing. When you clear cookie your session will destroyed.

PHP Sessions with disabled cookies, does it work?

Today I had skype interview for a job as PHP developer, one of the questions asked was about Cookies and PHP Sessions.
The question was, can PHP session be set and read, used, if Cookies are disabled in users Browser?
I told them not, beacuse PHP Sessions by default depends on setting a session cookie. When PHP session starts, new session Cookie is set with default name PHPSESSID, and that cookie holds value of that session id, for example: ftu63d8al491s5gatuobj39gk7
Then on apache server in tmp folder file sess_ftu63d8al491s5gatuobj39gk7 is created and it holds content of that session, for example: test1|s:12:"SessionTest1";test2|s:12:"SessionTest2";
They told me that's not true, and that you can use PHP Sessions even if user disables cookies in his browser.
Then I told them that you can do that, but then session id would be passed through URL as GET variable. And that's not secure and you must set it up in php.ini.
They were talking how you can use PHP Sessions even if Cookies are disabled in browser. And what if we are building web shop, and some granny uses our web shop and disables cookies and she joust don't care. And that PHP Sessions are great because you can use them even if user disables Cookies. I was like wtf, wtf wtf?!?!
I made test with two files, index.php starts session and sets session variables. And then session.php tries to read that session variables.
This is how it looks:
index.php
<p>This is where I start and set php sessions.</p>
<?php
session_start();
$_SESSION['test1'] = "SessionTest1";
$_SESSION['test2'] = "SessionTest2";
?>
<p>This is a link, that starts new HTTP Request, and tries to read session set on this page:</p>
<p>Read Session</p>
session.php
<?php
session_start();
var_export($_SESSION);
?>
<p>Back</p>
Now, if you enable cookies in your browser, visit index.php, and the visit session.php , session would be printed out.
But, if you clear your browser history and cookies, and then visit index.php, and then visit session.php, you would see empty array right?
So basically my question is, am I right?
Can you use PHP sessions if you disable cookies in your browser?
And do PHP Session mechanism by default, depends on setting a session COOKIE?
Update:
I was going mad about this, so I called back the guy I was talking with. And asked him, can PHP session work without cookies by default? The guy said "yes". Then I told him he is wrong and he said: "yes, yes, if you say so..." and start laughing. Then I told him, ok if PHP session can work without setting cookie, how would server know current user/browser session id, if its not stored in a session cookie? (I wanted to see if he knows that session id can be passed as GET variable) And he was quiet for at least 20s, and told me that he is a System Administrator, and that I should ask that the Developer guy. And that he is 43 years old and has huge experience of 13 years in the bussines (he started with 30? wtf?), but he trusts me on this one. And I explained him how Session work and that you can use it without Cookie but then session id is passed as GET variable, and told him I told them that on interview, but they ware telling me no, no no... :S
So basically, the guy didn't have a clue about PHP and PHP Sessions, and yes he was the one that asked me about sessions telling me that PHP Session can work without cookie, even when I told him it cant be done, and that there is a way to use PHP Sessions without cookies but it won't work by default. He was like, no no no...
At the end he told me that he was thinking that sessions can work without cookies because he, as System Admin on his servers, can never see sessions in tmp folder?!?!?
Anyway, those guys suck at PHP, there is no way I will accept job offer from them, and after all this I dont think they will offer me a job anyway...
Thanks for all the comments!
"A visitor accessing your web site is assigned a unique id, the
so-called session id. This is either stored in a cookie on the user
side or is propagated in the URL. "
Sessions: Introduction
If session.use_cookies = 1 (Cookie enabled.)
If session.use_cookies = 0 (Cookie disabled.)
If session.use_cookies = 1 then session stores the sessionId into cookie. Calling session_id() get the stored sessionId from cookie and saved data into session array will be found on all the pages. If session.use_cookies = 0 In this case session does not store sessionId into cookie and you will get each time a new sessionId using session_id() and data stored into session on other pages will not be found on another pages.
Yes session will work when cookies is disabled.
But first apache check php configuration settings.
Like:
--enable-trans-sid
and
--enable-track-vars
if these value are set true the session will passed by POST automatically.
If "--enable-trans-sid" and "--enable-track-vars" values are set to FALSE, we need to pass session id by using the SID constant.
< a href="index.php?<?= SID ?>" >Navigate from here< /a >
Need to set php.ini
ini_set("session.use_cookies", 0);
ini_set("session.use_trans_sid", 1);
So basically my question is, am I right?
Mostly. In the real world: YES.
Can you use PHP sessions if you disable cookies in your browser?
You CAN use PHP sessions without cookies, as long as the browser identity is obtained somehow and yields a unique value (and this value is passed to the PHP session layer):
session ID in GET (which is the "standard" PHP way if cookies are not allowed, and the "other" way you described). This value is then propagated automatically by PHP, e.g. added to all A HREF's and so on. Where it is not propagated because the automagical link recognition failed (e.g. complex URL built in Javascript), it is your responsibility to provide accordingly.
Or - and here we're not in Kansas anymore:
passed among the nonces with Auth Digest (this is a dirty trick, and of course requires that the whole site is behind an Auth-Digest access authentication scheme. And you can no longer use a "dummy auth" (i.e. http://welcome:guest#www.example.com ) because some browsers, e.g. Internet Explorer, do not support them anymore for security reasons)
recognizing the browser some other way ("fingerprinting") (this is normally(1) suicidal)
Use LSO (Local Shared Objects) to generate a random UUID if it's not there already, and store it so that it can be retrieved on subsequent accesses.
other ways ( see http://en.wikipedia.org/wiki/Evercookie )
(1) if you were in a LAN where you can trust the IPs, you could associate a "session" to the user IP. You might enforce a strict "no cookies" policy in a small firm and still have user sessions without resorting to _GET/_POST for your session ID.
You are right, Session cannot work without cookies.
To illustrate this try doing the following actions.
Login To Gmail.
After login disabled the cookies.
Refresh the page.
You will be redirected to the login page again as the server cannot identify the session.
Now again enable the cookies.
Refresh the page. (Note: Don't click on login button).
You will be automatically redirected to the Gmail inbox.
Hence, we can say without cookies session will not work.
Also, If you are trying to login into the gmail( taking as example you can take any website) with diabled cookies then it will message as "Your browser has cookies disabled. Make sure your cookies are enabled and try again."
If it was me, I would say "Yes"
Since you could store session in form / url somewhere to passed to next page (very bad idea). So, based on his question "can PHP session be set and read, used, if Cookies are disabled in users Browser?"
Then, it should be yes. It can read and used.
However, If user close browser, then it's gone, and that's it. (since that guy didn't ask about this part)
Yes.. It will Work
1.PHP will pass one GET parameter in URL with the name PHPSESSID but it can be changed session.name in php.ini file.
2. It add one hidden input in forms with same name.
You will need to put the session ID in the URL. You will need to make a change in your php.ini file so if you are on a shared host you will need to contact them to see what they will do for you.
// tell the PHP we want to use cookies from the session
ini_set('session.use_cookies', '0');
ini_set('session.use_only_cookies', '0');
ini_set('session.use_trans_sid','1');
session_start();
// then pass the session ID in the URL(inspect, navigate the network refresh the page you will see in the headers your session ID)

PHP: Session variables

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.

How do I troubleshoot Issues with sessions?

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.

Categories