Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
Language Detection and Translation Loader
Manages front-end language detection, session and cookie handling, and loads language translation scopes from PHP files with fallback suppor...
<?php
declare(strict_types=1);
// ------------------------------------------------------------
// Global language code list
// ------------------------------------------------------------
if (!defined('ALLOWED_LANG_CODES')) {
Simple PHP Router with Dynamic User ID Route
This code implements a basic PHP router that directs static URLs to specific files and handles dynamic user ID routes, returning a 404 error...
<?php
$routes = [
'/' => 'home.php',
'/about' => 'about.php',
'/user' => 'user.php'
];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
function handleRoute($uri, $routes)
{
if (array_key_exists($uri, $routes)) {
Load PHPMailer Library Once
This function loads the three essential PHPMailer files only once to prevent multiple inclusions during execution.
<?php
function mailer_require_phpmailer(): void
{
static $loaded = false;
if ($loaded) {
return;
}
$base = APP_PATH . '/libraries/PHPMailer/src';
require_once $base . '/Exception.php';
require_once $base . '/PHPMailer.php';
cURL GET Request in PHP
Call an external API with cURL and decode the JSON response.
<?php
$ch = curl_init('https://api.example.com/items');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$responseBody = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
PHP Read JSON Request Body
Read and validate a JSON request body in PHP.
<?php
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);
if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON body.']);
exit;
}
PHP JSON Response Helper
Return a JSON response from a small PHP endpoint.
<?php
function json_response(array $payload, int $status = 200): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
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();
Find Text in Files
Search for a word or phrase inside files recursively.
Select-String -Path "*.php" -Pattern "TODO" -Recurse |
Select-Object Path, LineNumber, Line
Reset One File to Last Commit
Discard local changes from one file and restore the committed version.
git restore path/to/file.php
Find Text in Files
A Windows CMD command that searches for text inside files.
@echo off
findstr /s /i /n "TODO" *.php
pause
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>';
Group Array Items by Key
A useful PHP helper for grouping database rows by a selected key.
<?php
function groupByKey(array $items, string $key): array
{
$groups = [];
foreach ($items as $item) {
$groupKey = (string) ($item[$key] ?? '');
if ($groupKey === '') {
continue;
}
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');
Simple Slug Generator
A compact PHP slug generator for URLs and filenames.
<?php
function makeSlug(string $text): string
{
$text = strtolower(trim($text));
$text = preg_replace('/[^a-z0-9]+/i', '-', $text);
$text = trim((string) $text, '-');
return $text !== '' ? $text : 'item';
}
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([
Filter an Array of Objects
A beginner-friendly JavaScript example for filtering objects by search text.
const snippets = [
{ title: 'PHP Slug Generator', language: 'php' },
{ title: 'CSS Loading Spinner', language: 'css' },
{ title: 'JavaScript Debounce', language: 'javascript' }
];
function searchSnippets(items, query) {