Snilld

php-best-practices

php-best-practices

Ensures 100% correct PHP code following industry best practices (PSR standards), security standards, and project-specific patterns. Use when writing or modifying PHP files in assets/php/.

# PHP Best Practices

Ensures flawless PHP code following industry standards (PSR), security best practices, and Creatures & Chronicles project-specific patterns.

## When to Use

- Writing new PHP files in `assets/php/`
- Modifying existing PHP files
- Implementing AJAX endpoints
- Database operations
- User authentication and session management
- Error handling and logging
- Before committing PHP changes

## Core Principles

1. **Security First** - Always validate input, use prepared statements, protect against CSRF
2. **Consistent Patterns** - Follow project-specific patterns (db-connection.php, logPhpError, CSRF)
3. **Error Handling** - Always handle errors gracefully with proper logging
4. **Code Quality** - Follow PSR standards for readability and maintainability
5. **Documentation** - Document all functions with purpose, parameters, and examples

## Overview

For details, templates, and code (file structure, database, security, error handling, AJAX response, PSR, function documentation, common patterns), see **[REFERENCE.md](REFERENCE.md)**.

- **1. File Structure & Organization** – Header template, includes, file layout
- **2. Database Access Patterns** – getDBConnection(), prepared statements, escapeSql
- **3. Security Best Practices** – CSRF, input validation, session, passwords
- **4. Error Handling & Logging** – logPhpError(), try-catch, error responses
- **5. AJAX Response Patterns** – JSON structure, endpoint template
- **6. Code Quality Standards (PSR)** – PSR-1, PSR-12
- **7. Function Documentation** – Docblocks, parameters, examples
- **8. Common Patterns** – Character save, user authentication

## 9. Validation Checklist

**Before committing, verify:**

✅ **Security:**
- [ ] CSRF token validated (for POST/PUT/DELETE)
- [ ] Input validated and sanitized
- [ ] SQL injection prevented (prepared statements or escapeSql)
- [ ] Passwords hashed (if applicable)
- [ ] Session security configured

✅ **Database:**
- [ ] Using `getDBConnection()` from includes
- [ ] Connection closed with `closeDBConnection()`
- [ ] SQL queries use prepared statements or `escapeSql()`
- [ ] Error handling for database operations

✅ **Error Handling:**
- [ ] Try-catch blocks for risky operations
- [ ] Using `logPhpError()` for logging
- [ ] Proper HTTP status codes
- [ ] JSON error responses for AJAX

✅ **Code Quality:**
- [ ] PSR-1 naming conventions followed
- [ ] Functions documented with docblocks
- [ ] Proper indentation (4 spaces)
- [ ] No hardcoded credentials

✅ **Headers:**
- [ ] Content-Type set (application/json for AJAX)
- [ ] CORS headers set (if needed)
- [ ] Proper HTTP status codes

## 10. Common Errors to Avoid

❌ **SQL Injection:**
```php
// WRONG
$sql = "SELECT * FROM users WHERE id = " . $_POST['id'];
```

❌ **Missing CSRF Protection:**
```php
// WRONG - No CSRF validation
if ($_POST['action'] === 'delete') {
// Delete operation
}
```

❌ **Plaintext Passwords:**
```php
// WRONG
$sql = "INSERT INTO users (password) VALUES ('" . $_POST['password'] . "')";
```

❌ **Missing Error Handling:**
```php
// WRONG
$conn = getDBConnection();
$result = $conn->query($sql);
// No error checking
```

❌ **Exposing Errors to Users:**
```php
// WRONG
echo "Error: " . $e->getMessage(); // Exposes internal details
```

❌ **Missing Input Validation:**
```php
// WRONG
$username = $_POST['username']; // No validation
```

## 11. Remember

- **Security first** - Always validate input, use CSRF protection, prevent SQL injection
- **Use project patterns** - db-connection.php, logPhpError, CSRF protection
- **Handle errors** - Try-catch blocks, proper logging, user-friendly messages
- **Follow PSR standards** - Consistent code style, proper naming, documentation
- **Test thoroughly** - Verify security, error handling, edge cases
- **Document everything** - Functions, complex logic, non-obvious decisions

## 12. File Locations Reference

- **Database utilities:** `assets/php/includes/db-connection.php`
- **CSRF protection:** `assets/php/includes/csrf-protection.php`
- **Error logging:** `assets/php/error-logging/auto_include.php`
- **Main PHP files:** `assets/php/`
- **Error logs:** `M:\rpg` (network drive)

---

**Goal:** Every PHP file must be secure, well-documented, follow best practices, and use project-specific patterns consistently.

    Gør brugeroplevelsen bedre.
    Hvilket firma arbejder du for?