PHP Scripts ·
Small PHP Snippets: Dates, Strings, Files, UUIDs, Mail
By Manu Mathew · Last updated 4 October 2026
WordPress and many small business sites run on PHP, and the same little tasks come up in plugins, themes and one-off scripts. This page brings together several short notes I wrote between 2013 and 2014. I have rewritten them in one place, with tested examples and current advice, so you don’t have to piece the answer together from fragments.
Quick answer
Add days with DateTimeImmutable::modify('+1 day'), count with count(), and replace text with str_replace() or preg_replace(). Create folders with mkdir($dir, 0755, true). Use random_bytes() for UUIDs, a mail library for SMTP, and require_once or an autoloader so a class is declared only once.
I tested every snippet with PHP 8.4 on the command line.
How do I add a day to a date?
Create a DateTimeImmutable and call modify('+1 day'), which returns a new date and leaves the original alone.
<?php
$date = new DateTimeImmutable('2013-04-12');
echo $date->modify('+1 day')->format('Y-m-d H:i:s'), "\n"; // 2013-04-13 00:00:00
// Or with the classic functions
echo date('Y-m-d', strtotime('2013-04-12 +1 day')), "\n"; // 2013-04-13
modify() handles month ends and leap years for you, but watch months: on 31 January 2026, modify('+1 month') gives 3 March, because February has no 31st. Use modify('last day of next month') when you mean the month end.
How do I get the length of an array?
count($array) returns the number of elements; add COUNT_RECURSIVE to count nested elements too.
<?php
$numbers = [1, 3, 5];
echo count($numbers), "\n"; // 3
$nested = ['a' => [1, 2], 'b' => [3]];
echo count($nested), "\n"; // 2
echo count($nested, COUNT_RECURSIVE), "\n"; // 5 (2 keys + 3 values)
How do I replace text in a string?
Use str_replace() for fixed text and preg_replace() for patterns.
<?php
// Plain text replacement
$vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
echo str_replace($vowels, '', 'Hello World of PHP'), "\n"; // Hll Wrld f PHP
// Pattern replacement with capture groups
echo preg_replace('/(\w+) (\d+), (\d+)/', '$2 $1 $3', 'April 15, 2003'), "\n"; // 15 April 2003
str_replace() accepts arrays, so one call can remove or swap a whole list of strings. In preg_replace(), $1, $2 and so on insert the captured groups; write ${1} when a digit follows straight after.
How do I split a number into its digits?
Cast the number to a string and use str_split(); use explode() when the parts are separated by a character.
<?php
$digits = str_split((string) 187954);
print_r($digits); // ['1', '8', '7', '9', '5', '4']
echo array_sum($digits), "\n"; // 34
$parts = explode(',', '10,20,30'); // split on a separator instead
echo implode(' | ', $parts), "\n"; // 10 | 20 | 30
How do I create a folder, or check that one exists?
mkdir($dir, 0755, true) creates the folder and any missing parents; is_dir() checks for a folder.
<?php
$dir = __DIR__ . '/uploads/2026/10';
if (!is_dir($dir) && !mkdir($dir, 0755, true)) { // true creates the parent folders too
exit("Could not create $dir\n");
}
echo is_dir($dir) ? "Folder ready\n" : "Missing\n";
// file_exists() is true for files AND folders; is_dir() only for folders
var_dump(file_exists(__FILE__), is_dir(__FILE__)); // bool(true) bool(false)
file_exists() is also true for plain files, so use is_dir() when you specifically need a folder.
How do I send a file as a download?
Check the requested name, send the content headers, then stream the file with readfile().
<?php
$dir = '/srv/reports';
$name = basename($_GET['file'] ?? ''); // drop any path the visitor sends
$path = "$dir/$name";
if (!preg_match('/\A[\w.-]+\.pdf\z/', $name) || !is_file($path)) {
http_response_code(404);
exit('No such file');
}
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Content-Length: ' . filesize($path));
header('Cache-Control: private, no-cache');
readfile($path);
Never pass a visitor’s input straight to readfile(). Here basename() drops any path, the pattern allows only plain PDF names, and the file must exist in the reports folder, so a request for ../../etc/passwd gets a 404.
How do I generate a UUID in PHP?
Take 16 bytes from random_bytes(), set the version and variant bits, and format them as hex.
<?php
// A random (version 4) UUID, as described in RFC 9562
function uuid_v4(): string {
$bytes = random_bytes(16);
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40); // version 4
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80); // RFC 9562 variant
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}
echo uuid_v4(), "\n"; // e.g. 1b4e28ba-2fa1-4d3b-a3f5-ef19b5a7633b
The class in the old note built an ID from the server number, the visitor’s IP address and the time. It looked like a UUID but didn’t follow the standard, and the IP part leaked personal data. In a framework, use its UUID helper, such as wp_generate_uuid4() in WordPress or symfony/uid.
How do I send email through SMTP from PHP?
Use a maintained library such as PHPMailer and read the SMTP settings from the environment, not from the code.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require __DIR__ . '/vendor/autoload.php'; // composer require phpmailer/phpmailer
$mail = new PHPMailer(true); // true: throw exceptions on errors
try {
$mail->isSMTP();
$mail->Host = getenv('SMTP_HOST');
$mail->Port = (int) getenv('SMTP_PORT');
$mail->SMTPAuth = getenv('SMTP_USER') !== false;
$mail->Username = (string) getenv('SMTP_USER');
$mail->Password = (string) getenv('SMTP_PASS'); // keep credentials out of the code
$mail->SMTPSecure = getenv('SMTP_TLS') ?: ''; // 'tls' or 'ssl' on a real server
$mail->CharSet = 'UTF-8';
$mail->setFrom('orders@example.com', 'Example Shop');
$mail->addAddress('customer@example.org');
$mail->Subject = 'Your order';
$mail->isHTML(true);
$mail->Body = '<p>Thanks for your order.</p>';
$mail->AltBody = 'Thanks for your order.';
$mail->send();
echo "Sent\n";
} catch (Exception $e) {
echo 'Not sent: ', $mail->ErrorInfo, "\n";
}
I tested this with PHPMailer 6 against a local test SMTP server. The old note used PEAR Mail, which is no longer maintained. On WordPress, use wp_mail() together with an SMTP plugin instead, so the site’s mail settings stay in one place.
How do I avoid “Cannot redeclare class” errors?
Load the file that declares the class with require_once, or let an autoloader load it on first use.
<?php
for ($i = 0; $i < 3; $i++) {
require_once __DIR__ . '/classes/Greeter.php'; // loaded the first time only
$greeter = new Greeter();
echo $greeter->hello($i), "\n";
}
// Or guard the declaration itself
if (!class_exists('Greeter', false)) {
require __DIR__ . '/classes/Greeter.php';
}
The class lives in its own file, classes/Greeter.php:
<?php
class Greeter
{
public function hello(int $n): string
{
return "Hello, count $n";
}
}
An autoloader is the modern answer, and it is what Composer sets up for you:
<?php
spl_autoload_register(function (string $class): void {
$file = __DIR__ . '/classes/' . $class . '.php';
if (is_file($file)) {
require $file;
}
});
echo (new Greeter())->hello(7), "\n"; // Hello, count 7, loaded on first use
PHP never lets you declare the same class twice in one request. If you need two versions, give them different names or namespaces.
WordPress runs on PHP. If your WordPress site needs fixes or ongoing care, see WordPress websites for small businesses.
Sources: PHP manual: DateTimeImmutable::modify; PHP manual: str_replace; PHP manual: preg_replace; PHP manual: mkdir; PHP manual: readfile; PHP manual: random_bytes; RFC 9562: UUIDs; PHPMailer; PHP manual: spl_autoload_register.