How to Use PHP Sessions to Store Data
Sometimes it’s necessary for you to temporarily store data specific to a particular user while he/she surfs your website. For example, you may want to store that user’s preferences or the secret word displayed in a CAPTCHA image for checking later. PHP sessions provide you with just such a facility.
What’s the Difference Between Storing Your Data in Cookies and in Session Variables?
If you have read my tutorial on How to Create and Use Cookies in PHP, you may be wondering why you might want to bother with sessions when you can already use cookies to store small amounts of data specific to a particular user.
There are undoubtedly a number of differences between the use of cookies and session data. The following are, to me, the most significant difference that will affect your choice of which to use.
- Cookies are returned and stored in the user’s browser, session data are stored on your web server.
- The life span of a cookie can be set to almost any duration of your choosing. PHP sessions have a predetermined short life. The exact life span depends on how your web host has configured PHP on your server.
- Depending on how your web server is configured, session data is often stored in a public temporary directory on the server. As such it is possible that other users on the server may be able to peek at the data you store there.
When to Use Sessions Rather than Cookies
The above differences affect your choice of whether you should use cookies or sessions to store your data. Note that the following list is not exhaustive.
-
When you need the data stored on the server and not your user’s browser
When you set a cookie, the cookie is returned to the user and stored in his browser. Sometimes this is not a good idea.
For example, some websites have a CAPTCHA test on their web comment forms, where an image showing a few random letters and numbers is displayed and users are supposed to type in those characters to prove that they are human and not some spam bot (program). In order for this to work, the script generating the image needs to store the secret word somewhere, so that the program doing the checking can verify the user’s answer.
In such cases, returning a cookie to the user is not a good idea, since a spam bot, on receiving that cookie, can find out the secret word. You can of course encrypt your secret word before storing it in the cookie, but why bother when PHP sessions is exactly you need for this purpose?
-
When the data is transient, and only relevant for the current browsing session
Since you don’t know how long your session data will be stored, it stands to reason that you should only use sessions when you don’t really need the data for long periods of time. In fact, the data stored should also not be particularly important, so that it’s not the end of world if it’s lost because it expired.
-
When the data does not contain any information that needs to be securely kept
As mentioned earlier, the session data is kept in a temporary directory on your web server. This is usually a publicly accessible folder that anyone with an account on the computer can read. As such, you should be careful what information you store in your session variables. For example, do NOT store credit card numbers, personal particulars, passwords, user names, and things like that in your session variables.
While this point may seem like a contradiction to my earlier item about the CAPTCHA secret word, it really is not. Think about it. The CAPTCHA secret word is merely a crude device to distinguish the spam bots from the humans. It’s not really a secret — you even display the word in the user’s browser in plain sight. It doesn’t really matter if someone on the same web server as you happens to see the secret word currently being used. There’s not much that person can do with it, and even if it’s possible, so what? At worst, you get a few extra spam messages to delete.
Contrast that with storing your customers’ credit card numbers or passwords. If these are compromised, you will have a serious problem on your hands.
How to Use Sessions in Your PHP Scripts
To use sessions in your script you need to do the following.
-
Starting a Session
At the beginning of your script, make a call to the
session_start()function. This call should be in every script that needs to utilise the session data. For example, if you have a script that creates a CAPTCHA image and needs to store the secret word for the session, you will need to putsession_start()at the beginning of the script. If you have another script that takes the user input for the form and checks the secret word entered by the user against what you stored earlier, you will also need to putsession_start()in that script.The function
session_start()takes no parameters. It always returns TRUE, so you don’t have to bother to check its return value.When
session_start()is first called, PHP sets a cookie (yes, a cookie) in your visitor’s browser, containing a session identifier (”session ID”). It also creates a session data file to store variables related to that particular session. If the same script, or another script on your site, callssession_start()later, the PHP interpreter will receive the session ID cookie from the browser and load the variables from the session data file it created earlier.Important: since session_start() sets a cookie via the HTTP cookie header, you must call it before you output anything from your script. It’s best to simply call it at the beginning of your script.
-
Storing and Accessing Variables
To store variables relevant to the session, assign what you want to a member of the
$_SESSIONarray. For example, the following snippet assigns “ABC123″ to$_SESSION["secretword"]and a colour to$_SESSION["theme"]:$_SESSION["secretword"] = "ABC123" ; $_SESSION["theme"] = "purple" ;
You can assign as many variables as you wish.
To access those variables, simply reference it as you would any PHP array. For example:
session_start(); $captcha = $_POST["captcha"] ; $secretword = $_SESSION["secretword"] ; if (strcmp( $captcha, $secretword )) { // it's a bot } else { // matched -- it's a human }The above code retrieves the contents of the “secretword” session data and stores it in
$secretword. It also retrieves the value returned by a form’s “captcha” field and stores it in$captcha. The functionstrcmp()is then used to compare the contents of the two variables. -
Ending a Session
Ending a session is not as easy as starting one, since there is no simple function to cleanly end it. If you really need a way to end a session yourself (other than by the user simply quitting his/her browser), PHP provides the
session_destroy()to destroy the data associated with a session. However, this in itself does not clean up everything. For example, the session cookie is not unset. The$_SESSIONarray is also still available until your script ends.To remove the cookie, manually delete it using the usual method one uses to delete a cookie in PHP. To get the name of the cookie to delete, call the
session_name()function, which returns a string that is also the name of the cookie set by the PHP session handler.Example code for how you can clean up after a session can be found in the official PHP manual.
Conclusion
With this introduction to PHP sessions, you should be able to code scripts that take advantage of the built-in session handling provided by PHP.
Related Articles
- How to using .htaccess - 301 redirect your URL
- How to Access and Manage your MySQL Database - phpMyAdmin
- How to Use third-party DNS - EveryDNS best solution
- How to Select a Web Server and Server Platform?
- Three steps can not be missing from the site
Random Post
Sponsor links
Recent Posts
- When it’s Smart to Comparison Shop for Auto Insurance
- Refinance Your Auto Loan and Ease a Tight Budget
- Stretch Your Cash - Save on Auto Insurance
- Smart Life Insurance Shoppers Going Online
- Affiliate networks: ROIMatrix.com
- Affiliate networks: OffersQuest
- Affiliate networks: Offertrack
- Affiliate networks: Profitistic
- Affiliate networks: ClixGalore
- Affiliate networks: Rextopia
- Affiliate networks: CPA Warehouse
- Affiliate networks: XY7.com
- Affiliate networks: NeverblueADS
- Affiliate networks: Affiliate Future
- Affiliate networks: Checkmystats
- Affiliate networks: RocketProfit
- Affiliate networks: CPA Storm
- Affiliate networks: CapitAll Network
- Affiliate networks: Agami Media Publisher Network
- Affiliate networks: LinkRevenue Advertisings Solution
Recent Comments
- Make money - On…
in Why Have Car Insurance When It Has … - Make money - On…
in Car Loan: Tips Can Help Drive Smart… - Make money - On…
in How to Get a Loan Online in Three E… - Advertising &ra…
in Online advertising is personalized - Make money - On…
in Title Insurance - Home Buyers Bewar… - Make money - On…
in Insurance: Spotting Gaps In Your Ho… - Make money - On…
in Insurance: Spotting Gaps In Your Ho… - Advertising &ra…
in Forms of online advertising popular… - Make money - On…
in What Credit Companies Give the Most… - Make money - On…
in Eliminate Your Debt with Zero APR C…
Most Commented
- A Beginners Guide to Web Hosting (20)
- How to Use Online Networks to Market Your Business (15)
- Getting The Best Web Hosting For Your Business (8)
- Home Mortgage Loan - Less Than Perfect Credit (7)
- Bad Credit Loan Scams: Don't Send Money Upfront! (7)
- Evaluating The Response To Your Internet Marketing (7)
- Is Internet Marketing Working For You (7)
- 100 Google AdSense Tips (6)
- Forms of online advertising popular Today (6)
- Home Equity Loans To Help You Finance (6)
Most Popular
- PhP Scripts *Great Collection*
- FREE 1 Year Latest Spyware Doctor with AntiVirus 6 and Privacy Guardian 4.1 License Key
- New 40 year mortgages - Good or bad?
- IBM Prepares to Fight off Microsoft.
- 11 Reasons Why You Should Have A Home Based Travel Business
- Bad Credit Unsecured Personal Loans - A Panacea for Adverse Credit
- Top secret choose hosting and design website your companies
- Home Equity Loans To Help You Finance
- Top 5 ways to avoid the mortgage crisis
- Dot5 hosting - The cheapest hosting
Categories
- Computer (48)
- Laptops / Notebooks (23)
- Desktop Computers (17)
- NetWork (105)
- Unix, Linux (70)
- Windows (64)
- Security (13)
- Marketing (152)
- Profitable Business Ideas (104)
- Documents - Ebook (45)
- Affiliate (196)
- Make money (172)
- ClickBank Store (21)
- CLICKS - CPC (18)
- Free Software (39)
- Online Payment Methode (91)
- Credit Cards (87)
- SEO (76)
- Exam, Testing (19)
- Lesson (18)
- Free webhosting (81)
- Free Domain (58)
- Open Source (72)
- Free Web Templates (20)
- Tutorials (89)
- Movies Online (2)
- Insurance (56)
- Community health (15)
- Google Tips (127)
- Share Revenue (31)
- Adsense (79)
- Internet Business (214)
- Ecommerce (44)
- Internet Marketing (105)
- Web traffic (26)
- High Profit (33)
- Human Resources (14)
- Technology (16)
- Healthy (32)
- Money Saving (92)
- Finance (87)
- Student loans (62)
- How to (143)
- Tips (148)
- Funny Zone (1)









No Comment
Leave Your Comments Below