To activate and check keys you’ll need to add a few simple code snippet to your app. We have written a multitude of documents on how to do this step by step, but let’s summarize and give some easy to use code examples.
Your app will need a few key pieces of functionality:
- A form to activate keys
- An automated key check every day (or on startup)
- An activation/deactivate function for your app
With only those three pieces of code your app will be protected. Let’s go over each one in detail and provide some example code.
But first, here’s a few notes about this page:
The below examples are in PHP for a web app, such as a WordPress plugin or theme, etc., but our license key system works in any language and for any type of app, even game engines.
To be as compatible as possible, we will avoid using external libraries in this example and focus on using built-in PHP functions, such a cURL.
We’ve previously documented many ways to do the below steps in other languages, including inside popular game engines, in the rest of our documentation.
Feel free to adjust the below code to better suit your needs, and remember to test everything before going live.
1. Form To Activate Keys #
After you’ve generated your keys you will need a way for your users to activate them. This is done with a simple form inside your app.
Please note that it’s a standard security practice to put sensitive data, like your API access token and the API URL, inside a separate file, so we’ll assume you have done this. For this example we use a .env file to accomplish this.
Here’s the example .env file we’re using if you would like to use it for your own project:
.Env file #
// .ENV file to hold sensitive information that shouldn't be directly coded
BASE_URL=https://batchkeys.com/api.php // Our API URL where you'll send the API call
AUTH_KEY=000000000000000000 // Your API authorization key, be sure to update this!
Activation_Form.php #
<?php
// activation_form.php
// Load and parse the .env file
$envPath = __DIR__ . '.env'; // Location of your .env file
// Fetch data from the .env file
if (file_exists($envPath)) {
$env = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($env as $line) {
list($name, $value) = explode('=', $line, 2);
$_ENV[$name] = $value;
}
} else {
echo "Error: .env file not found.";
exit;
}
// Get the base URL and API authentication key from the environment variables
$baseUrl = $_ENV['BASE_URL'];
$authKey = $_ENV['AUTH_KEY'];
// Ready necessary variables
$result = ''; // Variable to hold the response results from the API
$validKey = null; // Variable to hold the validity of the license key
// Check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['licenseKey'])) {
// Set license key variable from the form
$licenseKey = $_POST['licenseKey'];
// Initialize cURL session
$ch = curl_init($baseUrl);
// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'auth: ' . $authKey,
'key: ' . $licenseKey,
'domain: ' . $_SERVER['HTTP_HOST']
));
// Execute cURL session
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
$result = 'cURL error: ' . curl_error($ch);
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >= 200 && $httpCode < 300) {
// Decode the JSON response
$responseData = json_decode($response, true);
if ($responseData && isset($responseData['valid'])) {
$validKey = $responseData['valid'] == '1'; // Check if 'valid' is '1'
// Save to a local file if the key is valid
if ($validKey) {
$dataToSave = "<?php\n// Valid License Key\n\$licenseKey = '{$licenseKey}';\n\$valid = {$responseData['valid']};\n?>";
file_put_contents('valid.php', $dataToSave);
}
}
} else {
$result = "HTTP error: " . $httpCode;
}
}
// Close cURL session
curl_close($ch);
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && $validKey === false): ?>
<p>The license key is invalid. Please try again.</p>
<?php endif; ?>
<form action="" method="post">
<input type="text" id="licenseKey" name="licenseKey" placeholder="Enter license key..." required>
<input type="submit" value="Submit">
</form>
</body>
</html>
This code includes a basic form for your users to input the key. When they hit the submit button it will send the key and the domain name of the server your app is installed on to our API to be processed.
Our API will activate the key, lock it to that domain, and send a response with information. The code then looks through the response for a response “valid” as “1”, meaning the key is activated and valid.
Since the key is valid we will save that data to a local file along with the key, as we can use this in the the next step.
2. Checking Keys Daily (Or On Startup) #
It’s important to automatically check the user’s key regularly to ensure it’s still valid. For instance, you can use these checks to deactivate a key if the user decides to refund a purchase after activating it.
Depending on your app you might want to do this check on startup, or perhaps once a day. We have extensive documentation on checking keys daily and checking keys on startup. But let’s give an example here.
For our example we will check the key daily using a pseudo-cron (a file that acts as a server cron). To follow our previous example, we will use PHP but this can be accomplished in any language. First, create a file named something similar to pseudo_cron.php. Have this file install as part of your app.
This file will save the last time it ran to a local file, and if it’s been more than 24 hours since it last ran it will run now and save the new time. If it’s been less than 24 hours it will do nothing.
NOTE: If your app runs on WordPress you can use their built in wp_cron system instead. It functions essentially the same as our pseudo_cron.
Pseudo-Cron.php #
<?php
// pseudo_cron.php
$last_run_file = 'last_run.txt';
$last_run = file_get_contents($last_run_file);
// Check if the script has been run today
if (date('Y-m-d') !== $last_run) {
// Run the daily tasks
include('key_check.php'); // assuming this is the name of the file that performs a key check
// Update the last run date
file_put_contents($last_run_file, date('Y-m-d'));
}
?>
Then, call this function in some part of your app that is ran often. In our example we’ll put it in our footer.php as that file should load every time a page loads.
<?php
// footer.php (or another frequently accessed file)
include('pseudo_cron.php');
?>
Now, let’s create the actual key_check.php that our cron is calling. This is the part that will actually check the key automatically. It will perform an automated key check without any input from the user. In fact the user won’t even know we did this check unless something is wrong.
Key_Check.php #
<?php
// key_check.php
// Function to check internet connectivity
function checkInternetConnection() {
$connected = @fsockopen("google.com", 80);
if ($connected) {
fclose($connected);
return true; // connection is available
}
return false; // connection is not available
}
// Include the local validity file
include 'valid.php';
// Load and parse the .env file
$envPath = __DIR__ . '/.env';
if (file_exists($envPath)) {
$env = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($env as $line) {
list($name, $value) = explode('=', $line, 2);
$_ENV[$name] = $value;
}
} else {
echo "Error: .env file not found.";
exit;
}
// Get the base URL and API authentication key from the environment variables
$baseUrl = $_ENV['BASE_URL'];
$authKey = $_ENV['AUTH_KEY'];
// Check internet connectivity
if (checkInternetConnection()) {
// Internet connection is available, proceed to check the license key via API
$ch = curl_init($baseUrl);
// Set options for cURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'auth: ' . $authKey,
'key: ' . $licenseKey,
'domain: ' . $_SERVER['HTTP_HOST']
));
// Execute cURL session
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'cURL error: ' . curl_error($ch);
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >= 200 && $httpCode < 300) {
$responseData = json_decode($response, true);
if ($responseData && isset($responseData['valid'])) {
// Update local file based on the validity status from API
$dataToSave = "<?php\n// License Key Validity\n\$licenseKey = '{$licenseKey}';\n\$valid = {$responseData['valid']};\n?>";
file_put_contents('valid.php', $dataToSave);
}
}
}
curl_close($ch);
} else {
// No internet connection, use the existing data in valid.php
echo "Please check your internet connection. Using locally stored validation status until then.";
}
?>
Let’s break this code down and explain what it does:
- Checks for an internet connection by pinging a service (e.g. google.com in this example).
- Ping failed (likely means the user has no internet connection):
- Fall back to the data in the local file until a successful ping occurs.
- Ping was successful:
- Use the saved data we collected when the key was activated to recheck the key.
- Get the response from the API.
- Overwrite the “valid” variable in the local file with our new data.
- Ping failed (likely means the user has no internet connection):
Activating / Deactivating Your App Based On The Key’s Status #
So, we’ve activated the key and we’ve set up a way to check it whenever we want. But how do we actually activate or deactivate our app based on the key’s data? Pretty easily actually. Here’s how:
Main.php (or another critical file) #
<?php
// main.php (or some other critical file in your app)
// Include the local file where the most recent validation status is stored
include 'valid.php';
// Your very important part of your code, such as the main function of your app
function veryImportantFunction() {
echo "Function is active and running!"; // An example echo. Put your app's actual code here
}
// Conditionally execute the function based on the license validation
if ($valid === 1) { // Key is valid and working!
veryImportantFunction(); // Allows your app to run
} else { // Key is invalid (or has been deactivated)!
echo "Sorry, this app is deactivated due to an invalid license."; // Doesn't allow your app to fully work because the key is not valid
}
?>
This process will vary slightly depending on what your app does, but it works similarly for all apps. Wrap a critical portion of your code in a function. Then, check if “valid” is 1 (meaning the key is valid). If so, run the function and expect your app to work. If “valid” is 0, don’t let the function run and show a notice to the user.
Summing Up #
There you have it, by (1. giving the user a way to input and activate their key (2. regularly checking the key automatically, and (3. refusing to allow your app to run unless the key validates, you have integrated a powerful licensing system into your app that will protect your digital product from theft and unauthorized use for years to come.
Most of the PHP code above can be copy/pasted directly into your app within minutes. Be sure to test and retest everything, we cannot guaranteed this sample code will work with your app or be 100% safe for your app. Depending on your unique setup you may have to change the code slightly (or, if your app isn’t written in PHP, you’ll have to create an equivalent code in your chosen language).
Asking For Help #
If you need any help please feel free to contact the support desk. We’re happy to help and will do whatever we can to help you get started for as long as you need, free of charge.
You can also send us code snippets highlighting errors you’re experiencing and our team will review them and help as we can, but please note that we can’t create custom code for your app from scratch.
If you would like to send us code to review, please note that:
- We provide this as a free courtesy service for our customers and it shouldn’t be considered a replacement for an on-site developer.
- The person providing this free help may not be an expert in your coding language.
- It’s difficult to understand the scope of a code base through snippets, so make sure the provided code works with your existing code base.
- Be sure to test and verify any code we supply.
- You should also check it for errors and vulnerabilities, test it thoroughly before going live.
- We do not guarantee any code we provide will work or be 100% safe for your unique situation.