File Upload, Cookies & Sessions
Forms need enctype="multipart/form-data" for files. PHP stores uploads in $_FILES. Move from tmp_name with move_uploaded_file().
File Upload
Forms need enctype="multipart/form-data" for files. PHP stores uploads in $_FILES. Move from tmp_name with move_uploaded_file().
Real-life example: Upload is mailing a package — PHP checks size, type, then moves it from the post office (tmp) to your shelf (uploads/).
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["photo"])) {
$file = $_FILES["photo"];
if ($file["error"] === UPLOAD_ERR_OK) {
$dest = "uploads/" . basename($file["name"]);
move_uploaded_file($file["tmp_name"], $dest);
echo "Saved to $dest";
}
}
?><form method="post" enctype="multipart/form-data">
<input type="file" name="photo" accept="image/*" />
<button type="submit">Upload</button>
</form>Cookies
setcookie() sends small data to the browser. $_COOKIE reads it back. Use for theme, language, or "remember me" — not passwords.
Real-life example: Cookies are sticky notes the browser keeps — "this user prefers dark mode."
<?php
setcookie("theme", "dark", [
"expires" => time() + 86400 * 30,
"path" => "/",
"httponly" => true,
"samesite" => "Lax",
]);
$theme = $_COOKIE["theme"] ?? "light";
echo "Theme: $theme";
?>Sessions
session_start() begins server-side session storage in $_SESSION. Use for login state, shopping carts, and flash messages.
Real-life example: Sessions are a coat-check ticket — the browser holds the ticket; the server holds your coat.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$email = $_POST["email"] ?? "";
$_SESSION["user_email"] = $email;
session_regenerate_id(true); // security after login
}
if (isset($_SESSION["user_email"])) {
echo "Welcome, " . htmlspecialchars($_SESSION["user_email"]);
}
?>