When do I have to declare session_start();? - php

So Im a beginner when it comes to PHP so I need a little help. I am trying to figure out when to start the session. Should I do it when the user first registers or what about when they log in?
Also, are sessions 'universal' meaning when I check a session will it work or do I have to include a file to all pages that check if someone has a session?

"Should I do it when the user first registers or what about when they log in?"
You should do it every time you want to get or set any session information. Data stored in the $_SESSION array will only be available after the session is started.
"Also, are sessions 'universal' meaning when I check a session will it work or do I have to include a file to all pages that check if someone has a session?"
Calling session_start() is all you need to create a session. If a session was already created, that session will be used.

just to session_start() once in every file you access the $_SESSION variable. best would be to do it in a central spot. for example a file which is included in every of your applications files.

Related

Can i use session_start() at the start of every page i.e in the header file of my website

I know if session is not destroyed at the end of some specific task then it will retain its values and could create problems next when you use it.
But when you say destroying a session then does it mean ending the session like this
session_end()
or it means that you have to unset some specific session which u have set before by doing this.
unset($_SESSION['id'])
etc.
And if i start a session at the top of every page and do not set it by $_SESSION['id'] etc then could that create problem for me. If yes then why i haven't got proper answer to this anywhere.
Here is how you destroy a session:
session_destroy();
There is no such thing as session_end() in PHP.
To empty a specific session variable, you generally do the following:
$_SESSION['id'] = '';
If you start a new session on top of every page using session_start it will just make sure the session is setup would it not be active for any reason (destroyed or never started).
It's untrue that there would be no documentation, actually, the web is full with articles and tutorials on session management. I myself used the following that helped me a lot to setup my login system of my web app: https://www.owasp.org/index.php/Session_Management.
I also suggest you have a read through all the functions that PHP specifically has to offer starting here: http://www.php.net/manual/en/features.sessions.php.

PHP session for user authentication

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.

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.

PHP: User logged in sessions and cookies

Sorry for the newbie question! I'm making a small website that allows users to create their own accounts. It's not a banking system, and it's unlikely that someone would want to hack it. That said, I am trying to make it reasonably secure, as there are plenty of bored script kiddies out there.
Could someone describe a basic workflow for a user logging in and having a cookie set that will keep them logged in for 30 days?
At the moment I have the following:
Validate and sanitize inputted data.
Check supplied credentials against bcrypt hashed password in DB.
If correct then call "Login" function.
Login function:
a. Delete any session data from DB with userID (table with two columns: SessionString and UserID).
b. Add new session data to DB (newy random generated string and UserID).
c. Write random generated string and UserID to cookie.
d. Set $_SESSION("UserID") with $userID.
But although the two cookies are being created and written to, the $_SESSION("UserID") remains blank... I'm guessing because I can't write to $_SESSION any time I like?
And even once that's fixed, how do I use the data stored in the cookie to log a user in? I'm guessing I don't want to go to the DB on every page load. And it will still require me to create a database object to see if the credentials in the cookie are ok. Is this the right way to this?
Once again, apologies for the newbie question!
UPDATE:
Yes, I do understand the difference between $_SESSION variables and a cookies. I also have session_start() at the top of every page (right after <php with no blank lines). $_SESSION("UserID") just remains blank.
Here's the code from the top of the page:
<?php
session_start();
if(!isset($_SESSION['initiated'])) {
session_regenerate_id();
$_SESSION['initiated'] = true;
}
Thanks for the help.
First off, there is an important difference between a session and a cookie. When you use the $_SESSION[".."] you are creating a session (which lives on the server, compared to a cookie which lives on the client), even though the browser uses a cookie to keep track of the session id. To create a cookie you would use the setcookie() method.
That said, I would recommend you to read through this article which is a step-by-step guide on how to create a secure login script, with persistence using a cookie for a "Remember me"-feature. Describe how to do it in detail would be to extensive for an SO answer im afraid.
Side note:
To be able to write to the session, you might have to call session_start(); prior to getting or setting a session variable using $_SESSION[".."].
Did you write a custom session handler that has your session-files stored in the db? I guess you don't.
If you want to use $_SESSION you have to also do session_start(). When using PHP sessions the cookie to identify the user will be set for you. You will also get session files created in your /tmp directory. That's the location your variables and anything you assign to $_SESSION will be stored.
Unless you define a custom session handler, that will manage the location of the session files, you won't need to query your database. Just save the users credentials in $_SESSION.
See this Tutorial on how to use PHP sessions.
PS: You access arrays like this: $_SESSION["UserID"], not with ().
you might want want to look at this article in which i have already discussed about various types of session hijacking and how you could avoid it.
session security in php

Write session start on 1 page or all pages?

All the tutorials say to put session start. They don't say if that should be in all pages on the website, or some, or only 1.
And if it's only 1 page, does it have to be the main page? Or a page with a form that I am making that puts the session ID in the database? If the visitor never visits a page with a session id but they are on the site, do they still have a session id?
You need to put this in each page that need to access the session data before accessing (or creating) any session data.
See: http://php.net/manual/en/function.session-start.php
Just for a matter of completeness you can choose to write session_start(); in all pages, in just one or in none of them. Let me explain this.
You need to start session in every script where you need access to $_SESSION variable but instead of putting session_start(); in every single script you can create a file headers.php and put there all your repetitive code including session_start();
If everything in your application needs access to $_SESSION you can forget the use of session_start(); simply setting session.auto_start = 1 in your php.ini file. You will be able to access $_SESSION without writing session_start(); before.
More here
Anything that is going to access Session variables needs to start the session.
So unless you have a php page that is non-dependent on the session than every page needs it.
You need to declare session_start(); in every page if you want to get data from $_SESSION or store data into $_SESSION in those particular page. If you do not need to interact with $_SESSION then you don't have to declare session_start().#hmwhat

Categories