Sessions and Cookies
⏱ Estimated reading time: 2 min
Sessions and Cookies in CodeIgniter (CodeIgniter 4)
Sessions and Cookies are used to store user-related data across requests. CodeIgniter provides a secure and easy-to-use API for both.
1. Sessions
What Is a Session?
-
Stores data on the server
-
Identified by a session ID stored in a cookie
-
Commonly used for login/authentication
Session Configuration
File:
Key settings:
Starting a Session
Sessions are auto-started in CodeIgniter 4.
Access session:
Setting Session Data
Multiple values:
Getting Session Data
Check existence:
Removing Session Data
Destroy session:
Flashdata (Temporary Session Data)
Used for one-time messages (success/error).
Retrieve in view:
Example: Login Session
Check login:
2. Cookies
What Is a Cookie?
-
Stored on the client (browser)
-
Has size and security limitations
-
Used for preferences, remember-me, etc.
Setting a Cookie
Getting a Cookie
Deleting a Cookie
Secure Cookies
3. Sessions vs Cookies
| Feature | Sessions | Cookies |
|---|---|---|
| Storage | Server | Browser |
| Security | High | Lower |
| Size | Large | Small |
| Use Case | Login, auth | Preferences |
4. Best Practices
✅ Use sessions for sensitive data
✅ Use flashdata for messages
✅ Enable httponly & secure cookies
❌ Never store passwords in cookies
5. Common Use Cases
-
User authentication
-
Shopping cart
-
Language preference
-
Theme settings
Summary
-
Sessions store server-side user data
-
Cookies store client-side data
-
CodeIgniter provides secure APIs for both
-
Essential for authentication & UX
Register Now
Share this Post
← Back to Tutorials