PHP Security Patterns
Use when essential PHP security patterns including input validation, SQL injection prevention, XSS protection, CSRF tokens, password hashing, secure session management, and defense-in-depth strategies for building secure PHP applications.
What this skill does
# PHP Security Patterns
## Introduction
Security is paramount in PHP applications as they often handle sensitive user data,
authentication, and financial transactions. PHP's flexibility and dynamic nature
create opportunities for vulnerabilities if security best practices aren't followed.
Common PHP security vulnerabilities include SQL injection, cross-site scripting
(XSS), cross-site request forgery (CSRF), insecure password storage, session
hijacking, and file inclusion attacks. Each can lead to data breaches, unauthorized
access, or complete system compromise.
This skill covers input validation and sanitization, SQL injection prevention,
XSS protection, CSRF defense, secure password handling, session security, file
upload security, and defense-in-depth strategies.
## Input Validation and Sanitization
Input validation ensures data meets expected formats before processing, while
sanitization removes or encodes potentially dangerous content.
```php
<?php
declare(strict_types=1);
// Email validation
function validateEmail(string $email): bool {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
// URL validation
function validateUrl(string $url): bool {
return filter_var($url, FILTER_VALIDATE_URL) !== false;
}
// Integer validation
function validateInt(mixed $value, int $min = PHP_INT_MIN,
int $max = PHP_INT_MAX): ?int {
$int = filter_var($value, FILTER_VALIDATE_INT, [
'options' => [
'min_range' => $min,
'max_range' => $max,
],
]);
return $int !== false ? $int : null;
}
// String sanitization
function sanitizeString(string $input): string {
// Remove null bytes and control characters
$sanitized = str_replace("\0", '', $input);
$sanitized = preg_replace('/[\x00-\x1F\x7F]/u', '', $sanitized);
return trim($sanitized);
}
// HTML sanitization (output encoding)
function sanitizeHtml(string $input): string {
return htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
// Example usage
class UserRegistration {
private array $errors = [];
public function validate(array $data): bool {
// Validate email
if (!isset($data['email']) || !validateEmail($data['email'])) {
$this->errors[] = 'Invalid email address';
}
// Validate age
$age = validateInt($data['age'] ?? null, 13, 120);
if ($age === null) {
$this->errors[] = 'Age must be between 13 and 120';
}
// Validate username (alphanumeric, 3-20 chars)
$username = sanitizeString($data['username'] ?? '');
if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
$this->errors[] = 'Username must be 3-20 alphanumeric characters';
}
// Validate password strength
if (!$this->validatePassword($data['password'] ?? '')) {
$this->errors[] = 'Password must be at least 8 characters ' .
'with mixed case and numbers';
}
return empty($this->errors);
}
private function validatePassword(string $password): bool {
return strlen($password) >= 8
&& preg_match('/[A-Z]/', $password)
&& preg_match('/[a-z]/', $password)
&& preg_match('/[0-9]/', $password);
}
public function getErrors(): array {
return $this->errors;
}
}
// Whitelist validation for enums
function validateStatus(string $status): ?string {
$allowed = ['pending', 'approved', 'rejected'];
return in_array($status, $allowed, true) ? $status : null;
}
// Complex data validation
function validateUserData(array $data): array {
$validated = [];
// Required fields
$validated['email'] = validateEmail($data['email'] ?? '')
? $data['email']
: throw new InvalidArgumentException('Invalid email');
// Optional fields with defaults
$validated['age'] = validateInt($data['age'] ?? 0, 0, 150) ?? 18;
$validated['name'] = sanitizeString($data['name'] ?? '');
// Nested validation
if (isset($data['address'])) {
$validated['address'] = [
'street' => sanitizeString($data['address']['street'] ?? ''),
'city' => sanitizeString($data['address']['city'] ?? ''),
'zip' => preg_match('/^\d{5}$/', $data['address']['zip'] ?? '')
? $data['address']['zip']
: null,
];
}
return $validated;
}
```
Always validate input at the application boundary and sanitize before output to
prevent injection attacks.
## SQL Injection Prevention
SQL injection occurs when user input is directly interpolated into SQL queries,
allowing attackers to manipulate queries.
```php
<?php
declare(strict_types=1);
// UNSAFE: Direct string concatenation
function findUserUnsafe(PDO $pdo, string $email): ?array {
// NEVER DO THIS - vulnerable to SQL injection
$sql = "SELECT * FROM users WHERE email = '$email'";
$result = $pdo->query($sql);
return $result ? $result->fetch(PDO::FETCH_ASSOC) : null;
}
// SAFE: Prepared statements with PDO
function findUserSafe(PDO $pdo, string $email): ?array {
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result !== false ? $result : null;
}
// Safe: Positional parameters
function findUserById(PDO $pdo, int $id): ?array {
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result !== false ? $result : null;
}
// Safe: Multiple parameters
function findUsersByStatus(PDO $pdo, string $status, int $limit): array {
$stmt = $pdo->prepare(
'SELECT * FROM users WHERE status = :status LIMIT :limit'
);
$stmt->bindValue(':status', $status, PDO::PARAM_STR);
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Safe: IN clause with placeholders
function findUsersByIds(PDO $pdo, array $ids): array {
// Validate all IDs are integers
$ids = array_filter($ids, 'is_int');
if (empty($ids)) {
return [];
}
// Create placeholders: ?,?,?
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$sql = "SELECT * FROM users WHERE id IN ($placeholders)";
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Repository pattern with prepared statements
class UserRepository {
public function __construct(
private PDO $pdo
) {}
public function find(int $id): ?array {
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result !== false ? $result : null;
}
public function create(array $data): int {
$stmt = $this->pdo->prepare(
'INSERT INTO users (name, email, password_hash) VALUES (?, ?, ?)'
);
$stmt->execute([
$data['name'],
$data['email'],
$data['password_hash'],
]);
return (int) $this->pdo->lastInsertId();
}
public function update(int $id, array $data): bool {
$stmt = $this->pdo->prepare(
'UPDATE users SET name = ?, email = ? WHERE id = ?'
);
return $stmt->execute([
$data['name'],
$data['email'],
$id,
]);
}
public function delete(int $id): bool {
$stmt = $this->pdo->prepare('DELETE FROM users WHERE id = ?');
return $stmt->execute([$id]);
}
public function search(string $query, int $limit = 10): array {
$stmt = $this->pdo->prepare(
'SELECT * FROM users WHERE name LIKE ? OR email LIKE ? LIMIT ?'
);
$pattern = "%$query%";
$stmt->bindValue(1, $pattern, PDO::PARAM_STR);
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.