Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
Next.js Proxy Authentication Guard
Redirect unauthenticated requests from protected routes with the Next.js proxy convention.
// proxy.ts
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
export function proxy(request: NextRequest) {
const sessionId = request.cookies.get('session')?.value;
if (!sessionId) {
Basic Upload Validation
Validate upload error, size, and MIME type before accepting a file.
<?php
$file = $_FILES['avatar'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException('Upload failed.');
}
if ($file['size'] > 2 * 1024 * 1024) {
throw new RuntimeException('The file is too large.');
}
Safe Redirect Allow List
Redirect only to known internal paths instead of trusting user input.
<?php
$allowedRedirects = [
'/my-dashboard',
'/my-workspace',
'/my-billing',
];
$next = $_GET['next'] ?? '/my-dashboard';
if (!in_array($next, $allowedRedirects, true)) {
$next = '/my-dashboard';
}
header('Location: ' . $next);
exit;
Regenerate Session After Login
Regenerate the PHP session ID after a successful login.
<?php
session_start();
// After checking the username and password successfully:
session_regenerate_id(true);
$_SESSION['client_id'] = $client['id'];
$_SESSION['client_email'] = $client['email'];
$_SESSION['logged_in_at'] = time();
Password Hash and Verify
Hash a password and verify it later with PHP built-in helpers.
<?php
$password = $_POST['password'] ?? '';
$hash = password_hash($password, PASSWORD_DEFAULT);
// Later, during login:
$valid = password_verify($password, $hash);
if ($valid) {
echo 'Password is correct';
} else {
echo 'Invalid password';
}
PDO Insert with Named Parameters
Insert a row safely with PDO named parameters.
<?php
$sql = "INSERT INTO contacts (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':name' => trim($_POST['name'] ?? ''),
':email' => trim($_POST['email'] ?? ''),
]);
$contactId = (int) $pdo->lastInsertId();
Safe HTML Escape Helper
A small PHP helper for escaping output in HTML templates.
<?php
function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$title = '<script>alert("xss")</script>';
echo '<h1>' . e($title) . '</h1>';
CSRF Token Input
A simple PHP pattern for rendering and validating a CSRF token.
<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
function csrfInput(): string
{
$token = htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8');
PDO Select One Row
A safe PDO example for selecting a single row with a prepared statement.
<?php
function findUserByEmail(PDO $pdo, string $email): ?array
{
$stmt = $pdo->prepare(
'SELECT id, email, firstname, lastname
FROM users
WHERE email = :email
LIMIT 1'
);
$stmt->execute([