Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
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();
Simple Class with Property
Create a small class with properties and instantiate it.
using System;
Product product = new()
{
Name = "Keyboard",
Price = 49.99m
};
Console.WriteLine($"{product.Name}: {product.Price:C}");
class Product
{
public string Name { get; set; } = "";
public decimal Price { get; set; }
}
Read All Lines from File
Read a text file into lines and print each line with its index.
using System;
using System.IO;
string path = "notes.txt";
if (!File.Exists(path))
{
Console.WriteLine("File not found.");
return;
}
string[] lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length; i++)
{
Count Words with Dictionary
Count repeated words with a Dictionary in a simple console example.
using System;
using System.Collections.Generic;
string text = "csharp is useful and csharp is fun";
string[] words = text.ToLower().Split(' ');
Dictionary<string, int> counts = new();
foreach (string word in words)
{
if (!counts.ContainsKey(word))
{
Filter a List with LINQ
Filter a list of numbers using a LINQ Where expression.
using System;
using System.Collections.Generic;
using System.Linq;
List<int> numbers = new() { 3, 8, 12, 15, 20, 21 };
List<int> evenNumbers = numbers
.Where(number => number % 2 == 0)
.ToList();
Console.WriteLine(string.Join(", ", evenNumbers));
Read Console Input Safely
Read a number from the console without crashing on invalid input.
using System;
Console.Write("Enter your age: ");
string? input = Console.ReadLine();
if (int.TryParse(input, out int age))
{
Console.WriteLine($"You are {age} years old.");
}
else
{
Console.WriteLine("Please enter a valid number.");
}
Remove Empty Folders
Remove empty folders under the current directory.
Get-ChildItem -Directory -Recurse |
Sort-Object FullName -Descending |
Where-Object { -not (Get-ChildItem -Path $_.FullName -Force) } |
Remove-Item -Force
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
Create Project Folders
Create a simple frontend project folder structure.
$folders = @(
"src",
"public",
"assets",
"assets/css",
"assets/js",
"assets/img"
)
foreach ($folder in $folders) {
New-Item -ItemType Directory -Path $folder -Force | Out-Null
}
Write-Host "Project folders created."
List Large Files
Find large files in the current folder and subfolders.
Get-ChildItem -Recurse -File |
Where-Object { $_.Length -gt 100MB } |
Sort-Object Length -Descending |
Select-Object FullName, @{Name="SizeMB"; Expression={[math]::Round($_.Length / 1MB, 2)}}
Rename Images with Counter
Rename JPG images in a folder with a clean numbered filename.
$counter = 1
Get-ChildItem -Filter *.jpg | ForEach-Object {
$newName = "image-{0:D3}.jpg" -f $counter
Rename-Item -Path $_.FullName -NewName $newName
$counter++
}
Match Date YYYY-MM-DD
Match a simple ISO-style date format.
^\d{4}-\d{2}-\d{2}$
Find HTML Tags
Find simple opening or closing HTML tags in text.
<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^>]*)?>
Validate Hex Color
Match CSS hex colors like #fff or #a1b2c3.
^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
Extract Numbers from Text
Find integer and decimal numbers inside a string.
\d+(?:\.\d+)?
Match Email Address
A practical beginner regex for basic email-like text matching.
^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
Reset One File to Last Commit
Discard local changes from one file and restore the committed version.
git restore path/to/file.php
Show Changed Files
Show which files changed before you commit.
git status --short
git diff --name-only
Stash Work in Progress
Temporarily save unfinished changes and restore them later.
git stash push -m "work in progress"
git stash list
git stash pop
Undo Last Commit Keep Changes
Undo the last commit but keep the changed files in your working directory.
git reset --soft HEAD~1
Create and Switch Branch
Create a new Git branch and switch to it in one command.
git switch -c feature/login-page
Search Multiple Columns
Search several text columns with LIKE placeholders.
SELECT id, title, description
FROM snippets
WHERE title LIKE :search_title
OR description LIKE :search_description
OR language_code LIKE :search_language
ORDER BY updated_at DESC;