Skip to content

Instantly share code, notes, and snippets.

@thgs
Created February 26, 2015 05:33
Show Gist options
  • Save thgs/d3b159396992463f27ae to your computer and use it in GitHub Desktop.
Save thgs/d3b159396992463f27ae to your computer and use it in GitHub Desktop.
Script to randomly pick a file and echo it, or return the filename
<?php
/*
* Script to randomly pick a file and echo it, or return the filename
*
*/
# data
$_helpScreen = <<<OUT
Random File Picker Help
-=-=-=-==-=-=--==-=-=-=-
php rfp.php <option>
<option> - required
Options
--------
file - outputs a random filename
echo - outputs the contents of a random filename
OUT;
$_asciiDir = 'ascii/';
# functions
function helpScreen()
{
echo $_helpScreen.PHP_EOL;
exit(0);
}
function getRandomFile()
{
# access settings
global $_asciiDir;
# get contents
$c = scandir($_asciiDir);
unset($c[0], $c[1]);
$c = array_values($c);
# add full path
foreach ($c as &$file)
$file = $_asciiDir . $file;
# filter contents
$c = array_values(
array_filter($c, function($f){
return (!is_dir($f));
})
);
# pick random file
$pick = rand(0, count($c) - 1);
# return filename
return $c[$pick];
}
function echoContents($fn)
{
global $_asciiDir;
echo file_get_contents($fn);
}
# init vars
$_asciiDir = __DIR__ .'/'. $_asciiDir;
# code
if (!isset($argv[1])) helpScreen();
try
{
switch ($argv[1])
{
case 'file':
echo getRandomFile();
break;
case 'echo':
echoContents(getRandomFile());
break;
default: helpScreen();
}
# terminate
exit(0);
}
catch (Exception $e)
{
exit('Error: '.$e->getMessage());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment