Php License Key System Github Apr 2026
// Authentication check (you should implement proper auth) $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? null; if ($apiKey !== 'your-admin-api-key') { http_response_code(401); echo json_encode(['error' => 'Unauthorized']); exit; }
/** * Create a unique license key */ private function createLicenseKey($productId) { $prefix = strtoupper(substr(preg_replace('/[^a-zA-Z0-9]/', '', $productId), 0, 4)); $uniqueId = uniqid() . bin2hex(random_bytes(8)); $hash = hash_hmac('sha256', $uniqueId . LICENSE_SALT, SECRET_KEY); $licenseKey = $prefix . '-' . strtoupper(substr($hash, 0, 8)) . '-' . strtoupper(substr($hash, 8, 8)) . '-' . strtoupper(substr($hash, 16, 8)); // Check for uniqueness $checkSql = "SELECT id FROM licenses WHERE license_key = :license_key"; $checkStmt = $this->db->prepare($checkSql); $checkStmt->execute([':license_key' => $licenseKey]); if ($checkStmt->rowCount() > 0) { return $this->createLicenseKey($productId); // Recursive retry } return $licenseKey; }
-- License logs table CREATE TABLE IF NOT EXISTS license_logs ( id INT AUTO_INCREMENT PRIMARY KEY, license_id INT, action VARCHAR(50), details TEXT, ip_address VARCHAR(45), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_license_id (license_id), INDEX idx_action (action), INDEX idx_created_at (created_at) ); <?php // config/database.php define('DB_HOST', 'localhost'); define('DB_NAME', 'license_system'); define('DB_USER', 'your_username'); define('DB_PASS', 'your_password');
/** * Validate domain */ private function validateDomain($licenseId, $domain) { $sql = "SELECT COUNT(*) as count FROM license_domains WHERE license_id = :license_id AND domain = :domain"; $stmt = $this->db->prepare($sql); $stmt->execute([ ':license_id' => $licenseId, ':domain' => $domain ]); $result = $stmt->fetch(); return $result['count'] > 0; } php license key system github
/** * Update last validated timestamp */ private function updateLastValidated($licenseId) { $sql = "UPDATE licenses SET last_validated_at = NOW() WHERE id = :id"; $stmt = $this->db->prepare($sql); $stmt->execute([':id' => $licenseId]); }
/** * Validate a license key */ public function validate($licenseKey, $domain = null, $activationCode = null) { // Get license details $license = $this->getLicense($licenseKey); if (!$license) { return ['valid' => false, 'error' => 'Invalid license key']; } // Check status if ($license['status'] !== 'active') { return ['valid' => false, 'error' => "License is {$license['status']}"]; } // Check expiry if ($license['expires_at'] && strtotime($license['expires_at']) < time()) { $this->updateLicenseStatus($license['id'], 'expired'); return ['valid' => false, 'error' => 'License has expired']; } // Validate domain if provided if ($domain && !$this->validateDomain($license['id'], $domain)) { return ['valid' => false, 'error' => 'Domain not authorized for this license']; } // Validate activation if provided if ($activationCode && !$this->validateActivation($license['id'], $activationCode)) { return ['valid' => false, 'error' => 'Invalid activation code']; } // Update last validated timestamp $this->updateLastValidated($license['id']); // Log validation $this->logValidation($license['id'], $domain); return [ 'valid' => true, 'license_type' => $license['license_type'], 'expires_at' => $license['expires_at'], 'max_domains' => $license['max_domains'], 'customer_name' => $license['customer_name'], 'customer_email' => $license['customer_email'] ]; }
public function prepare($sql) { return $this->connection->prepare($sql); } // Authentication check (you should implement proper auth)
class LicenseValidator { private $db;
public function lastInsertId() { return $this->connection->lastInsertId(); } } <?php // src/LicenseGenerator.php require_once DIR . '/Database.php';
/** * Generate a unique license key */ public function generateLicenseKey($productId, $customerName, $customerEmail, $licenseType, $maxDomains = 1, $expiryDays = null) { // Generate unique license key $licenseKey = $this->createLicenseKey($productId); // Calculate expiry date $expiresAt = null; if ($expiryDays !== null) { $expiresAt = date('Y-m-d H:i:s', strtotime("+{$expiryDays} days")); } elseif ($licenseType !== 'perpetual') { $duration = $licenseType === 'trial' ? 30 : ($licenseType === 'monthly' ? 30 : 365); $expiresAt = date('Y-m-d H:i:s', strtotime("+{$duration} days")); } // Insert into database $sql = "INSERT INTO licenses (license_key, product_id, customer_name, customer_email, license_type, max_domains, expires_at) VALUES (:license_key, :product_id, :customer_name, :customer_email, :license_type, :max_domains, :expires_at)"; $stmt = $this->db->prepare($sql); $stmt->execute([ ':license_key' => $licenseKey, ':product_id' => $productId, ':customer_name' => $customerName, ':customer_email' => $customerEmail, ':license_type' => $licenseType, ':max_domains' => $maxDomains, ':expires_at' => $expiresAt ]); // Log the action $this->logAction($this->db->lastInsertId(), 'license_generated', "License generated for {$customerEmail}"); return [ 'license_key' => $licenseKey, 'expires_at' => $expiresAt, 'license_type' => $licenseType ]; } LICENSE_SALT, SECRET_KEY); $licenseKey = $prefix
echo json_encode($result); <?php // public/example-client.php class LicenseClient { private $apiUrl; private $licenseKey; private $domain; private $activationCode; private $cacheFile;
/** * Cache validation result */ private function cacheValidation($data) { file_put_contents($this->cacheFile, json_encode([ 'timestamp' => time(), 'data' => $data ])); }
/** * Check if license is valid */ public function checkLicense() { // Check cache first $cached = $this->getCachedValidation(); if ($cached && $cached['timestamp'] > (time() - 86400)) { // 24 hour cache return $cached['data']; } // Validate with server $result = $this->validateWithServer(); if ($result['valid']) { $this->cacheValidation($result); } return $result; }








