Forum Moderators: coopster

Message Too Old, No Replies

Directory listing and downloads counting.

How to count downloads through a php directory listing script

         

jimmyz

3:20 pm on Feb 13, 2007 (gmt 0)

10+ Year Member



Hi to all,
I'm another of the new comers to the world of servers...
I started runnig on my machine an Apache 2.2 (for fun, mostly) and I have found, loved and been using a lovely php directory listing script.

Could you please help me with this?
1. How can I add a downloads counting feature?
2. Limit number of displayed files per page
3. Put a nice link, pointing at my site's root directory, so that I can access the main index page by typing [127.0.0.1...] on my browser or [mysite.com...] from another machine?

This is my index.php:
####################################################################
<?php
// The starting directory. Default: .
$kataloog = ".";
// Will the files be opened in a new window? 0=no, 1=yes. Default: 0
$ava_uues_aknas = 0;
// The maximum allowed space in server (to calculate remaining space).
// 1MB = 1024KB. Default: 25600
$max_space = 25600;
// How deep in subfilders will the script search for files? Default: 1
$dir_levels = 1;
// Will the top image be displayed? 0=no, 1=yes. Default: 1
$logo = 1;
// Will index.php be displayed on the list? 0=no, 1=yes. Default: 0
$kuva_index = 0;
$charset = "UTF-8";
// The list on available icons.
$ikoonid = array("asp", "avi", "bmp", "chm", "css", "doc", "exe", "gif", "gz", "htm", "html", "jpg", "jpeg", "js", "jsp", "mov", "mp3", "mpeg", "mpg", "pdf", "php", "png", "ppt", "rar", "sql", "txt", "wav", "wmv", "xls", "xml", "xsl", "zip");
// The array of folders that will be hidden from the list.
$varjatud_kaustad = array("ikoonid");
// Filenames that will be hidden from the list.
$varjatud_failid = array(".ftpquota", "index.php");
// Password for uploading files. You need to set the password to activate uploading.
// To upload into a directory it has to have proper rights.
$parool = "";
// Location in the server. Usually this does not have to be set manually.
$aadress_serveris = "";
// Translations
$lang_en = array(
"file_name" => "File name",
"size" => "Size",
"last_changed" => "Last changed",
"total_used_space" => "Total used space",
"free_space" => "Free space",
"password" => "Password",
"upload" => "Load the file",
"failed_upload" => "Failed to upload the file!",
"failed_move" => "Failed to move the file into the right directory!",
"wrong_password" => "Wrong password"
);

$lang = $lang_en;

<?php
}
function Failisuurus($suurus)
{
$suurused = Array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');
$yh = $suurused[0];
for ($i=1; (($i < count($suurused)) && ($suurus >= 1024)); $i++)
{
$suurus = $suurus / 1024;
$yh = $suurused[$i];
}
return round($suurus, 2)." ".$yh;
}
function Faililaiend($fail)
{
$a = explode(".", $fail);
$b = count($a);
return $a[$b-1];
}
function Failimuut($aeg)
{
return date ("d.m.y H:i:s", $aeg);
}

function Failiikoon($l)
{
$l = strtolower($l);
global $ikoonid;
if(in_array($l, $ikoonid))
{
return "ikoonid/".$l.".gif";
}
else
return "ikoonid/tundmatu.gif";
}

function Teenool($sort_by, $sort_as, $type, $dir)
{
if($sort_by == $type && $sort_as == "desc")
{
return "<a href=\"?dir=".$dir."&amp;sort_by=".$type."&amp;sort_as=asc\">
<img style=\"border:0;\" alt=\"asc\" src=\"ikoonid/nool_y.gif\" /></a>";
}
else
return "<a href=\"?dir=".$dir."&amp;sort_by=".$type."&amp;sort_as=desc\">
<img style=\"border:0;\" alt=\"desc\" src=\"ikoonid/nool_a.gif\" /></a>";
}

function nimi_cmp_desc($a, $b)
{
return strcmp($a["nimi"], $b["nimi"]);
}

function suurus_cmp_desc($a, $b)
{
return ($a["suurus"] - $b["suurus"]);
}

function suurus_cmp_asc($b, $a)
{
return ($a["suurus"] - $b["suurus"]);
}

function muut_cmp_desc($a, $b)
{
return ($a["muudetud"] - $b["muudetud"]);
}

function muut_cmp_asc($b, $a)
{
return ($a["muudetud"] - $b["muudetud"]);
}

function nimi_cmp_asc($b, $a)
{
return strcmp($a["nimi"], $b["nimi"]);
}

function sum_dir($start_dir, $ignore_files, $levels = 1)
{
if ($dir = opendir($start_dir))
{
while ((($file = readdir($dir))!== false))
{
if (!in_array($file, $ignore_files))
{
if ((is_dir($start_dir . '/' . $file)) && ($levels - 1 >= 0))
{
$levels -= 1;
$filesize += sum_dir($start_dir . '/' . $file, $ignore_files, $levels);
}
elseif (is_file($start_dir . '/' . $file))
{
$filesize += filesize($start_dir . '/' . $file) / 1024;
}
}
}

closedir($dir);
return $filesize;
}
}

function ylemine_kataloog($dir)
{
$tykid = explode("/", $dir);
$arv = count($tykid);
$tykid2 = array();
for($i = 0; $i < $arv - 1; $i++)
{
$tykid2[$i] = $tykid[$i];
}
$dir2 = implode("/", $tykid2);
return $dir2;
}

if(!$_GET["dir"])
$dir = $kataloog;
else
{

if(ereg("\.\.(.*)", $_GET["dir"]) ¦¦ $_GET["dir"][0] == '/')
{
$dir = $kataloog;
$ylemine_dir = "";
}
else
{
$dir = $_GET["dir"];
$ylemine_dir = ylemine_kataloog($dir);
}
}

// Uploaditud
$veateade = NULL;
if($_FILES['userfile']['name'])
{
if($parool && $_POST['parool'] == $parool)
{
$nimi = basename($_FILES['userfile']['name']);
if(get_magic_quotes_gpc())
$nimi = stripslashes($nimi);

$uploaddir = ($aadress_serveris?$aadress_serveris:dirname($_SERVER['SCRIPT_FILENAME']))."/".$dir."/";
$uploadfile = $uploaddir . $nimi;

if(!is_uploaded_file($_FILES['userfile']['tmp_name']))
{
$veateade = $lang["failed_upload"];
}
if(!@move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{
$veateade = $lang["failed_move"];
}
else
chmod($uploadfile, 0644);
}
else
$veateade = $lang["wrong_password"];
}

// Loeme failide ja kaustade andmed
if($avakaust = @opendir($dir))
{
$i = 0;
while ($asi = readdir($avakaust))
{
if($asi!= "." && $asi!= "..")
{
if(is_dir($dir."/".$asi))
{
if(!in_array($asi, $varjatud_kaustad))
$kaustad[] = htmlspecialchars($asi);
}
else if(!in_array($asi, $varjatud_failid))
{
$failid[$i]["nimi"] = htmlspecialchars($asi);
$asi = $dir."/".$asi;
$failid[$i]["laiend"] = Faililaiend($asi);
$failid[$i]["suurus"] = filesize($asi);
$failid[$i]["muudetud"] = filemtime($asi);
$i++;
}
}
}
closedir($avakaust);

// Sorteerime failid ja kaustad. Vaikimisi sorteeritakse nime j&#915;¤rgi.
if($failid ¦¦ $kaustad)
{
if($_GET["sort_by"] == "nimi" && $_GET["sort_as"]!= "asc")
{
@sort($kaustad);
@usort($failid, "nimi_cmp_desc");
}
elseif($_GET["sort_by"] == "nimi" && $_GET["sort_as"] == "asc")
{
@rsort($kaustad);
@usort($failid, "nimi_cmp_asc");
}
elseif($_GET["sort_by"] == "suurus" && $_GET["sort_as"]!= "asc" && $failid)
{
usort($failid, "suurus_cmp_desc");
}
elseif($_GET["sort_by"] == "suurus" && $_GET["sort_as"] == "asc" && $failid)
{
usort($failid, "suurus_cmp_asc");
}
elseif($_GET["sort_by"] == "muudetud" && $_GET["sort_as"]!= "asc" && $failid)
{
usort($failid, "muut_cmp_desc");
}
elseif($_GET["sort_by"] == "muudetud" && $_GET["sort_as"] == "asc" && $failid)
{
usort($failid, "muut_cmp_asc");
}
else
{
@sort($kaustad);
@usort($failid, "nimi_cmp_desc");
}
}

// Algab lehe HTML
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>

<meta content="text/html; charset=<?php print $charset;?>" http-equiv="content-type" />
<title>Encode Explorer</title>
</head>

<body>

<?php
// Veateate printimine (kui on, mida printida)
if($veateade)
{
?>
<div id="veateade"><?php print $veateade;?></div>
<?php
}
?>

<div id="raam">
<?php
if($logo){
?>
<img alt="Encode Explorer" src="ikoonid/logo.png" /><br />
<?php
}
?>

<!-- ALGAB LISTITABEL -->
<table class="tabel" border="0" cellpadding="3" cellspacing="0">

<tr class="rida_yks">
<td style="width:25px;">
&nbsp;
</td>
<td>
<?php print $lang["file_name"];?>
<?php echo Teenool($_GET["sort_by"], $_GET["sort_as"], "nimi", $dir);?>
</td>
<td style="width: 100px; text-align: right;">
<?php print $lang["size"];?>
<?php echo Teenool($_GET["sort_by"], $_GET["sort_as"], "suurus", $dir);?>
</td>
<td style="width: 150px; text-align: center;">
<?php print $lang["last_changed"];?>
<?php echo Teenool($_GET["sort_by"], $_GET["sort_as"], "muudetud", $dir);?>
</td>
</tr>
<tr class="rida_kaks">
<td style="width: 25px;">
<img alt="tyyp" src="ikoonid/dir.gif" />
</td>
<td colspan="3">
<a href="?dir=<?php print $ylemine_dir;?>">..</a>
</td>
</tr>

<?php
// Kaustade ja failide kuvamine algab
$rida = 1;

// Kuvame kaustad
if($kaustad)
{
foreach ($kaustad as $kaust)
{
$rida_stiil = ($rida? "rida_yks" : "rida_kaks");
?>
<tr class="<?php echo $rida_stiil;?>">
<td style="width: 25px;">
<img alt="tyyp" src="ikoonid/dir.gif" />
</td>
<td colspan="3">
<?php echo "<a href=\"?dir=".$dir."/".$kaust."\">".$kaust."</a>";?>
</td>
</tr>
<?php
$rida=!$rida;
}
}

// Kuvame failid
if($failid)
{
foreach ($failid as $fail)
{
$rida_stiil = ($rida? "rida_yks" : "rida_kaks");
?>

<tr class="<?php echo $rida_stiil;?>">
<td style="width: 25px;">
<img alt="tyyp" src="<?php echo Failiikoon($fail["laiend"]);?>" />
</td>
<td>
<?php
echo "<a href=\"".$dir."/".$fail["nimi"]."\"";
if($ava_uues_aknas)
echo "target=\"_blank\"";
echo ">".$fail["nimi"]."</a>";
?>

</td>
<td style="text-align: right;">
<?php echo Failisuurus($fail["suurus"]);?>
</td>
<td style="text-align: center;">
<?php echo Failimuut($fail["muudetud"]);?>
</td>
</tr>
<?php
$rida=!$rida;
}
}
}

// Kaustade ja failide kuvamine l&#915;µppeb
?>

</table>
<!-- LOPPEB LISTITABEL -->
</div>

<?php
if($parool)
{
?>
<!-- ALGAB UPLOADI ALA -->
<div id="upload">
<form enctype="multipart/form-data" action="" method="post">
<table cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td align="left">
<?php print $lang["password"];?>: <input type="password" name="parool" />
</td>
<td align="right">
<input name="userfile" type="file" />
<input type="submit" value="<?php print $lang["upload"];?>" />
</td>
</tr>
</table>
</form>
</div>
<!-- L&#915;&#8226;PPEB UPLOADI ALA -->
<?php
}
?>

<!-- ALGAB INFOALA -->
<div id="infoala">
<?php
// Konto suuruse arvutamine
$ignore_files = array('..', '.');
$start_dir = getcwd();
$size = sum_dir($start_dir, $ignore_files, $dir_levels);
$remaining = $max_space - $size;
$kokku = round($size/1024, 3);
$jargi = round($remaining/1024, 3);
?>
<?php print $lang["total_used_space"];?>: <?php print $kokku;?> MB ¦ <?php print $lang["free_space"];?>: <?php print $jargi;?> MB ¦ <a href="http://scripts.owner.site.net">encode explorer</a> by delos
</div>
<!-- LOPPEB INFOALA, v3.3 -->
</body>
</html>
###################################################################

I hope I'm bothering the mods with this long post... If it is a problem please delete it.... :-(

Also hope not to tire up the helpers...

[edited by: jatar_k at 1:21 pm (utc) on Feb. 19, 2007]
[edit reason] tried to trim some code [/edit]

jimmyz

3:21 pm on Feb 13, 2007 (gmt 0)

10+ Year Member



I hope I'm REALLY NOT bothering the mods with this long post...

jatar_k

1:22 pm on Feb 19, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld jimmyz,

1. How can I add a downloads counting feature?
I didn't really read through all the code but you would need a download script. The script would build the headers for the file to be downloaded and then add a count to a database.

Are we talk downloads or uploads? I see some upload code in there.

2. Limit number of displayed files per page
You would need to look for threads on pagination [google.com]

3. Put a nice link, pointing at my site's root directory, so that I can access the main index page by typing [127.0.0.1...] on my browser or [mysite.com...] from another machine?

this would be an apache configuration issue

Are you hosting this locally or do you have it hosted somewhere else?

It's really hard for me to work through all that code, funny how varnames in other laguages make it more difficult.

I also have to apologize, I had this thread on hold to trim the code and got sidetracked and left it on hold. Thanks coop for reminding me.

jimmyz

3:26 pm on Feb 20, 2007 (gmt 0)

10+ Year Member



jatar_k, thank you for your reply, you are very kind, I hope not to tire you up, with all this unknowledgement of mine.

(1) I have found a script (in perl), but it needs to have the link written in a form like: [mysite.com...] for a file as: [mysite.com...] But the content of the page is generated from the php script, so I can not change the link to the file(s). Is it possible to add some code in this script to add this feature or is it possible to use another script that could work along with the first one?

We're talking downloads, the script gives the option of uploading if you set a password. But I don't care for this.

(2) I hope I find something usefull and find out how to incorporate it with the directory listing script... I will give it a shot.

(3) I wanted to make the directory listing script to include

<a href="http://www.mysite.com" title="www.mysite.com">www.mysite.com</a></div>
. This is done.

Thanks for your work again.

jatar_k

3:46 pm on Feb 20, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



is this the line that outputs the link to the file?

<?php echo "<a href=\"?dir=".$dir."/".$kaust."\">".$kaust."</a>";?>

not sure what $kaust is but that is the first thing you need to do is identify exactly which line is outputting the link

you can then change that output to point to the perl script and see if that works

jimmyz

2:44 pm on Feb 21, 2007 (gmt 0)

10+ Year Member



You open my eyes jatar_k!
This is for outputting the FOLDER url, few lines belowit has:

echo "<a href=\"".$dir."/".$fail["nimi"]."\"";if($ava_uues_aknas)
echo "target=\"_blank\"";
echo ">".$fail["nimi"]."</a>";

and this is for outputting the files links.

I changed the first line with:

echo "<a href=\"http://www.mysite.com/cgi-bin/counter/load.cgi?".$dir."/".$fail["nimi"]."\"";

but the outputed url is:
http://www.mysite.com/cgi-bin/counter/load.cgi?./file.rar

instead of
http://www.mysite.com/cgi-bin/counter/load.cgi?directory/file.rar

Any ideas?

[edited by: jimmyz at 2:54 pm (utc) on Feb. 21, 2007]

jatar_k

2:53 pm on Feb 21, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



the dot refers to the current working directory

you could add a line before that checks the $dir var and if it contains only a dot then you could switch it to either blank or to the present directory

that would depend on what type of path you need for the perl file

<note>ther's a big problem with reading scripts in other languages, I assume fail means file, well now I do, but to me it was saying that something had failed

funny ;)

jimmyz

3:21 pm on Feb 21, 2007 (gmt 0)

10+ Year Member



Script is in estonian language -unknown for me too...
fail means file and nimi means name as far as I can understand...

I changed again the code:

echo "<a href=\"http://www.mysite.com/cgi-bin/counter/load.cgi?directory/".$fail["nimi"]."\"";

and it worked! I'm very happy now. :-)

Only thing left is to follow your indication about limiting number of displayed files per page.

Thank you jatar_k, I wish I could give back to you.

jimmyz

3:24 pm on Feb 21, 2007 (gmt 0)

10+ Year Member



Works only for first level files...
It is not entering the subfolders...
:-(

jatar_k

3:38 pm on Feb 21, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



you would need to do a little switching

your solution works for files in the same folder but not for ones in subfolders

did it work the original way for subfolders?

if so then you could do something like

if ($dir == '.') {
echo "<a href=\"http://www.mysite.com/cgi-bin/counter/load.cgi?directory/".$fail["nimi"]."\"";} else {
echo "<a href=\"http://www.mysite.com/cgi-bin/counter/load.cgi?".$dir."/".$fail["nimi"]."\""; }

if it didn't work for subfolders before then you will have to figure out how to change it and make the adjustment in your else statement

jimmyz

12:57 pm on Feb 22, 2007 (gmt 0)

10+ Year Member



Wow!
this one is working fine!

if ($dir == '.') {
echo "<a href=\"http://www.mysite.com/cgi-bin/counter/load.cgi?directory/".$fail["nimi"]."\"";} else {
echo "<a href=\"http://www.mysite.com/cgi-bin/counter/load.cgi?directory/".$dir."/".$fail["nimi"]."\""; }

No matter how deep the folder is, the generated url is perfect! It is exactly what I wanted!
Thank you again, jatar_k

jatar_k

1:17 pm on Feb 22, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



my pleasure, glad to help