Community코딩 & 개발github.com

PHP 8.0+ 개발 — XAMPP, RESTful API, PDO/MySQL/MariaDB 및 인증

PHP 8.0+ 개발을 위한 스킬입니다. XAMPP 환경 구성, RESTful API 설계, PDO 기반 MySQL/MariaDB 데이터베이스 연동, 그리고 인증 시스템 구현을 지원합니다. PHP 백엔드 구축, API 엔드포인트 생성, XAMPP 설정, 또는 데이터베이스 통합 작업 시 활용하세요.

MySQL/MariaDB 및 인증란 무엇인가요?

이 스킬은 PHP 8.0+ 환경에서 고품질 애플리케이션을 개발하기 위한 종합 가이드를 제공합니다. PDO(Prepared Statement)를 통한 안전한 데이터베이스 접근, RESTful API 설계, XAMPP 환경 구성, 그리고 인증 및 세션 관리에 특화되어 있습니다. GitHub Copilot, Claude Code, Codex 등 다양한 AI 에이전트 플랫폼에서 이식 가능하게 설계되었으며, 로컬 명령어와 표준 도구를 활용하여 MCP 서버 없이도 작동합니다. PHP 8.0의 네임드 인자, 유니온 타입, 널 세이프 연산자 등의 최신 기능을 최대한 활용하며, SQL 인젝션 방지를 위한 Prepared Statement, 비밀번호 해싱, CORS 설정 등 보안 모범 사례를 강조합니다. 검증 프로토콜을 통해 스킬 적용 전후의 빌드, 린트, 테스트를 자동으로 수행하여 정확성을 보장합니다.

지원 대상✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/mianhtsys/landingMod3/tree/HEAD/MODULO_3_DESARROLLO_AL_LADO_DEL_CLIENTE_Y_SERVIDOR_WEB/architecture-skills-framework/.agents/skills/php-development

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

PHP 개발

최신 PHP 8.x 릴리스, PHPUnit 11+, Composer 2.x 및 PDO 기반 MySQL 또는 MariaDB 애플리케이션에 최적화되었습니다.

PHP 8.0+, 안전한 데이터베이스 접근을 위한 PDO, RESTful API 설계, 그리고 공식 PHP 문서(https://php.net)에 따른 XAMPP 환경 구성에 대한 전문 지침을 통해 고품질 PHP 애플리케이션을 구축하세요.

  • 가능한 경우 기본 병렬 하위 에이전트 디스패치와 200k+ 컨텍스트 윈도우를 활용하세요.

크로스 클라이언트 이식성

이 스킬은 GitHub Copilot, Claude Code, Codex에서 사용할 수 있도록 작성되었습니다.

  • GitHub Copilot: 폴더를 Copilot이 인식 가능한 스킬 경로에 배치하거나, 폴더 검색이 불가능한 경우 워크플로우를 프로젝트 지침에 포함시키세요.
  • Claude Code: 폴더를 로컬 스킬 디렉토리 또는 호환 가능한 플러그인 소스에 배치하세요.
  • Codex: 폴더를 $CODEX_HOME/skills/php-development에 설치하거나 동기화하고, 주요 변경 후 Codex를 재시작하세요.

MCP 가용성 및 폴백

선호 MCP 서버: 필요 없음

  • 폴백 프롬프트: "MCP 없이 PHP 개발 스킬을 사용하세요. 로컬 명령어, 번들 리소스, 표준 셸 또는 편집기 도구, 직접 검증에 의존하세요. 결론을 내리기 전에 사용된 증거를 보여주세요."
  • 활성 호스트가 MCP를 노출하지 않는 경우 MCP 작업이 사용되었다고 주장하지 마세요.
  • 로컬 파일, 테스트, 렌더링된 출력, 로그 또는 스크린샷을 폴백 증거 경로로 취급하세요.

안티 패턴

  • SQL 직접 인터폴레이션: PHP 데이터 접근의 정확성과 보안을 위해 Prepared Statement가 기준입니다.
  • 요청 파싱, 비즈니스 규칙, 렌더링 혼합: 결합도가 높은 스크립트는 테스트가 어렵고 API로 발전시키기 어렵습니다.
  • 검증만으로 XSS를 방지한다고 가정: 사용자 제어 콘텐츠가 HTML로 렌더링될 때 출력 인코딩이 여전히 중요합니다.

검증 프로토콜

"스킬 적용 성공"을 주장하기 전에:

  1. 통과/실패: PHP 개발 구현이 대상 런타임, 프레임워크 버전 및 영향받는 파일을 지정합니다.
  2. 통과/실패: 변경된 부분에 대해 빌드, 린트, 테스트 또는 이에 상응하는 로컬 검증이 실행됩니다.
  3. 통과/실패: 오류, 종속성 드리프트 및 환경 차이에 대한 엣지 케이스가 처리되거나 명시적으로 범위를 벗어난 것으로 표시됩니다.
  4. 압박 테스트 시나리오: 해피 패스 테스트를 통과하지만 하나의 경계 조건에서 실패하는 변경에 워크플로우를 적용합니다.
  5. 성공 메트릭: 테스트되지 않은 성공 주장이 없어야 합니다. 모든 구현 주장은 명령 또는 아티팩트에 매핑됩니다.

전후 예시

<?php
// Before
$stmt = $pdo->query("SELECT * FROM users WHERE email = '$email'");
$user = $stmt->fetch();

// After
$stmt = $pdo->prepare('SELECT id, email, password_hash FROM users WHERE email = :email LIMIT 1');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

문자열 인터폴레이션을 Prepared Statement로 대체하고 결과 형태를 좁혔습니다.

활성화 조건

증상 -> 작업 트리거 사용: 일치하는 항목이 있으면 이 스킬을 적용하고 아래 프로토콜로 검증하세요.

핵심 PHP 개발:

  • 적절한 HTTP 메서드를 사용한 PHP RESTful API 구축
  • XAMPP(Apache + MySQL + PHP) 환경 작업
  • PDO를 사용한 안전한 데이터베이스 작업 구현
  • 인증 및 세션 관리 시스템 생성
  • 파일 업로드 및 양식 제출 처리

데이터베이스 및 데이터 계층:

  • PDO를 사용한 PHP와 MySQL/MariaDB 연결
  • SQL 인젝션 방지를 위한 Prepared Statement 작성
  • 데이터 무결성을 위한 트랜잭션 처리 구현
  • 데이터 접근을 위한 리포지토리 패턴 생성
  • MySQLi와 PDO 비교 작업

보안 및 모범 사례:

  • 비밀번호 해싱(password_hash, password_verify) 구현
  • XSS, CSRF 및 SQL 인젝션 방지
  • 사용자 입력 검증 및 정화
  • 세션 및 인증 토큰 관리
  • API 접근을 위한 CORS 헤더 구성

API 개발:

  • 적절한 HTTP 상태 코드를 사용한 RESTful 엔드포인트 설계
  • JSON 요청 및 응답 처리
  • 인증 및 권한 부여를 위한 미들웨어 구현
  • 오류 처리 및 로깅
  • 속도 제한 및 API 버전 관리

파트 1: PHP 8.0+ 기초

최신 PHP 기능

<?php
// Named arguments (PHP 8.0+)
function createUser(string $name, string $email, bool $isAdmin = false): User {
    return new User($name, $email, $isAdmin);
}

// Call with named arguments
$user = createUser(email: '[email protected]', name: 'John Doe');

// Union types (PHP 8.0+)
function processValue(string|int|float $value): string {
    return (string)$value;
}

// Nullsafe operator (PHP 8.0+)
$country = $session?->user?->address?->country ?? 'Unknown';

// Constructor property promotion (PHP 8.0+)
class User {
    public function __construct(
        public string $name,
        public string $email,
        private string $passwordHash
    ) {}
}

타입 선언 및 엄격한 타입

<?php
declare(strict_types=1); // Enforce type safety

// Typed properties and return types
class Recipe {
    private int $id;
    private string $title;
    private ?DateTime $createdAt;

    public function __construct(int $id, string $title) {
        $this->id = $id;
        $this->title = $title;
    }

    public function getTitle(): string {
        return $this->title;
    }

    public function setCreatedAt(?DateTime $date): void {
        $this->createdAt = $date;
    }
}

// Union and intersection types
function processData(string|array $data): string|int {
    return is_array($data) ? count($data) : strlen($data);
}

파트 2: PDO 데이터베이스 통합

데이터베이스 연결 클래스

<?php
class Database {
    private static ?PDO $instance = null;

    public static function getInstance(): PDO {
        if (self::$instance === null) {
            $host = $_ENV['DB_HOST'] ?? 'localhost';
            $dbname = $_ENV['DB_NAME'] ?? 'recipe_sharing_system';
            $username = $_ENV['DB_USER'] ?? 'root';
            $password = $_ENV['DB_PASSWORD'] ?? '';
            $charset = 'utf8mb4';

            $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";

            try {
                self::$instance = new PDO($dsn, $username, $password, [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]);
            } catch (PDOException $e) {
                error_log("Database connection failed: " . $e->getMessage());
                throw new RuntimeException("Database connection error");
            }
        }

        return self::$instance;
    }
}

보안을 위한 Prepared Statement

<?php
class UserRepository {
    private PDO $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    // Find user by email with prepared statement
    public function findByEmail(string $email): ?array {
        $stmt = $this->db->prepare(
            "SELECT id, email, password_hash, role, status
             FROM user
             WHERE email = :email LIMIT 1"
        );

        $stmt->bindParam(':email', $email, PDO::PARAM_STR);
        $stmt->execute();

        $user = $stmt->fetch();
        return $user ?: null;
    }

    // Create new user with password hashing
    public function create(string $name, string $email, string $password): int {
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $this->db->prepare(
            "INSERT INTO user (name, email, password_hash, role, status, created_at, updated_at)
             VALUES (:name, :email, :password_hash, 'user', 'active', NOW(), NOW())"
        );

        $stmt->bindParam(':name', $name, PDO::PARAM_STR);
        $stmt->bindParam(':email', $email, PDO::PARAM_STR);
        $stmt->bindParam(':password_hash', $passwordHash, PDO::PARAM_STR);

        $stmt->execute();

        return (int) $this->db->lastInsertId();
    }

    // Authentication with password verification
    public function authenticate(string $email, string $password): ?array {
        $user = $this->findByEmail($email);

        if ($user === null) {
            return null;
        }

        if (!password_verify($password, $user['password_hash'])) {
            return null;
        }

        // Check if password needs rehash
        if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
            $newHash = password_hash($password, PASSWORD_DEFAULT);
            $this->updatePasswordHash($user['id'], $newHash);
        }

        unset($user['password_hash']); // Remove sensitive data
        return $user;
    }

    private function updatePasswordHash(int $userId, string $hash): void {
        $stmt = $this->db->prepare(
            "UPDATE user SET password_hash = :hash WHERE id = :id"
        );
        $stmt->execute([':hash' => $hash, ':id' => $userId]);
    }
}

트랜잭션 관리

<?php
class RecipeService {
    private PDO $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    // Create recipe with ingredients, instructions, and images in a transaction
    public function createRecipeWithDetails(array $recipeData, array $ingredients, array $instructions): int {
        try {
            $this->db->beginTransaction();

            // Insert recipe
            $stmt = $this->db->prepare(
                "INSERT INTO recipe (title, description, category, difficulty, prep_time, cook_time, servings, author_id, status, created_at, updated_at)
                 VALUES (:title, :description, :category, :difficulty, :prep_time, :cook_time, :servings, :author_id, 'pending', NOW(), NOW())"
            );

            $stmt->execute([
                ':title' => $recipeData['title'],
                ':description' => $recipeData['description'],
                ':category' => $recipeData['category'],
                ':difficulty' => $recipeData['difficulty'],
                ':prep_time' => $recipeData['prepTime'],
                ':cook_time' => $recipeData['cookTime'],
                ':servings' => $recipeData['servings'],
                ':author_id' => $recipeData['authorId'],
            ]);

            $recipeId = (int) $this->db->lastInsertId();

            // Insert ingredients
            $ingredientStmt = $this->db->prepare(
                "INSERT INTO ingredient (recipe_id, name, quantity, unit, sort_order, created_at, updated_at)
                 VALUES (:recipe_id, :name, :quantity, :unit, :sort_order, NOW(), NOW())"
            );

            foreach ($ingredients as $index => $ingredient) {
                $ingredientStmt->execute([
                    ':recipe_id' => $recipeId,
                    ':name' => $ingredient['name'],
                    ':quantity' => $ingredient['quantity'],
                    ':unit' => $ingredient['unit'],
                    ':sort_order' => $index,
                ]);
            }

            // Insert instructions
            $instructionStmt = $this->db->prepare(
                "INSERT INTO instruction (recipe_id, step_number, instruction_text, created_at, updated_at)
                 VALUES (:recipe_id, :step_number, :instruction_text, NOW(), NOW())"
            );

            foreach ($instructions as $index => $instruction) {
                $instructionStmt->execute([
                    ':recipe_id' => $recipeId,
                    ':step_number' => $index + 1,
                    ':instruction_text' => $instruction['text'],
                ]);
            }

            $this->db->commit();

            return $recipeId;

        } catch (Exception $e) {
            $this->db->rollBack();
            error_log("Failed to create recipe: " . $e->getMessage());
            throw $e;
        }
    }
}

파트 3: RESTful API 개발

JSON 응답 헬퍼

<?php
class Response {
    public static function json(mixed $data, int $statusCode = 200): never {
        http_response_code($statusCode);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
        exit;
    }

    public static function error(string $message, int $statusCode = 400): never {
        self::json([
            'success' => false,
            'error' => $message,
        ], $statusCode);
    }

    public static function success(mixed $data = null, string $message = 'Success'): never {
        self::json([
            'success' => true,
            'message' => $message,
            'data' => $data,
        ]);
    }
}

CORS 미들웨어

<?php
// Handle CORS headers
$allowedOrigins = [
    'http://localhost:5173', // Vite dev server
    'http://localhost:3000',  // Alternative dev server
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (in_array($origin, $allowedOrigins, true)) {
    header("Access-Control-Allow-Origin: $origin");
}

header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

인증 미들웨어

<?php
function requireAuth(): array {
    $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';

    if (!preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
        Response::error('Unauthorized: Missing or invalid token', 401);
    }

    $token = $matches[1];

    // Validate token (example withJWT)
    try {
        $payload = JWT::decode($token, $_ENV['JWT_SECRET'], ['HS256']);
        return (array) $payload;
    } catch (Exception $e) {
        Response::error('Unauthorized: Invalid token', 401);
    }
}

function requireAdmin(): array {
    $user = requireAuth();

    if ($user['role'] !== 'admin') {
        Response::error('Forbidden: Admin access required', 403);
    }

    return $user;
}

파트 4: 오류 처리 및 로깅

전역 예외 핸들러

<?php
function exceptionHandler(Throwable $exception): void {
    error_log(sprintf(
        "Uncaught %s: %s in %s on line %d",
        get_class($exception),
        $exception->getMessage(),
        $exception->getFile(),
        $exception->getLine()
    ));

    $statusCode = ($exception instanceof HttpException) ? $exception->getStatusCode() : 500;
    $message = $_ENV['APP_ENV'] === 'production' ? 'Internal Server Error' : $exception->getMessage();

    Response::error($message, $statusCode);
}

set_exception_handler('exceptionHandler');

입력 검증 예시

<?php
trait ValidationTrait {
    public function validateEmail(string $email): bool {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }

    public function sanitizeString(string $input): string {
        return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
    }

    public function validateRecipeData(array $data): array {
        $errors = [];

        if (empty($data['title']) || strlen($data['title']) > 255) {
            $errors['title'] = 'Title is required and must be under 255 characters';
        }

        if (!in_array($data['category'] ?? null, ['appetizer', 'main', 'dessert'], true)) {
            $errors['category'] = 'Invalid category';
        }

        return $errors;
    }
}

파트 5: 배포 및 모범 사례

Composer 설정

{
    "name": "your-app/recipe-sharing",
    "require": {
        "php": ">=8.0",
        "ext-pdo": "*",
        "ext-mbstring": "*"
    },
    "require-dev": {
        "phpunit/phpunit": "^11.0",
        "phpstan/phpstan": "^1.10"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

환경 변수 (.env)

DB_HOST=localhost
DB_NAME=recipe_sharing_system
DB_USER=root
DB_PASSWORD=
JWT_SECRET=your-secret-key-change-in-production
APP_ENV=development

XAMPP 구성 (php.ini 권장)

; Error reporting
error_reporting = E_ALL
display_errors = On
display_startup_errors = On

; File uploads
upload_max_filesize = 10M
post_max_size = 12M

; Session
session.use_strict_mode = 1
session.cookie_httponly = 1
session.cookie_secure = 1

; Timezone
date.timezone = UTC

요약

이 PHP 개발 스킬은 PHP 8.0+ 애플리케이션을 구축하기 위한 모범 사례, 코드 예시 및 구성을 제공합니다. 핵심 주제는 다음과 같습니다:

  • PDO를 포함한 보안 데이터베이스 접근 및 Prepared Statement
  • RESTful API 설계 및 JSON 응답
  • 인증 및 권한 부여 (비밀번호 해싱, JWT)
  • 오류 처리 및 로깅
  • XAMPP 환경 설정

적절한 HTTP 메서드, 상태 코드 및 미들웨어를 사용하여 모든 API 엔드포인트를 구성하세요. SQL 인젝션을 방지하기 위해 PDO에서 항상 Prepared Statement를 사용하고, 안전한 비밀번호 저장을 위해 password_hash()를 사용하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

mianhtsys/landingMod3

Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.

mianhtsys/landingMod3

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

mianhtsys/landingMod3

Diseña y compara alternativas arquitectónicas trazables a RF/RNF sin implementar código.

mianhtsys/landingMod3

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.

mianhtsys/landingMod3

Revisión adversarial de la arquitectura contra RF/RNF, detectando contradicciones, cobertura faltante y complejidad innecesaria.

mianhtsys/landingMod3

Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.

mianhtsys/landingMod3

>- Generate grounded-and-verified, engine-agnostic database documentation that reaches 100% parity with the real schema. Introspects the LIVE database as ground truth and cross-validates it against ORM models, migrations, generated types, seeds, and application queries, then proves completeness by diffing the docs back against the database. Produces ER diagrams (mermaid), per-table data dictionaries, and a machine-readable schema.json. Works with PostgreSQL, MySQL, SQL Server, and SQLite across any ORM (Prisma, TypeORM, Drizzle, Sequelize, Knex, Django, Rails) or raw SQL. Use when asked to document a database, produce an ERD or data dictionary, write db/schema docs, audit schema drift, or refresh existing DB docs.

mianhtsys/landingMod3

Compara estrategias de persistencia y motores de datos según consistencia, concurrencia, volumen, recuperación y operación.

mianhtsys/landingMod3

Design robust, scalable database schemas for SQL and NoSQL databases. Provides normalization guidelines, indexing strategies, migration patterns, constraint design, and performance optimization. Ensures data integrity, query performance, and maintainable data models.

mianhtsys/landingMod3

Consolida análisis especializados en una recomendación arquitectónica, matriz de decisión, ADR y plan de validación.

mianhtsys/landingMod3

Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.

mianhtsys/landingMod3

Build and maintain web frontends — component architecture, state management, API integration, responsive layout, client-side performance, and frontend testing patterns. Framework agnostic, focused on web frontend implementation. Do not use for backend service implementation, data engineering, or platform infrastructure work.

mianhtsys/landingMod3

Evalúa despliegue, contenedores, escalado, alta disponibilidad, observabilidad, backup, recuperación y CI/CD de forma proporcional.

mianhtsys/landingMod3

Execute read-only SQL queries against multiple Microsoft SQL Server databases. Use when: (1) querying MSSQL/SQL Server databases, (2) exploring database schemas/tables, (3) running SELECT queries for data analysis, (4) checking database contents. Supports multiple database connections with descriptions for intelligent auto-selection. Blocks all write operations (INSERT, UPDATE, DELETE, DROP, etc.) for safety.

mianhtsys/landingMod3

Generate and maintain OpenAPI 3.1 specifications from code, design-first specs, and validation patterns. Use when creating API documentation, generating SDKs, or ensuring API contract compliance.

mianhtsys/landingMod3

Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features

mianhtsys/landingMod3

Analiza requisitos funcionales y no funcionales, reglas, restricciones, capacidad y ambigüedades antes de seleccionar tecnologías.

mianhtsys/landingMod3

Implement modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first breakpoint strategies. Use when building adaptive interfaces, implementing fluid layouts, or creating component-level responsive behavior.

mianhtsys/landingMod3

>- Use when designing or implementing software securely: define security requirements, threat-model a feature, choose secure defaults, design authentication and authorization, handle untrusted data and secrets, evaluate dependencies, design multi-tenant trust boundaries, or review security-sensitive changes. Use for prevention during requirements, design, implementation, and review; not for post-build security assessments or scanning an existing codebase.

mianhtsys/landingMod3

Revisa seguridad arquitectónica, identidad, autorización, secretos, APIs, auditoría, fraude y resiliencia antes de implementar.

관련 스킬