Skip to main content
Course/Module 10/Topic 2 of 4Advanced

Authentication & Security

Implement secure user authentication — password hashing, session management, CSRF protection, and role-based access control.

55 minBy Priygop TeamLast updated: Feb 2026

User Authentication

  • Password Hashing: $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]); — never store plain text passwords. BCrypt automatically generates unique salt per password
  • Login Verification: password_verify($inputPassword, $storedHash) — returns true/false. Constant-time comparison prevents timing attacks. Don't reveal whether username or password was wrong
  • Session Management: session_start() at the beginning of every page. $_SESSION['user_id'] = $user['id']; $_SESSION['role'] = $user['role']; — store minimal data in session (ID and role, not password)
  • Session Security: session_regenerate_id(true) after login — prevents session fixation attacks. Set cookie params: session_set_cookie_params(['httponly' => true, 'secure' => true, 'samesite' => 'Strict'])
  • Logout: session_unset(); session_destroy(); setcookie(session_name(), '', time() - 3600); — clear session data, destroy session file, expire the cookie. Redirect to login page
  • Role-Based Access: function requireAuth($role = null) { if (!isset($_SESSION['user_id'])) { redirect('/login'); } if ($role && $_SESSION['role'] !== $role) { http_response_code(403); die('Forbidden'); } }

Security Best Practices

  • CSRF Protection: Generate token on form render — $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); <input type='hidden' name='csrf_token' value='...'> — verify on submit before processing
  • XSS Prevention: htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8') — escape all user-generated content before displaying in HTML. Never echo raw user input. Use in templates: <?= htmlspecialchars($post['title']) ?>
  • SQL Injection: Always use prepared statements with PDO — $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?'); $stmt->execute([$email]); — never concatenate user input into SQL strings
  • File Upload Security: Validate MIME type (finfo_file), check extension against whitelist, generate random filename (uniqid() . '.jpg'), limit file size (ini_set('upload_max_filesize', '5M')), store outside web root
  • Input Validation: filter_var($email, FILTER_VALIDATE_EMAIL) for email. preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username) for username. Always validate on server side — client validation is bypassable
  • HTTP Headers: header('X-Content-Type-Options: nosniff'); header('X-Frame-Options: DENY'); header('Content-Security-Policy: default-src self'); — defense-in-depth security headers
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep