Code:
function csv_extract($csv = "counter.csv")
{
$return = array();
if(!is_file($csv)){
touch($csv);
}
$fh = fopen($csv, "r");
while (!feof($fh)) {
$output = explode(",", fgets($fh, 4096));
if($output[0] !== "" && $output[1] !== ""){
$return[$output[0]] = trim($output[1]);
}
}
fclose($fh);
return $return;
}
This function opens the csv flat file and dumps the variables into an array. This function will only work where ther are 2 value for each entry. EG: in this script we have a filename and a number.
Code:
function csv_inject($file, $input = array(), $csv = "counter.csv")
{
$output = "";
$cr = "\n";
$input[$file]++;
foreach($input as $key => $val){
if($key !== "" && $val !== ""){
$output .= trim($key) . "," . trim($val) . $cr;
}
}
$output = preg_replace("#(.*)\n$#", "\$1", $output);
$fh = fopen($csv, "w");
fwrite($fh, $output);
fclose($fh);
}
This function is called when a file is downloaded. The file currently being downloaded is $file and its count value gets incremented.
Next we go through the array, making sure we aren't writing empty array elements to the flat file.
We "trim" the white space off the values, then make a new line for the next element.
the preg_replace statement is removing the last new line from the file, then we write out the info to the file.
Code:
function dir_read($types = array('mp3'), $dir = "music")
{
$return = array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
$ext = preg_replace("#(.*)\.([a-z0-9]{3})$#", "\$2", strtolower($file));
if(array_search( $ext, $types) !== FALSE){
$return[$file] = 0;
}
}
closedir($dh);
}
}
return $return;
}
This function reads the content of a directory, gets the extension of the files (using the preg_replace statement), check to see if out extension is listed in the allowed extensions array. If the file meets our conditions its written to the directory listing array, with a value of 0 (funky but explained later).
Code:
function array_output($from_csv = array(), $return = array())
{
foreach($return as $key => $val){
$return[$key] = $from_csv[$key];
}
return $return;
}
This function merges the arrays we got from the csv_extract and dir_read functions.
Basically we go through the dir list and replace its count value for the one we got from the csv file. Whats why in the dir_read function we assigned 0 to the array elements.
Code:
//Page output
if(isset($_GET['download'])){
if(1===1){
echo '<meta http-equiv="Refresh" content="1;url='.$dir."/".$_GET['download'].'">';
csv_inject($_GET['download'], $listing);
}
}else{
foreach($listing as $key => $val){
echo "<a target='_blank' href='?download=".$key."'>".$key."</a> | Downloaded ".$val." times<br />";
}
}
This, amazingly enough, is the output. I expect that any user would change the looks.
Hope this is helpful to anyone wanting a non-sql solution for a small script.