Sessions — PHP Technical Interview Questions & Answers
Sessions
Sessions
- A session remembers the user across pages. session_start(); then $_SESSION['user'] = 'Asha'; Next page: session_start(); echo $_SESSION['user']; PHP stores data on the server and sends a cookie with the session id.
- session_start() must run before any HTML output. session_destroy() on logout. Don’t store passwords in $_SESSION.
- Trap: forgetting session_start(). Trap: session_start after echo.
Technical Interview Tip: session_start(); $_SESSION['user']='Asha';
Code Examples for Sessions
Sessions — working example
<?php
// Sessions
$scores = [80, 90, 70];
$avg = array_sum($scores) / count($scores);
echo "avg=" . number_format($avg, 1) . "\n";
foreach ($scores as $s) {
if ($s >= 80) echo "high: $s\n";
}Sessions: scores array, print avg, then high marks. Say the output.
How to Explain Sessions to an Interviewer
Where is session data stored?
On the server Browser only keeps the session id cookie