', '#', '+', '-', '=', '|', '{', '}', '.', '!']; foreach ($specialChars as $char) { $text = str_replace($char, '\\'.$char, $text); } return $text; } /** * ตรวจสอบความปลอดภัยของ file path */ public static function securePath($path) { // ป้องกัน directory traversal $path = str_replace(['../', '.\\', '..\\'], '', $path); $path = preg_replace('/[^a-zA-Z0-9_\-\/\.]/', '', $path); return $path; } /** * สร้าง hash สำหรับการเข้ารหัสข้อมูล */ public static function generateHash($data) { return hash('sha256', $data.(defined('SECURITY_SALT') ? SECURITY_SALT : 'default_salt')); } /** * ตรวจสอบความแข็งแรงของข้อมูล */ public static function validateInput($input, $type, $minLength = 1, $maxLength = 255) { if (empty($input) || strlen($input) < $minLength || strlen($input) > $maxLength) { return false; } switch ($type) { case 'name': // ตรวจสอบว่ามีเฉพาะอักษรที่อนุญาต return preg_match('/^[a-zA-Zก-๙\s\.\-]+$/u', $input); case 'email': return filter_var($input, FILTER_VALIDATE_EMAIL) !== false; case 'text': // ตรวจสอบว่าไม่มี control characters อันตราย return !preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', $input); default: return true; } } /** * Log security events */ public static function logSecurityEvent($event, $userId = null, $details = []) { $logFile = __DIR__.'/../../logs/security.log'; $timestamp = date('Y-m-d H:i:s'); $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown'; $logEntry = [ 'timestamp' => $timestamp, 'event' => $event, 'user_id' => $userId, 'ip' => $ip, 'details' => $details ]; if (!file_exists(dirname($logFile))) { mkdir(dirname($logFile), 0755, true); } file_put_contents($logFile, json_encode($logEntry)."\n", FILE_APPEND | LOCK_EX); } }