Sessions & Cookies Interview Questions
Comprehensive sessions & cookies interview questions and answers for PHP. Prepare for your next job interview with expert guidance.
Questions Overview
1. What is the difference between sessions and cookies in PHP?
Basic2. How do you start a session in PHP and what does session_start() do?
Basic3. How do you set and retrieve cookies in PHP?
Basic4. What are the security considerations when working with sessions?
Moderate5. How do you implement session timeout in PHP?
Moderate6. What is session hijacking and how can it be prevented?
Advanced7. How do you destroy a session in PHP?
Basic8. What are the different session storage handlers in PHP?
Advanced9. How do you implement remember me functionality using cookies?
Moderate10. What is session fixation and how to prevent it?
Advanced11. How do you handle session data in distributed environments?
Advanced12. What are the limitations of cookies and how to work around them?
Moderate13. How do you implement secure session validation?
Advanced14. What is the purpose of session_cache_limiter() and its options?
Moderate15. How do SameSite cookies work and why are they important?
Moderate16. What are session configuration options in php.ini?
Moderate17. How do you implement custom session handling?
Advanced18. What is session garbage collection and how does it work?
Moderate19. How do you handle session expiration in AJAX applications?
Advanced20. What are HTTP-only cookies and their importance?
Basic21. How do you implement session-based authentication?
Moderate22. What is flash session data and how is it implemented?
Moderate23. How do you handle concurrent session access?
Advanced24. What are secure cookies and when should they be used?
Basic25. How do you implement session persistence across subdomains?
Advanced26. What are the best practices for session security in PHP?
Moderate27. How do you implement session migration?
Advanced28. What are domain cookies and their use cases?
Moderate29. How do you handle session synchronization in multi-server environments?
Advanced30. What is session adoption and its security implications?
Advanced1. What is the difference between sessions and cookies in PHP?
BasicSessions store data on the server with a unique session ID sent to client via cookie, while cookies store data directly on the client's browser. Sessions are more secure for sensitive data and expire when browser closes by default, while cookies can persist for specified durations.
2. How do you start a session in PHP and what does session_start() do?
Basicsession_start() initiates or resumes a session. It must be called before any output is sent to browser. It generates a unique session ID, creates/loads the session file on server, and sets a session cookie. It also loads existing session data into $_SESSION superglobal.
3. How do you set and retrieve cookies in PHP?
BasicCookies are set using setcookie() function: setcookie(name, value, expire, path, domain, secure, httponly). They can be retrieved using $_COOKIE superglobal array. Parameters control cookie lifetime, visibility, and security settings.
4. What are the security considerations when working with sessions?
ModerateKey security considerations include: using session_regenerate_id() to prevent session fixation, setting secure and httponly flags, implementing session timeout, validating session data, proper session destruction, and securing session storage location.
5. How do you implement session timeout in PHP?
ModerateSession timeout can be implemented by: setting session.gc_maxlifetime in php.ini, storing last activity timestamp in session, checking elapsed time on each request, and destroying session if timeout exceeded. Also consider implementing sliding expiration.
6. What is session hijacking and how can it be prevented?
AdvancedSession hijacking occurs when attacker steals session ID to impersonate user. Prevention includes: using HTTPS, setting secure/httponly flags, regenerating session IDs, implementing IP validation, using token-based authentication, and proper session timeout.
7. How do you destroy a session in PHP?
BasicComplete session destruction requires: session_unset() to clear variables, session_destroy() to destroy session data, clearing session cookie using setcookie(), and unset($_SESSION) array. Best practice includes clearing all related cookies and session data.
8. What are the different session storage handlers in PHP?
AdvancedPHP supports various session handlers: files (default), database, memcached, redis. Custom handlers can be implemented using SessionHandler interface. Each has advantages for different scenarios (scalability, persistence, performance).
9. How do you implement remember me functionality using cookies?
ModerateRemember me involves: generating secure token, storing hashed token in database, setting long-lived cookie with token, validating token on subsequent visits. Implementation should include token rotation, secure storage, and proper expiration handling.
10. What is session fixation and how to prevent it?
AdvancedSession fixation occurs when attacker sets victim's session ID. Prevention includes: regenerating session ID on login/privilege change using session_regenerate_id(true), validating session data, and implementing proper session security measures.
11. How do you handle session data in distributed environments?
AdvancedDistributed sessions require: centralized storage (Redis/Memcached), consistent session handling across servers, proper load balancing configuration, implementing sticky sessions or session replication, and handling failover scenarios.
12. What are the limitations of cookies and how to work around them?
ModerateCookie limitations include: size (4KB), number per domain, browser settings blocking cookies. Workarounds include: using local storage for larger data, implementing fallback mechanisms, splitting data across multiple cookies, server-side storage alternatives.
13. How do you implement secure session validation?
AdvancedSecure session validation includes: checking user agent consistency, validating IP address (with caution), implementing CSRF tokens, validating session age, checking session data integrity, and implementing proper authentication checks.
14. What is the purpose of session_cache_limiter() and its options?
Moderatesession_cache_limiter() controls HTTP caching of pages with sessions. Options include: nocache, private, public, private_no_expire. Affects how browsers and proxies cache session pages. Important for security and proper page caching.
15. How do SameSite cookies work and why are they important?
ModerateSameSite cookie attribute controls how cookie is sent with cross-site requests. Values: Strict, Lax, None. Helps prevent CSRF attacks and protects against cross-site request attacks. Important for modern web security compliance.
16. What are session configuration options in php.ini?
ModerateKey options include: session.save_handler, session.save_path, session.gc_maxlifetime, session.cookie_lifetime, session.cookie_secure, session.cookie_httponly. These control session behavior, storage, lifetime, and security settings.
17. How do you implement custom session handling?
AdvancedCustom session handling requires implementing SessionHandlerInterface with methods: open, close, read, write, destroy, gc. Used for custom storage solutions or specific session management requirements. Must handle all session operations properly.
18. What is session garbage collection and how does it work?
ModerateGarbage collection removes expired session data. Controlled by session.gc_probability, session.gc_divisor, and session.gc_maxlifetime settings. Process runs randomly based on probability settings. Important for server resource management.
19. How do you handle session expiration in AJAX applications?
AdvancedAJAX session handling includes: implementing session checks in AJAX calls, handling session timeout responses, providing user feedback, implementing automatic logout, and managing session refresh mechanisms. Consider implementing keepalive requests.
20. What are HTTP-only cookies and their importance?
BasicHTTP-only cookies cannot be accessed by JavaScript, protecting against XSS attacks. Set using httponly parameter in setcookie() or session configuration. Important security measure for sensitive cookies like session IDs.
21. How do you implement session-based authentication?
ModerateSession authentication involves: validating credentials, storing user data in session, implementing session security measures, handling remember me functionality, implementing proper logout, and managing session expiration.
22. What is flash session data and how is it implemented?
ModerateFlash data persists for only one request cycle, commonly used for temporary messages. Implementation involves storing data in session, checking for data existence, displaying data, and removing after use. Often used for success/error messages.
23. How do you handle concurrent session access?
AdvancedConcurrent access handling includes: implementing session locking mechanisms, using database transactions for session storage, handling race conditions, implementing proper session state management, and considering distributed session storage.
24. What are secure cookies and when should they be used?
BasicSecure cookies are only transmitted over HTTPS. Set using secure parameter in setcookie() or session configuration. Should be used for all sensitive data and session cookies when site uses HTTPS. Essential for maintaining transport security.
25. How do you implement session persistence across subdomains?
AdvancedCross-subdomain sessions require: setting session cookie domain to main domain, configuring session handler for shared access, managing session security across subdomains, and handling domain-specific session data appropriately.
26. What are the best practices for session security in PHP?
ModerateBest practices include: using HTTPS, setting secure/httponly flags, implementing proper session timeout, regenerating session IDs, validating session data, secure storage, proper destruction, and implementing CSRF protection.
27. How do you implement session migration?
AdvancedSession migration involves: copying session data to new storage, updating session handler configuration, managing transition period, handling failover scenarios, and ensuring data consistency. Important for system upgrades or architecture changes.
28. What are domain cookies and their use cases?
ModerateDomain cookies are accessible across subdomains. Set using domain parameter in setcookie(). Used for maintaining user state across subdomains, implementing single sign-on, sharing necessary data between related sites. Requires careful security consideration.
29. How do you handle session synchronization in multi-server environments?
AdvancedMulti-server synchronization requires: centralized session storage, consistent configuration across servers, handling race conditions, implementing proper locking mechanisms, and managing session replication or shared storage.
30. What is session adoption and its security implications?
AdvancedSession adoption occurs when taking over existing session. Security implications include: potential session fixation attacks, need for proper validation, importance of session regeneration, and implementing proper authentication checks. Requires careful implementation.