Harden sessions
Cookie params
The session id travels in a cookie, so lock that cookie down first. Set HttpOnly to hide it from scripts and restrict it to secure connections on live sites.
Call session_set_cookie_params before session_start. Every request that uses sessions needs the same call.
session_set_cookie_params([
"lifetime" => 0,
"httponly" => true,
]);
session_start();
echo "ready";
Regenerate ids
Change the session id at privilege boundaries such as login and password change. The stored data stays, only the id changes.
Pass true to delete the old session record on the server. The old id stops working right away.
session_start();
$_SESSION["user_id"] = 42;
session_regenerate_id(true);
echo "ok";
Detect theft simply
A basic check compares a stored browser marker with the current request. If the marker changes, treat the session as suspect and clear it.
This is not perfect, but it stops casual id reuse. Keep the logic simple and log suspicious resets for review.
session_start();
$agent = $_SERVER["HTTP_USER_AGENT"];
if ($_SESSION["agent"] !== $agent) {
$_SESSION = [];
echo "reset";
}
Where sessions live
By default PHP stores session data in files on the server. Only the random id goes to the browser, never the data itself.
Use session_save_path to inspect the storage directory. On shared hosting keep that directory outside public web access.
echo session_save_path();
session_start();
echo session_id();
Next: Password hashing
Article author: Arthur Isaev