Skip to content

sayborok/php-security-core

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PHP Security Core

A lightweight, standalone, and robust security class for PHP 8.x projects.

License: MIT PHP Version

Developed by sayborok, this library provides a comprehensive suite of security tools to protect your PHP applications against common vulnerabilities. It is designed to be drop-in ready, framework-agnostic, and follow PSR-4 standards.


🚀 Features

  • SQL Injection Protection: Secure PDO wrapper with automatic prepared statements and strict type binding.
  • XSS Sanitization: Input/Output cleaning with strict HTML5 entity encoding.
  • CSRF Protection: Secure token generation, validation, and expiration.
  • Password Security: Built-in helpers for modern password hashing (Argon2id/Bcrypt).
  • Secure Sessions: Anti-hijacking (User-Agent binding), secure cookie params (HttpOnly, SameSite), and automatic ID regeneration.
  • Encryption: Secure data storage using AES-256-GCM (Authenticated Encryption).
  • Signed URLs: HMAC-SHA256 protected temporary URLs with expiration.
  • Directory Traversal Protection: Path sanitization to prevent unauthorized file access.
  • XXE Protection: Safe XML loading with external entity loading disabled.
  • UUID Generation: Cryptographically secure Version 4 UUIDs.
  • Spam Prevention: Built-in Honeypot and Session-based Rate Limiting.
  • Secure File Uploads: MIME-type validation, extension whitelisting, and filename randomization.
  • Input Validation: Helpers for Emails, URLs, IPs, etc.
  • Security Logging: Automatic logging of daily security events.
  • Security Headers: Automated injection of X-Frame-Options, HSTS, X-Content-Type-Options.

📦 Installation

You can install this package via Composer:

composer require sayborok/php-security-core

Or simply download the src/Security.php file and include it in your project.


🛠 Usage

1. Initialization & Secure Session

use SecurityCore\Security;

// Starts session with HttpOnly, Strict, and Secure cookies
Security::secureSessionStart();

// Send security headers (HSTS, Clickjacking protection, etc.)
Security::secureHeaders();

// Optional: Check for session hijacking
try {
    Security::checkSessionHijacking();
} catch (Exception $e) {
    die("Session invalid: " . $e->getMessage());
}

2. Password Security

// Hashing a password
$hash = Security::hashPassword('user_password');

// Verification
if (Security::verifyPassword('user_password', $hash)) {
    // Access granted
}

3. Signed URLs (HMAC)

$key = 'your-secret-key';
$baseUrl = 'https://example.com/download?file=report.pdf';

// Generate a signed link valid for 5 minutes
$signedUrl = Security::generateSignedUrl($baseUrl, $key, 300);

// Validate in the receiving controller
if (Security::validateSignedUrl($_SERVER['REQUEST_URI'], $key)) {
    // Valid and not expired
}

4. Database Queries (SQLi Protection)

$sql = "SELECT * FROM users WHERE email = :email AND status = :status";
$params = [
    'email' => $userInput,
    'status' => 1
];

// Auto-prepares and binds types dynamically
$stmt = Security::dbQuery($pdo, $sql, $params);
$user = $stmt->fetch();

5. Path & XML Security

// Prevent Directory Traversal
$safePath = Security::sanitizePath($_GET['file']); // Strips ../ segments

// Prevent XXE Attacks
$xml = Security::safeLoadXml($unsafeXmlString); // Disables external entities

6. Encryption (AES-256-GCM)

$key = 'YOUR_32_BYTE_SECRET_KEY'; // Use random_bytes(32) to generate
$encrypted = Security::encrypt("Sensitive Data", $key);
$decrypted = Security::decrypt($encrypted, $key);

7. Spam Prevention & Rate Limiting

// 1. Honeypot
echo Security::honeypot(); 

if (Security::checkHoneypot()) {
    die("Bot Detected!");
}

// 2. Rate Limiting (e.g., 5 attempts / 60 seconds)
if (!Security::rateLimit('login_attempt', 5, 60)) {
    die("Too many requests.");
}

📝 License

This project is open-sourced software licensed under the MIT license.

About

A lightweight, standalone PHP 8.2+ security class providing robust protection against SQLi, XSS, CSRF, Password Attacks, Directory Traversal, XXE, and more. PSR-4 compliant and framework-agnostic.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages