Cookies — PHP Technical Interview Questions & Answers

Cookies

Cookies

  • A cookie is a small string stored in the browser. setcookie('theme', 'dark', time()+86400, '/'); then $_COOKIE['theme']. Use for theme or ‘remember me’ token — not the raw password.
  • HttpOnly cookies are harder for JS to steal. Expiry in the past deletes a cookie.
  • Trap: setcookie after HTML started. Trap: huge data in cookies — use sessions.

Technical Interview Tip: setcookie then $_COOKIE. Sessions for login state.

Code Examples for Cookies

Cookies — working example

<?php
// Cookies
$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";
}

Cookies: scores array, print avg, then high marks. Say the output.

How to Explain Cookies to an Interviewer

Cookie vs session?

Cookie in the browser Session data on the server