Skip to main content

🐘 PHP Code Examples

<?php

class TKIAuth {
private const API_KEY = 'your-api-key-here';
private const API_URL = 'http://your-domain.com/api/license/auth';
private const PRODUCT = 'MyPHPApp';
private const VERSION = '1.0.0';

private $timeout = 30;

private function getHWID() {
// Generate HWID based on system info
$hwid_parts = [
php_uname('n'), // hostname
php_uname('m'), // machine type
php_uname('s'), // OS name
$_SERVER['HTTP_USER_AGENT'] ?? '',
$_SERVER['SERVER_NAME'] ?? ''
];

$hw_string = implode('-', $hwid_parts);
return 'PHP-' . substr(md5($hw_string), 0, 16);
}

private function getLocalIP() {
// Try to get real IP address
$ip_keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];

foreach ($ip_keys as $key) {
if (!empty($_SERVER[$key])) {
$ip = $_SERVER[$key];
// Handle comma-separated IPs (X-Forwarded-For)
if (strpos($ip, ',') !== false) {
$ip = trim(explode(',', $ip)[0]);
}
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}

return '127.0.0.1';
}

public function authenticate($license_key, $ip = null, $hwid = null) {
$payload = [
'data' => [
'product' => self::PRODUCT,
'version' => self::VERSION,
'licensekey' => $license_key,
'ip' => $ip ?: $this->getLocalIP(),
'hwid' => $hwid ?: $this->getHWID()
]
];

$json_data = json_encode($payload);

$headers = [
'Content-Type: application/json',
'Authorization: ' . self::API_KEY,
'User-Agent: TKI-Auth-PHP/1.0',
'Content-Length: ' . strlen($json_data)
];

$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => implode("\r\n", $headers),
'content' => $json_data,
'timeout' => $this->timeout
]
]);

try {
$response = file_get_contents(self::API_URL, false, $context);

if ($response === false) {
return ['success' => false, 'error' => 'Network error'];
}

$http_code = $this->getHttpResponseCode($http_response_header);
$data = json_decode($response, true);

if ($http_code === 200 && isset($data['status_overview']) && $data['status_overview'] === 'success') {
return [
'success' => true,
'data' => $data,
'user' => $data['discord_username'] ?? 'Unknown',
'expires' => $data['expire_date'] ?? 'Unknown',
'staff_license' => $data['staff_license'] ?? false
];
} else {
return [
'success' => false,
'error' => $data['message'] ?? "HTTP $http_code"
];
}
} catch (Exception $e) {
return ['success' => false, 'error' => $e->getMessage()];
}
}

public function authenticateWithRetry($license_key, $max_retries = 3, $ip = null, $hwid = null) {
$last_error = '';

for ($attempt = 1; $attempt <= $max_retries; $attempt++) {
$result = $this->authenticate($license_key, $ip, $hwid);

if ($result['success']) {
return $result;
}

$last_error = $result['error'];

if ($attempt < $max_retries) {
$wait_time = $attempt * 2; // 2, 4, 6 seconds
echo "Attempt $attempt failed, retrying in {$wait_time}s...\n";
sleep($wait_time);
}
}

return ['success' => false, 'error' => $last_error];
}

private function getHttpResponseCode($headers) {
if (isset($headers[0])) {
preg_match('/HTTP\/\d\.\d (\d+)/', $headers[0], $matches);
return isset($matches[1]) ? (int)$matches[1] : 0;
}
return 0;
}
}

class LicenseManager {
private $auth;
private $license_info = null;
private $is_authenticated = false;
private $license_key = '';

public function __construct() {
$this->auth = new TKIAuth();
}

public function authenticate($license_key) {
echo "Authenticating license...\n";

$result = $this->auth->authenticateWithRetry($license_key);

if ($result['success']) {
$this->is_authenticated = true;
$this->license_info = $result['data'];
$this->license_key = $license_key;

echo "✓ License authenticated!\n";
echo " User: {$result['user']}\n";
echo " Expires: {$result['expires']}\n";
echo " Staff License: " . ($result['staff_license'] ? 'Yes' : 'No') . "\n";

return true;
} else {
echo "✗ Authentication failed: {$result['error']}\n";
return false;
}
}

public function validatePeriodic() {
if (!$this->is_authenticated || empty($this->license_key)) {
return false;
}

$result = $this->auth->authenticate($this->license_key);

if ($result['success']) {
echo "✓ Periodic validation successful\n";
return true;
} else {
echo "⚠ Periodic validation failed: {$result['error']}\n";
$this->onLicenseExpired();
return false;
}
}

private function onLicenseExpired() {
$this->is_authenticated = false;
$this->license_info = null;
echo "License expired or validation failed!\n";
// Implement your logic here
}

public function isAuthenticated() {
return $this->is_authenticated;
}

public function getLicenseInfo() {
return $this->license_info;
}
}

// Console Application Example
class ConsoleApp {
private $license_manager;

public function __construct() {
$this->license_manager = new LicenseManager();
}

public function run() {
echo "Enter license key: ";
$license_key = trim(fgets(STDIN));

if (empty($license_key)) {
echo "No license key provided!\n";
return 1;
}

if (!$this->license_manager->authenticate($license_key)) {
return 1;
}

echo "Starting application...\n";

// Simulate application running with periodic validation
for ($i = 0; $i < 10; $i++) {
if (!$this->license_manager->isAuthenticated()) {
echo "Application stopped due to license issues\n";
return 1;
}

echo "Application is running... (iteration " . ($i + 1) . ")\n";

// Validate license every 5 iterations
if ($i % 5 === 4) {
$this->license_manager->validatePeriodic();
}

sleep(2);
}

echo "Application completed successfully!\n";
return 0;
}
}

// Web Application Example
class WebApp {
private $license_manager;

public function __construct() {
session_start();
$this->license_manager = new LicenseManager();
}

public function handleRequest() {
$action = $_GET['action'] ?? 'login';

switch ($action) {
case 'authenticate':
$this->handleAuthenticate();
break;
case 'logout':
$this->handleLogout();
break;
case 'dashboard':
$this->handleDashboard();
break;
default:
$this->showLogin();
break;
}
}

private function handleAuthenticate() {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$this->redirectToLogin('Invalid request method');
return;
}

$license_key = $_POST['license_key'] ?? '';

if (empty($license_key)) {
$this->redirectToLogin('Please enter a license key');
return;
}

if ($this->license_manager->authenticate($license_key)) {
$_SESSION['authenticated'] = true;
$_SESSION['license_info'] = $this->license_manager->getLicenseInfo();
header('Location: ?action=dashboard');
exit;
} else {
$this->redirectToLogin('Authentication failed');
}
}

private function handleLogout() {
session_destroy();
header('Location: ?action=login');
exit;
}

private function handleDashboard() {
if (!isset($_SESSION['authenticated']) || !$_SESSION['authenticated']) {
$this->redirectToLogin('Not authenticated');
return;
}

$info = $_SESSION['license_info'];

echo "<!DOCTYPE html>
<html>
<head><title>Licensed App Dashboard</title></head>
<body>
<h1>Welcome to Licensed App!</h1>
<p>User: {$info['discord_username']}</p>
<p>Expires: {$info['expire_date']}</p>
<p>Staff License: " . ($info['staff_license'] ? 'Yes' : 'No') . "</p>
<a href='?action=logout'>Logout</a>
</body>
</html>";
}

private function showLogin($error = null) {
$error_msg = $error ? "<p style='color: red;'>$error</p>" : '';

echo "<!DOCTYPE html>
<html>
<head><title>License Authentication</title></head>
<body>
<h1>License Authentication</h1>
<form method='post' action='?action=authenticate'>
<input type='text' name='license_key' placeholder='Enter license key' required>
<button type='submit'>Authenticate</button>
</form>
$error_msg
</body>
</html>";
}

private function redirectToLogin($error) {
header('Location: ?action=login&error=' . urlencode($error));
exit;
}
}

// WordPress Plugin Example
class TKIAuthWordPress {
private $auth;

public function __construct() {
$this->auth = new TKIAuth();
add_action('init', [$this, 'init']);
add_action('wp_ajax_tki_validate', [$this, 'ajaxValidate']);
add_action('wp_ajax_nopriv_tki_validate', [$this, 'ajaxValidate']);
add_shortcode('tki_auth_form', [$this, 'shortcodeAuthForm']);
}

public function init() {
// Plugin initialization
}

public function ajaxValidate() {
check_ajax_referer('tki_auth_nonce', 'nonce');

$license_key = sanitize_text_field($_POST['license_key']);

if (empty($license_key)) {
wp_send_json_error('License key required');
return;
}

$result = $this->auth->authenticate($license_key);

if ($result['success']) {
update_user_meta(get_current_user_id(), 'tki_license_valid', true);
update_user_meta(get_current_user_id(), 'tki_license_info', $result['data']);

wp_send_json_success([
'message' => 'License validated successfully!',
'user' => $result['user'],
'expires' => $result['expires']
]);
} else {
wp_send_json_error($result['error']);
}
}

public function shortcodeAuthForm($atts) {
$nonce = wp_create_nonce('tki_auth_nonce');

return "
<div id='tki-auth-form'>
<input type='text' id='tki-license-key' placeholder='Enter license key'>
<button onclick='validateLicense()'>Validate License</button>
<div id='tki-result'></div>
</div>

<script>
function validateLicense() {
const licenseKey = document.getElementById('tki-license-key').value;
const resultDiv = document.getElementById('tki-result');

if (!licenseKey) {
resultDiv.innerHTML = '<p style=\"color: red;\">Please enter a license key</p>';
return;
}

resultDiv.innerHTML = '<p>Validating...</p>';

fetch('" . admin_url('admin-ajax.php') . "', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'action=tki_validate&license_key=' + encodeURIComponent(licenseKey) + '&nonce=$nonce'
})
.then(response => response.json())
.then(data => {
if (data.success) {
resultDiv.innerHTML = '<p style=\"color: green;\">✓ License validated! User: ' + data.data.user + '</p>';
} else {
resultDiv.innerHTML = '<p style=\"color: red;\">✗ ' + data.data + '</p>';
}
})
.catch(error => {
resultDiv.innerHTML = '<p style=\"color: red;\">Network error</p>';
});
}
</script>";
}
}

// Laravel Controller Example
/*
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class AuthController extends Controller {
private $licenseManager;

public function __construct() {
$this->licenseManager = new LicenseManager();
}

public function showLogin() {
return view('auth.login');
}

public function authenticate(Request $request) {
$request->validate([
'license_key' => 'required|string'
]);

if ($this->licenseManager->authenticate($request->license_key)) {
session([
'authenticated' => true,
'license_info' => $this->licenseManager->getLicenseInfo()
]);

return redirect()->route('dashboard')
->with('success', 'License authenticated successfully!');
}

return back()->withErrors(['license_key' => 'Invalid license key']);
}

public function dashboard() {
if (!session('authenticated')) {
return redirect()->route('login');
}

return view('dashboard', ['info' => session('license_info')]);
}

public function logout() {
session()->flush();
return redirect()->route('login');
}
}
*/

// Usage Examples
if (php_sapi_name() === 'cli') {
// CLI usage
$app = new ConsoleApp();
exit($app->run());
} else {
// Web usage
$app = new WebApp();
$app->handleRequest();
}

// WordPress Plugin usage (in plugin file)
// new TKIAuthWordPress();

?>

Composer Dependencies​

{
"require": {
"php": ">=8.0",
"ext-json": "*",
"ext-curl": "*"
},
"autoload": {
"psr-4": {
"TKIAuth\\": "src/"
}
}
}

cURL Alternative Implementation​

<?php

class TKIAuthCurl extends TKIAuth {
public function authenticate($license_key, $ip = null, $hwid = null) {
if (!extension_loaded('curl')) {
return ['success' => false, 'error' => 'cURL extension not available'];
}

$payload = [
'data' => [
'product' => self::PRODUCT,
'version' => self::VERSION,
'licensekey' => $license_key,
'ip' => $ip ?: $this->getLocalIP(),
'hwid' => $hwid ?: $this->getHWID()
]
];

$ch = curl_init();

curl_setopt_array($ch, [
CURLOPT_URL => self::API_URL,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: ' . self::API_KEY,
'User-Agent: TKI-Auth-PHP-cURL/1.0'
],
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_FOLLOWLOCATION => true
]);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($response === false) {
return ['success' => false, 'error' => "cURL error: $error"];
}

$data = json_decode($response, true);

if ($http_code === 200 && isset($data['status_overview']) && $data['status_overview'] === 'success') {
return [
'success' => true,
'data' => $data,
'user' => $data['discord_username'] ?? 'Unknown',
'expires' => $data['expire_date'] ?? 'Unknown',
'staff_license' => $data['staff_license'] ?? false
];
} else {
return [
'success' => false,
'error' => $data['message'] ?? "HTTP $http_code"
];
}
}
}

?>