Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP session_start() function: Why I need it everytime I use anything related to PHP sessions

For logging out a user from my website, I am redirecting the page to logout.php where I am using session_destroy() function. Even there also, logout functionality is not working without session_start() function. By adding session_start() function before session_destroy() function, I am able to logout the user successfully.

Why do I need to use session_start() function everytime and in every page where I am doing something related to sessions?

like image 337
sumit Avatar asked Apr 25 '11 15:04

sumit


4 Answers

session_destroy() destroys the active session. If you do not initialized the session, there will be nothing to be destroyed.

like image 112
John Cartwright Avatar answered Oct 30 '22 09:10

John Cartwright


Why do I need to use session_start() function everytime and in every page where I am doing something related to sessions?

So PHP knows which session to destroy. session_start() looks whether a session cookie or ID is present. Only with that information can you destroy it.

like image 29
Pekka Avatar answered Oct 30 '22 10:10

Pekka


In the default configuration, PHP Sessions operate off of the hard disk. PHP asks you to explicitly tell it when you need this support to avoid unnecessary disk IO.

session_start() also tells PHP to find out if the user's session exists.

like image 44
Jesse Bunch Avatar answered Oct 30 '22 09:10

Jesse Bunch


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.

as per http://php.net/manual/en/function.session-start.php

Essentially by calling session_start(), PHP reads the header and cross references that session ID to what is on your system(file system/database/etc), which can then populate the $_SESSION that is relavent to that specific user. Which in turn allows you to call session_destroy() because it knows what session to actually destroy.

like image 35
Mike Lewis Avatar answered Oct 30 '22 11:10

Mike Lewis