PHP Security Patterns
БесплатноБез исполняемых скриптовНе проверенUse when essential PHP security patterns including input validation, SQL injection prevention, XSS protection, CSRF tokens, password hashing, secure session…
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
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
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
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);
Установить PHP Security Patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл 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.
Как установить скилл PHP Security Patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл PHP Security Patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic