473,756 Members | 4,046 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PHP file download counter

I use htaccess to protect directory and granting access to download
file only for the authorized users. Just want implement simple PHP file
download counter for single file. I need track the number of downloads
of this file on my website, IP address and date. Since I have no access
to Apache log files, I need some other way, use script that will write
a log file. Is there some handy way?

M.

Oct 23 '06 #1
7 3437

"mistral" <po*******@soft home.netwrote in message
news:11******** *************@e 3g2000cwe.googl egroups.com...
I use htaccess to protect directory and granting access to download
file only for the authorized users. Just want implement simple PHP file
download counter for single file. I need track the number of downloads
of this file on my website, IP address and date. Since I have no access
to Apache log files, I need some other way, use script that will write
a log file. Is there some handy way?

M.
Write a script that supplies the file download with the correct mime type
and in that script record the details you want to the place you want...
Oct 23 '06 #2

"Johnny писал(а):
"
"mistral" <po*******@soft home.netwrote in message
news:11******** *************@e 3g2000cwe.googl egroups.com...
I use htaccess to protect directory and granting access to download
file only for the authorized users. Just want implement simple PHP file
download counter for single file. I need track the number of downloads
of this file on my website, IP address and date. Since I have no access
to Apache log files, I need some other way, use script that will write
a log file. Is there some handy way?
M.
-----------
Write a script that supplies the file download with the correct mime type
and in that script record the details you want to the place you want...
-----------------

How to interface this with htaccess? I am new in Php, perhaps there is
ready scripts written for this tasks?

M.

Oct 23 '06 #3
Johnny is right. Here's some code I've used before that does something
similar. This will log the request to a flat file then redirect the
user:

<?

//
// Class SimpleRedirectL og
//
// Create a simple redirect log. Sample usage:
//
// SimpleRedirectL og::logRedirect ('file.zip');
//
// That will update a file called "logs/file.zip-access-log.csv"
// with the IP address of the client and the number of times the
// URL has been accessed. The client will be redirected to "file.zip".
//

class SimpleRedirectL og
{
function logRedirect($ur l, $logPath = null)
{
if (SimpleRedirect Log::logAccess( $url, $logPath) !== false) {
header("Locatio n: $url");
return true;
}
return false;
}

function logAccess($url, $logPath = null)
{
$ok = false;
$counter = 0;

if (is_null($logPa th)) {
$logPath = dirname(__FILE_ _) . '/logs/' .
preg_replace('#[/\\\]#', '_', $url) .
'-access-log.csv';
}

if (!($fh = fopen($logPath, 'a+'))) {
trigger_error(' Failed to open log file.');
} elseif (!flock($fh, LOCK_EX)) {
trigger_error(' Failed to lock log file.');
} elseif (($size = filesize($logPa th)) === false) {
trigger_error(' Failed to get log file size.');
} else {
$err = false;
if ($size 0) {
// Get the current counter value
$val = '';
$offset = -1;
for (;;) {
if (fseek($fh, $offset--, SEEK_END) !== 0) {
trigger_error(" Failed to retrieve counter.");
$err = true;
} elseif (($c = fgetc($fh)) === false) {
break;
} elseif ($c == ',') {
if (!preg_match('/^[1-9][0-9]*$/', $val)) {
trigger_error(" Stored counter is invalid: \"$val\".");
$err = true;
} else {
$counter = intval($val);
}
break;
} elseif ($c != "\r" && $c != "\n") {
$val = $c . $val;
}
}
if (fseek($fh, 0, SEEK_END) !== 0) {
trigger_error(" Failed to seek in log file.");
$err = true;
}
}
if (!$err) {
$entry =
SimpleRedirectL og::csvEncode(d ate('Y/m/d G:i:s')) . ',' .
SimpleRedirectL og::csvEncode($ url) . ',' .
SimpleRedirectL og::csvEncode($ _SERVER['REMOTE_ADDR']) . ',' .
($counter + 1) . "\n";
if (!fwrite($fh, $entry)) {
trigger_error(' Failed to write log data.');
} else {
$ok = true;
}
}
}

if ($fh && !fclose($fh)) {
trigger_error(' Failed to close log file.');
$ok = false;
}

return $ok ? $counter : false;
}

function csvEncode($str)
{
if (preg_match("/[,\"\r\n]/", $str)) {
$str = '"' . preg_replace('/([" \\\\])/', '\\\\\1', $str) . '"';
}
return $str;
}
}

?>

You could modify this to use readfile() if you want to send the file
directly from PHP instead of using a redirect.

mistral wrote:
"Johnny писал(а):
"
"mistral" <po*******@soft home.netwrote in message
news:11******** *************@e 3g2000cwe.googl egroups.com...
I use htaccess to protect directory and granting access to download
file only for the authorized users. Just want implement simple PHP file
download counter for single file. I need track the number of downloads
of this file on my website, IP address and date. Since I have no access
to Apache log files, I need some other way, use script that will write
a log file. Is there some handy way?
M.
-----------
Write a script that supplies the file download with the correct mime type
and in that script record the details you want to the place you want...

-----------------

How to interface this with htaccess? I am new in Php, perhaps there is
ready scripts written for this tasks?

M.
Oct 24 '06 #4

"pe*******@gmai l.com wrote:
"
Johnny is right. Here's some code I've used before that does something
similar. This will log the request to a flat file then redirect the
user:
<?
//
// Class SimpleRedirectL og
//
// Create a simple redirect log. Sample usage:
//
// SimpleRedirectL og::logRedirect ('file.zip');
//
// That will update a file called "logs/file.zip-access-log.csv"
// with the IP address of the client and the number of times the
// URL has been accessed. The client will be redirected to "file.zip".
//

class SimpleRedirectL og
{
function logRedirect($ur l, $logPath = null)
{
if (SimpleRedirect Log::logAccess( $url, $logPath) !== false) {
header("Locatio n: $url");
return true;
}
return false;
}

function logAccess($url, $logPath = null)
{
$ok = false;
$counter = 0;

if (is_null($logPa th)) {
$logPath = dirname(__FILE_ _) . '/logs/' .
preg_replace('#[/\\\]#', '_', $url) .
'-access-log.csv';
}

if (!($fh = fopen($logPath, 'a+'))) {
trigger_error(' Failed to open log file.');
} elseif (!flock($fh, LOCK_EX)) {
trigger_error(' Failed to lock log file.');
} elseif (($size = filesize($logPa th)) === false) {
trigger_error(' Failed to get log file size.');
} else {
$err = false;
if ($size 0) {
// Get the current counter value
$val = '';
$offset = -1;
for (;;) {
if (fseek($fh, $offset--, SEEK_END) !== 0) {
trigger_error(" Failed to retrieve counter.");
$err = true;
} elseif (($c = fgetc($fh)) === false) {
break;
} elseif ($c == ',') {
if (!preg_match('/^[1-9][0-9]*$/', $val)) {
trigger_error(" Stored counter is invalid: \"$val\".");
$err = true;
} else {
$counter = intval($val);
}
break;
} elseif ($c != "\r" && $c != "\n") {
$val = $c . $val;
}
}
if (fseek($fh, 0, SEEK_END) !== 0) {
trigger_error(" Failed to seek in log file.");
$err = true;
}
}
if (!$err) {
$entry =
SimpleRedirectL og::csvEncode(d ate('Y/m/d G:i:s')) . ',' .
SimpleRedirectL og::csvEncode($ url) . ',' .
SimpleRedirectL og::csvEncode($ _SERVER['REMOTE_ADDR']) . ',' .
($counter + 1) . "\n";
if (!fwrite($fh, $entry)) {
trigger_error(' Failed to write log data.');
} else {
$ok = true;
}
}
}

if ($fh && !fclose($fh)) {
trigger_error(' Failed to close log file.');
$ok = false;
}

return $ok ? $counter : false;
}

function csvEncode($str)
{
if (preg_match("/[,\"\r\n]/", $str)) {
$str = '"' . preg_replace('/([" \\\\])/', '\\\\\1', $str) . '"';
}
return $str;
}
}

?>

You could modify this to use readfile() if you want to send the file
directly from PHP instead of using a redirect.

mistral wrote:
"Johnny писал(а):
"
"mistral" <po*******@soft home.netwrote in message
news:11******** *************@e 3g2000cwe.googl egroups.com...
I use htaccess to protect directory and granting access to download
file only for the authorized users. Just want implement simple PHP file
download counter for single file. I need track the number of downloads
of this file on my website, IP address and date. Since I have no access
to Apache log files, I need some other way, use script that will write
a log file. Is there some handy way?
M.
-----------
Write a script that supplies the file download with the correct mime type
and in that script record the details you want to the place you want...
-----------------
How to interface this with htaccess? I am new in Php, perhaps there is
ready scripts written for this tasks?
M.
------------------

I tried script, but not work for me. What variables need be edited?

M.

Oct 24 '06 #5
Hi,

Try setting error_reporting (E_ALL) and watch for any errors. Pls paste
your script that uses the class...

By default you'll need a web-writable directory called "logs" located
in the same directory where the class file is.

mistral wrote:
"pe*******@gmai l.com wrote:
"
Johnny is right. Here's some code I've used before that does something
similar. This will log the request to a flat file then redirect the
user:
<?
//
// Class SimpleRedirectL og
//
// Create a simple redirect log. Sample usage:
//
// SimpleRedirectL og::logRedirect ('file.zip');
//
// That will update a file called "logs/file.zip-access-log.csv"
// with the IP address of the client and the number of times the
// URL has been accessed. The client will be redirected to "file.zip".
//

class SimpleRedirectL og
{
function logRedirect($ur l, $logPath = null)
{
if (SimpleRedirect Log::logAccess( $url, $logPath) !== false) {
header("Locatio n: $url");
return true;
}
return false;
}

function logAccess($url, $logPath = null)
{
$ok = false;
$counter = 0;

if (is_null($logPa th)) {
$logPath = dirname(__FILE_ _) . '/logs/' .
preg_replace('#[/\\\]#', '_', $url) .
'-access-log.csv';
}

if (!($fh = fopen($logPath, 'a+'))) {
trigger_error(' Failed to open log file.');
} elseif (!flock($fh, LOCK_EX)) {
trigger_error(' Failed to lock log file.');
} elseif (($size = filesize($logPa th)) === false) {
trigger_error(' Failed to get log file size.');
} else {
$err = false;
if ($size 0) {
// Get the current counter value
$val = '';
$offset = -1;
for (;;) {
if (fseek($fh, $offset--, SEEK_END) !== 0) {
trigger_error(" Failed to retrieve counter.");
$err = true;
} elseif (($c = fgetc($fh)) === false) {
break;
} elseif ($c == ',') {
if (!preg_match('/^[1-9][0-9]*$/', $val)) {
trigger_error(" Stored counter is invalid: \"$val\".");
$err = true;
} else {
$counter = intval($val);
}
break;
} elseif ($c != "\r" && $c != "\n") {
$val = $c . $val;
}
}
if (fseek($fh, 0, SEEK_END) !== 0) {
trigger_error(" Failed to seek in log file.");
$err = true;
}
}
if (!$err) {
$entry =
SimpleRedirectL og::csvEncode(d ate('Y/m/d G:i:s')) . ',' .
SimpleRedirectL og::csvEncode($ url) . ',' .
SimpleRedirectL og::csvEncode($ _SERVER['REMOTE_ADDR']) . ',' .
($counter + 1) . "\n";
if (!fwrite($fh, $entry)) {
trigger_error(' Failed to write log data.');
} else {
$ok = true;
}
}
}

if ($fh && !fclose($fh)) {
trigger_error(' Failed to close log file.');
$ok = false;
}

return $ok ? $counter : false;
}

function csvEncode($str)
{
if (preg_match("/[,\"\r\n]/", $str)) {
$str = '"' . preg_replace('/([" \\\\])/', '\\\\\1', $str) . '"';
}
return $str;
}
}

?>

You could modify this to use readfile() if you want to send the file
directly from PHP instead of using a redirect.

mistral wrote:
"Johnny писал(а):
"
"mistral" <po*******@soft home.netwrote in message
news:11******** *************@e 3g2000cwe.googl egroups.com...
I use htaccess to protect directory and granting access to download
file only for the authorized users. Just want implement simple PHP file
download counter for single file. I need track the number of downloads
of this file on my website, IP address and date. Since I have no access
to Apache log files, I need some other way, use script that will write
a log file. Is there some handy way?
M.
-----------
Write a script that supplies the file download with the correct mime type
and in that script record the details you want to the place you want...
-----------------
How to interface this with htaccess? I am new in Php, perhaps there is
ready scripts written for this tasks?
M.

------------------

I tried script, but not work for me. What variables need be edited?

M.
Oct 24 '06 #6
"pe*******@gmai l.com wrote:
"
Hi,
Try setting error_reporting (E_ALL) and watch for any errors. Pls paste
your script that uses the class...
By default you'll need a web-writable directory called "logs" located
in the same directory where the class file is.
mistral wrote:
"pe*******@gmai l.com wrote:
"
Johnny is right. Here's some code I've used before that does something
similar. This will log the request to a flat file then redirect the
user:
<?
//
// Class SimpleRedirectL og
//
// Create a simple redirect log. Sample usage:
//
// SimpleRedirectL og::logRedirect ('file.zip');
//
// That will update a file called "logs/file.zip-access-log.csv"
// with the IP address of the client and the number of times the
// URL has been accessed. The client will be redirected to "file.zip".
//
class SimpleRedirectL og
{
function logRedirect($ur l, $logPath = null)
{
if (SimpleRedirect Log::logAccess( $url, $logPath) !== false) {
header("Locatio n: $url");
return true;
}
return false;
}
function logAccess($url, $logPath = null)
{
$ok = false;
$counter = 0;
if (is_null($logPa th)) {
$logPath = dirname(__FILE_ _) . '/logs/' .
preg_replace('#[/\\\]#', '_', $url) .
'-access-log.csv';
}
if (!($fh = fopen($logPath, 'a+'))) {
trigger_error(' Failed to open log file.');
} elseif (!flock($fh, LOCK_EX)) {
trigger_error(' Failed to lock log file.');
} elseif (($size = filesize($logPa th)) === false) {
trigger_error(' Failed to get log file size.');
} else {
$err = false;
if ($size 0) {
// Get the current counter value
$val = '';
$offset = -1;
for (;;) {
if (fseek($fh, $offset--, SEEK_END) !== 0) {
trigger_error(" Failed to retrieve counter.");
$err = true;
} elseif (($c = fgetc($fh)) === false) {
break;
} elseif ($c == ',') {
if (!preg_match('/^[1-9][0-9]*$/', $val)) {
trigger_error(" Stored counter is invalid: \"$val\".");
$err = true;
} else {
$counter = intval($val);
}
break;
} elseif ($c != "\r" && $c != "\n") {
$val = $c . $val;
}
}
if (fseek($fh, 0, SEEK_END) !== 0) {
trigger_error(" Failed to seek in log file.");
$err = true;
}
}
if (!$err) {
$entry =
SimpleRedirectL og::csvEncode(d ate('Y/m/d G:i:s')) . ',' .
SimpleRedirectL og::csvEncode($ url) . ',' .
SimpleRedirectL og::csvEncode($ _SERVER['REMOTE_ADDR']) . ',' .

($counter + 1) . "\n";
if (!fwrite($fh, $entry)) {
trigger_error(' Failed to write log data.');
} else {
$ok = true;
}
}
}
if ($fh && !fclose($fh)) {
trigger_error(' Failed to close log file.');
$ok = false;
}
return $ok ? $counter : false;
}
function csvEncode($str)
{
if (preg_match("/[,\"\r\n]/", $str)) {
$str = '"' . preg_replace('/([" \\\\])/', '\\\\\1', $str) . '"';
}
return $str;
}

}
?>
You could modify this to use readfile() if you want to send the file
directly from PHP instead of using a redirect.
mistral wrote:
"
"mistral" <po*******@soft home.netwrote in message
news:11******** *************@e 3g2000cwe.googl egroups.com...
I use htaccess to protect directory and granting access to download
file only for the authorized users. Just want implement simple PHP file
download counter for single file. I need track the number of downloads
of this file on my website, IP address and date. Since I have no access to Apache log files, I need some other way, use script that will write a log file. Is there some handy way?
M.
-----------
Write a script that supplies the file download with the correct mime type
and in that script record the details you want to the place you want...
-----------------
How to interface this with htaccess? I am new in Php, perhaps there is
ready scripts written for this tasks?
M.
------------------
I tried script, but not work for me. What variables need be edited?
M.
-----------

Hi,

I tried link file to download:

http://www.mydomain.com/SimpleRedire...p?title=MyFile

M.

Oct 25 '06 #7
Hi,

You can add this to the bottom of the script to handle that
URL:

if (isset($_GET['title'])) {
SimpleRedirectL og::logRedirect ($_GET['title']);
}
Hi,

I tried link file to download:

http://www.mydomain.com/SimpleRedire...p?title=MyFile

M.
Oct 25 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2983
by: Bernhard | last post by:
I am not sure if php can achieve this, but i guess that my problem shoulb be solved with an server side language. Is there any way i can tell if a visitor of my website has finished a download? For example the visitor clicks on a file download link, and when his download is finished then i want to happen something (for example some download counter or something like that.)
0
1797
by: Marius III | last post by:
Hi there, I am building a File download counter in PHP5. It's working fine but the problem is that its not working with any Download Managers for ex: Free Download Manager / DAP etc. The download manager downloads the actual PHP script file. How can I correct this? Here is my code:
1
5399
by: Roy | last post by:
Hi, I have a problem that I have been working with for a while. I need to be able from server side (asp.net) to detect that the file i'm streaming down to the client is saved completely/succsessfully on the client's computer before updating some metadata on the server (file downloaded date for instance) However, All examples i have tried, and all examples I have found that other people says works - doesn't work for me :-(
4
5708
by: pradqdo | last post by:
Hi folks, I have a very strange problem when I try to port my client/server program to cygwin. It is a simple shell program where the server executes client's commands + it can send and receive files (something like ftp server/client). I implemented all the commands which the server executes from scratch meaning I don't use fork and exec. It was very educational but my problem is that when I try to "get <filename>" from server to the...
39
2859
by: cj | last post by:
I have a 2005 TCP/IP server that creates a new thread to handle each incoming TCP/IP request. Once the request has been answered by the thread the TCP/IP socket is disconnected and the sub/thread ends. This program originally written in 2003 and I rewrote it in 2005 earlier this year. I don't know how long this has been going on but we just noticed today that the program was using over a gig of virtual memory. Real memory was quite...
3
1845
by: malaysiauser | last post by:
Dear all, Last year I install a download control script in Linux server. its working. This year i'd changed my hosting server to other company. i'd tried install the script. It was installed properly but doesn't work. More about the script; This script will log date, time, ip address, by day, by month, by year and analysis of downloads. It has 4 log files for one module (year, date...) Now the problem is if i create new module, it...
13
2026
by: Adhal | last post by:
Hi, How can I stop hotlinking to a specific file, and I want it to redirect it to a PHP link so I can monitor the number of downloads. Here is my site with the download page: http://www.adhal.org/software/downloads.htm And here is softpedia directly connecting to my file and bypassing the counter php. http://www.softpedia.com/get/File-managers/HashNET.shtml
1
47480
KevinADC
by: KevinADC | last post by:
Note: You may skip to the end of the article if all you want is the perl code. Introduction Many websites have a form or a link you can use to download a file. You click a form button or click on a link and after a moment or two a file download dialog box pops-up in your web browser and prompts you for some instructions, such as open or save. Im going to show you how to do that using a perl script. What You Need Any recent...
7
7156
Curtis Rutland
by: Curtis Rutland | last post by:
Building A Silverlight (2.0) Multi-File Uploader All source code is C#. VB.NET source is coming soon. Note: This project requires Visual Studio 2008 SP1 or Visual Web Developer 2008 SP1 and Silverlight 2.0. To get these tools please visit this page Get Started : The Official Microsoft Silverlight Site and follow Step 1. Occasionally you find the need to have users upload multiple files at once. You could use multiple FileUpload...
0
9431
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9255
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9819
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9689
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7226
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5119
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5289
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.