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?
It must be on every page you intend to use. The variables contained in the session—such as username and favorite color—are set with $_SESSION, a global variable. In this example, the session_start function is positioned after a non-printing comment but before any HTML.
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. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
You want to put session_start(); at the top of your page before any other code. However, if you are using includes to make your life easier, it's best to put it at the very top of a file that is included in all files.
session_destroy() function: It destroys the whole session rather destroying the variables. When session_start() is called, PHP sets the session cookie in browser. We need to delete the cookies also to completely destroy the session. Example: This example is used to destroying the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With