QA
Beginner LevelPHP 8+

How do you set secure, tamper-resistant HTTP cookies in PHP using setcookie() with SameSite and HttpOnly flags?

❓ Interview Prompt: Explain setting HTTP cookies in PHP using setcookie(), expiration timestamps, HttpOnly, Secure, and SameSite options array.

'setcookie()' sends HTTP 'Set-Cookie' response headers to store client-side cookies in the browser.

Essential Security Options Array (PHP 7.3+):

•
'expires': Expiration Unix timestamp.
•
'secure' => true: Restricts cookie transmission strictly to encrypted HTTPS connections.
•
'httponly' => true: Prevents client-side JavaScript ('document.cookie') from accessing the cookie, defeating XSS token theft!
•
'samesite' => 'Strict' / 'Lax': Restricts sending cookies on cross-site requests, mitigating CSRF attacks.

Code Implementation Example

php
<?php
// Setting a secure HTTP cookie using PHP 7.3+ options array
setcookie('remember_token', 'random_secret_token_123', [
    'expires'  => time() + 86400 * 30, // 30 days
    'path'     => '/',
    'domain'   => 'company.com',
    'secure'   => true,     // HTTPS only!
    'httponly' => true,     // Block JavaScript access (XSS protection!)
    'samesite' => 'Strict'  // CSRF protection!
]);
💡Configuring secure HTTP cookies with HttpOnly, Secure, and SameSite flags in PHP.
🎯 Interview Key Takeaway

Set httponly => true and samesite => Strict on cookies to mitigate XSS script theft and CSRF cross-site attacks.

#Cookies#Security#HttpOnly#SameSite#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?