Skip to content

Instantly share code, notes, and snippets.

@renekreijveld

renekreijveld/gencodes.php

Last active Oct 11, 2017
Embed
What would you like to do?
Joomla CLI script to generate unique codes with a predefined length.
<?php
/**
* gencodes.php
*
* This Joomla CLI script can generate unique codes of a predefined length.
* The codes are written to standard output.
*
* Modify the value of variables $how_many and $code_length to your liking.
*
* Installation: upload this file to your Joomla CLI folder.
* Example usage: php gencodes.php > codes.txt
*
* Written by: René Kreijveld, email [at] renekreijveld [dot] nl
*
*/
// Make sure we're being called from the command line, not a web interface
if (PHP_SAPI !== 'cli')
{
die('This is a command line only application.');
}
// We are a valid entry point.
const _JEXEC = 1;
// Load system defines
if (file_exists(dirname(__DIR__) . '/defines.php'))
{
require_once dirname(__DIR__) . '/defines.php';
}
if (!defined('_JDEFINES'))
{
define('JPATH_BASE', dirname(__DIR__));
require_once JPATH_BASE . '/includes/defines.php';
}
// Get the framework.
require_once JPATH_LIBRARIES . '/import.legacy.php';
// Bootstrap the CMS libraries.
require_once JPATH_LIBRARIES . '/cms.php';
class CreateCodesCli extends JApplicationCli
{
function createCode($length) {
// Generate codes from these characters.
// This prevents hard-to-read codes with characters like
// A and 4, 1 and I, 0 and O
$chars = "2356789ABCDEFGHJKLMNPQRSTUVWXYZ";
$code = "";
while (strlen($code) < $length) {
$code .= $chars{mt_rand(0,strlen($chars))};
}
return $code;
}
public function doExecute()
{
// How many codes do you want to generate?
$how_many = 1000;
// How long (in characters) must your code be?
$code_length = 8;
for ($x = 1; $x <= $how_many; $x++) {
// Generate code
$code = $this->createCode($code_length);
// Write to standard output
$this->out($code);
}
}
}
JApplicationCli::getInstance('CreateCodesCli')->execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment