Hi,

Does anyone have a simple script that i could put on my webpages that when a user clicks on a link to download a file it displays something like (File Downloaded XX times) on the webpage.

I found many scripts with admin interface etc, but i just want it as simple as possible, in the code there should be to my knowledge somewhere where i put the url for it to track the link.

Thanks
genieuk

Recommended Answers

All 34 Replies

I found a simple script but have one problem with it, if someone would look at it for me.

Basically everything works fine but on the page that users see it does not show the xx times file was downloaded. I think it is a simple error or something, if someone could tell me what it is so i can sort it please.

here is everything for the script:
==================

Download counter script using PHP. It simply counts each click on the download link and stores the result in a writable text file.

First upload the file you wish users to download to your server. Then create a text file and name it “counter.txt“. Open the text file and add a 0, save and upload to your server and set the text file permissions to 777.

Now create a PHP file named “countdownloads.php” and add the following code:

<?php
    $myFile = "counter.txt";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, filesize($myFile));
    fclose($fh);

    $theData = $theData + 1;

    $myFile = "counter.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $theData);
    fclose($fh);

    header("Location: download.zip");
    ?>

Now add the following code to your HTML page that will display the link to your download:

<p><a href="countdownloads.php">Download File</a><br />
    <?php
    $myFile = "counter.txt";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, filesize($myFile));
    echo $theData;
    fclose($fh);
    ?> Downloads<br />
    since Feb 2008</p>

Upload these files to the same directory on your server and that should do the trick.

The part that i think would be wrong is this bit of code,

It shows link and Downloads since Feb2008 on webpages but not xx times file was downloaded.

<p><a href="countdownloads.php">Download File</a><br />
    <?php
    $myFile = "counter.txt";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, filesize($myFile));
    echo $theData;
    fclose($fh);
    ?> Downloads<br />
    since Feb 2008</p>

do anything know or see where problem is?

Anyone?

I think it has something to do with this bit of code that outputs xx downloads since Feb 2009. All is working great etc, downloads are counted like they should in the counter.txt file etc but nothing shows on out put page.

<p><a href="countdownloads.php">Download File</a><br />
    <?php
    $myFile = "counter.txt";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, filesize($myFile));
    echo $theData;
    fclose($fh);
    ?> Downloads<br />
    since Feb 2008</p>

Try to make sure the file is in the current directory. Also an easier method of getting a files contents would be to use the get contents method: $theData = file_get_contents( "counter.txt" ); Thats it.

Actually I'll rewrite it.

In the countdownloads.php replace it for this:

<?php

$file = "DOWNLOAD NAME INC DIRECTORY";
$counter = "COUNTER NAME INC DIRECTORY";

//Don't edit below this line
$prevNum = file_get_contents( $counter );
$newNum = $prevNum + 1;
$handle = fopen( $counter , "w" ) or die( "Issue opening the counting file, please chmod the counter file named ".$counter );
fwrite( $handle , $newNum );
fclose( $handle );

echo '<p>Download should start shortly...</p>';
echo '<meta http-equiv="refresh" content="0; URL='.$file.'" />';

?>

Ok that will make the script smaller but acheive the same thing. Next change the lines for echoing out the number to this:

<p><a href="countdownloads.php">Download File</a><br />
    <?php
    $file = "COUNTER NAME INC DIRECTORY";
    $downloads = file_get_contents( $file );
    echo $downloads;
    ?> Downloads<br />
    since Feb 2008</p>

Off the cuff as I have heard people say, so it might not work I'll test it now.

Oh yes if you can't be bothered to create the file then just go through the download process once, it will turn up errors about it not existing but then it will create the file.

Thanks so much for your time, really appreciate it.

Where it says 'DOWNLOAD NAME INC DIRECTORY'

Do i replace that with the full url to the file that is to be downloaded?

and

Do i replace 'COUNTER NAME INC DIRECTORY' with the full url to the counter.txt file?

For some reason i keep getting:

Issue opening the counting file, please chmod the counter file named http://my-domain.com/test/counter.txt

I have tried CHMOD 666, 644, 755, and still wont work, my server does not allow CHMOD 777 for security reasons. Yet the old code counter.txt was set to CHMOD 644 and had no problems,

Can you confirm this works for you? as i keep getting that chmod error.

Thank you,
genieuk

It might be that you have to put the directory releative to the current working directory. I have tested the script on a working Windows server.

If it is in the releative directory (current working directory) then you could just add counter.txt and download.zip or whatever the download file is.

You might also want to try adding counter.file for your counter file.

Delete the counter file and just add it to the directory without chmoding it.

Hi i managed to work out the links,

I can put full url link of download file or just as a directory, does not matter.

But still get CHMOD error, i am using a Linux server.

Thank you,
Mathew

Not sure if it because of CHMOD error but the xx amount of downloads does not show, i think i because of the chmod problem that i am having. Strange, it seems if i put full url in browser to the counter.txt file it shows the file which at the moment only contains a 0 as that what i want the download to start from yet it seems that the script is having problems reading the file.

Ok try again remove the counter. CHMOD the PHP download counter document to the highest you can. Then go to the download page (where the counter is) and click the download link to download the file. When you go to the countdownloads.php page it should give some errors, then go back to the index page with the download link. It should say 1 now then go through and test it again this time there should be no errors.

It's 3:05am in the morning why are you still up :P I have an excuse I work nights haha.

Have you changed the download page $file attribute this should be the counter on the file.

Hi no i not changed anything only where i need to enter the URLS.

Whenn you say i should get an error when i first do it, i dont even get that, i did start from fresh so maybe that why i dont get it.

I just keep getting the CHMOD error, and because the script it cannot read the counter.txt file it gives the error. When i click the download the link it waits a few seconds then the page that has the download link changes to example: http://www.my-domain.com/ countdownloads.php and that is where i get the CHMOD error.

Also i am not sure if this is correct, in your first piece of code where it says:

$file = "DOWNLOAD NAME INC DIRECTORY";
$counter = "COUNTER NAME INC DIRECTORY";

as you see the $file means url to file download and $counter means url to counter.

but in your second piece of code, where it says:

$file = "COUNTER NAME INC DIRECTORY";

now that is the url to the counter, problem is i think how can $file in second piece of code be counter url when in first piece of code $file is url to file that is to be counted and downloaded.

Thank you
genieuk

Hi,

I managed to solve it. In the countdownloads.php the $counter variable must not be full url only name of file (counter.txt)

same goes for output page.

Problem is it does not show xx mount file was downloaded on page that contains the download link. IT shows the download since etc text but not the xx times it was downloaded.

Thank you,
genieuk

Hi,

Me again. I spoken to host and they said CHMOD Permission 777 is not permitted as it is a security risk.

I have two options switch host, which i dont want to do as they have always been fantastic and reliable or is there another way it can be done without the file permission?

The only other way i can think of is seeing if someone would alter it to so it uses a simple MySQL database instead so it wont depend on the counter.txt file permission.

Any suggestions or ideas?

Thank you
genieuk

Yes it would actually be easier with a MySql database. The reason for not being able to open the counter text is because your host has probably denied access to open and read external files (files linked with the http://) so just make sure in the download page you also link to it by just putting the counter.txt name.

Ok so I will rewrite the script and give you a SQL snippet for you to add to your new table.

Yes it would actually be easier with a MySql database. The reason for not being able to open the counter text is because your host has probably denied access to open and read external files (files linked with the http://) so just make sure in the download page you also link to it by just putting the counter.txt name.

Ok so I will rewrite the script and give you a SQL snippet for you to add to your new table.

WOW thanks for this and doing the MySQL thingy for me, god you are nice.

i am not using the http:// link and just using counter.txt but makes no difference.

Only thing that concerns me is, if i have let say 5 web pages in the same directory and each page has a download link will they conflict using the MySQL, for example:?

counterdownloads.php in that file you have to specify the name of the counter file (example counter.txt,counter1.txt etc) now if i had 5 webpages and only one counterdownloads.php would it start causing confusion it what counter to use.

I hope you understand what i mean, otherwise every page that has a link will have to be in a folder with with it own counterdownloads.php to avoid conflict. Not sure if the MySQL solves this aswell.

Look forward to the update. Man your great.

Thank you
genieuk

Hi,

Dont want to sound rude or inpatient, just thought i would ask, when this new script would be done by please?

Also just incase you dont read it, read post above this one.

Thanks,
genieuk

Ok I have read and I agree with the issue of having more than one download in any one directory. I'm sure I can create a script that uses MySql and will be able to use the one page to count all the downloads and redirect to the files. I shall start this now for you. I should be done in about 5-10mins, if you want to wait.

WOW, thanks, i cannot beleive how quick you are.

If you could explain how it exactly works and where i have to make edits etc that would be great so i can understand it more better.

Thanks ever so much for your time, i really do appreciate it.

Sorry it is take a little longer writing up the instructions LOL ok I will add comments next to all the different things that are going on.

This is great, if i dont see it in next few minutes i will see in the morning as it 02:58AM and me tired.

Thanks thou for everything.

Ok I haven't commented it yet but the instructions are pretty thorough so you should be able to see whats going on.

I have attached the files but I will also post them here:

INDEX.PHP

<?php

    function sql_con() {
        $con = mysql_connect( "HOST" , "USERNAME" , "PASSWORD" );
        $db = mysql_select_db( "DATABASE_NAME" , $con );   
    }
    
    function returnDls( $file ) {
        sql_con();
        $q = mysql_query("SELECT * FROM counter WHERE file='$file'");
        $array = mysql_fetch_array( $q );
        echo $array['dls'];
    }

?>

<a href="count.php?file=file.zip">File</a><br />
<p>This file has been downloaded <strong><?php returnDls( "file.zip" ); ?></strong> times.</p>

COUNT.PHP

<?php

    // Please enter the deatils for your MySql database into the function below.
    function sql_con() {
        $con = mysql_connect( "HOST" , "USERNAME" , "PASSWORD" );
        $db = mysql_select_db( "DATABASE_NAME" , $con );   
    }
    
    /**************INSTRUCTIONS**************/
    /****************************************/
    /*
    
        Please execute the following lines in
        your database query area. This would
        be called sql query and can be found
        on the tabs at the top when looking
        at the PHPMYADMIN database view. The
        following lines will add the table:
        
        CREATE TABLE IF NOT EXISTS `counter` (
          `file` varchar(500) NOT NULL,
          `dls` varchar(4) NOT NULL,
          PRIMARY KEY (`file`),
          UNIQUE KEY `file` (`file`)
        ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
        
        If you wish to add a new file to the
        database then just add the file to 
        the directory of your choice and
        link to this file as shown below:
        
        count.php?file=FILENAME_PATH_AND_EXTENSION
        
        This will add the file path, name
        and extension to the database and
        will redirect to the file.
        
        To display the number of views please
        add this to the top of the document
        you wish to display it on, you will
        also need to add the details like above:
        
        <?php
        
            function sql_con() {
                $con = mysql_connect( "HOST" , "USERNAME" , "PASSWORD" );
                $db = mysql_select_db( "DATABASE_NAME" , $con );   
            }
            
            function returnDls( $file ) {
                sql_con();
                $q = mysql_query("SELECT * FROM counter WHERE file='$file'");
                $array = mysql_fetch_array( $q );
                echo $array['dls'];
            }
        
        ?>
        
        To use this just add this line
        were you wish to display the
        the number of the downloads. For
        example:
        
        <?php returnDls( "example.zip" ); ?>
        
        This would output JUST a number.
           
    */
    
    $file = $_GET['file'];
    
    sql_con();
    
    $q = mysql_query("SELECT * FROM counter WHERE file='$file'");
    
    if( @mysql_num_rows( $q ) > 0 ) {
       $row = mysql_fetch_array( $q );
       $updateVal = $row['dls'] + 1;
       $update = mysql_query("UPDATE counter SET dls='$updateVal' WHERE file='$file'") or die( "error occured: ".mysql_error() );    
    } else {
        $q = mysql_query("INSERT INTO counter (file, dls) VALUES ('$file', '1')");   
    }
    
    echo '<meta http-equiv="refresh" content="0; URL='.$file.'" />';
    

?>

I have tested it and you will have to loop through it once before it's ready.

Give it a go and get back to me.

Hi,

I can more and less sort of see where things go but to be very sure i will wait for you to comment it and then i will try.

So basically just to get this write.

To track a link i need to add the file for example (download.zip) to the database, i use PHPMyAdmin, i know how to run swl query etc but did not know i could add an actual file to the database.

When you say:

#
To display the number of views please
#
  add this to the top of the document
#
  you wish to display it on, you will
#
  also need to add the details like above:
#
 
#
  <?php
#
 
#
  function sql_con() {
#
  $con = mysql_connect( "HOST" , "USERNAME" , "PASSWORD" );
#
  $db = mysql_select_db( "DATABASE_NAME" , $con );
#
  }
#
 
#
  function returnDls( $file ) {
#
  sql_con();
#
  $q = mysql_query("SELECT * FROM counter WHERE file='$file'");
#
  $array = mysql_fetch_array( $q );
#
  echo $array['dls'];
#
  }
#
 
#
  ?>

Does that mean i can also now have on the links page telling people how many times the page has been viewed? if so i just add that to my webpage?

Where it says:

#
To use this just add this line
#
  were you wish to display the
#
  the number of the downloads. For
#
  example:
#
 
#
  <?php returnDls( "example.zip" ); ?>
#
 
#
  This would output JUST a number.
#
 
#
  */

Do i enter full url or directory to the file or just replace example.zip with the file name and extension.

Sorry for sounding dumb but i want to understand how it all exactly works etc so i know then in the future what i am doing etc.


Thank you,
genieuk

Ok the first thing about the functions you need to put on the page that you want to display the ammount of downloads. Basicly what I am doing is creating a function that connects to the database (habbit) then I am creating a function that will ask the database how many times the file is downloaded then return how many times it has been downloaded.

As for the second part you can use either the full URL including the http://domain.com/file.zip etc. or just use the filename and extension file.zip etc.

So basicly just copy what it says to copy and then change the database information for both documents then change the link in the link tag to count.php?file=whatever your file is then click the link, this will automaticly add it to the database for you.

Very important though! the sql block must be executed in the phpmyadmin window in order fo it to access the table. If you are unsure how to do this please refer to the phpMyAdmin documentation.

If you wish I can create a video tutorial if it is really neccessary.

and no you do not add it to the database the only thing that gets added is the url/location of the file relative to the directory you are calling it from so it is probably better to link the file with http:// as apose to file.zip by its self.

What happens is, when it goes to the count.php document it will take the file name and check if it is already in the database if it is then it will update the amount of dls to the new dl total ( 1 more than before ).

However if it isn't already in the table it will add the name of the file to the table and give it 1 download. So that the next time the script is run with the same file name it will be in the database and it will add one to the total of downloads.

I suppose when you learn more about PHP and MySql it will seem so much easier.

Good skills to learn.

Hi,

I am so sorry, i think i am confusing myself.

Firstly the count.php file, is it easier for me to think of that as the processing file, the file that processes everything.

and it confuses me because you say in count.php

To use this just add this line
        were you wish to display the
        the number of the downloads. For
        example:
        
        <?php returnDls( "example.zip" ); ?>

but in index.php it then has this:

<?php

    function sql_con() {
        $con = mysql_connect( "HOST" , "USERNAME" , "PASSWORD" );
        $db = mysql_select_db( "DATABASE_NAME" , $con );   
    }
    
    function returnDls( $file ) {
        sql_con();
        $q = mysql_query("SELECT * FROM counter WHERE file='$file'");
        $array = mysql_fetch_array( $q );
        echo $array['dls'];
    }

?>

<a href="count.php?file=file.zip">File</a><br />
<p>This file has been downloaded <strong><?php returnDls( "file.zip" ); ?></strong> times.</p>

What confuses me is what code do i actually put on the page to output this file has been downloaded xx times.

I don't expect you to do a video, but i would appreciate it if you explained it something likr they have done at this link: http://www.bal4.co.uk/2008/02/26/simple-php-download-counter-script/#comment-191

It makes it much easier for me to understand, it says what code goes where to out put this file has been downloaded xx times but also tells me to create a file save it as whatever etc.

Could you simplify this more for me and do something like on the link?

Thanks
genieuk

Okay sure, here it goes.

Okay to actually display the number of time downloaded you must copy this block of code to any page you wishto display the amount of downloads:

<?php
        
            function sql_con() {
                $con = mysql_connect( "HOST" , "USERNAME" , "PASSWORD" );
                $db = mysql_select_db( "DATABASE_NAME" , $con );   
            }
            
            function returnDls( $file ) {
                sql_con();
                $q = mysql_query("SELECT * FROM counter WHERE file='$file'");
                $array = mysql_fetch_array( $q );
                echo $array['dls'];
            }
        
        ?>

This will create the function that will retreive the number of downloads. To confirm this block must be at the top of your downloads page.

Okay so I am going to make my own downloads page that will have three downloads.

<?php
        
            function sql_con() {
                $con = mysql_connect( "HOST" , "USERNAME" , "PASSWORD" );
                $db = mysql_select_db( "DATABASE_NAME" , $con );   
            }
            
            function returnDls( $file ) {
                sql_con();
                $q = mysql_query("SELECT * FROM counter WHERE file='$file'");
                $array = mysql_fetch_array( $q );
                echo $array['dls'];
            }
        
        ?>

<a href="code.php?file=http://example.com/example.zip">example.zip</a><br />
<p>This has been downloaded <?php echo returnDls( "http://example.com/example.zip" ); ?> times.</p>

<a href="code.php?file=http://example.com/example2.zip">example2.zip</a><br />
<p>This has been downloaded <?php echo returnDls( "http://example.com/example2.zip" ); ?> times.</p>

<a href="code.php?file=http://example.com/example3.zip">example3.zip</a><br />
<p>This has been downloaded <?php echo returnDls( "http://example.com/example3.zip" ); ?> times.</p>

This would give me:

example.zip
This has been downloaded 1 times.

example2.zip
This has been downloaded 150 times.

example3.zip
This has been downloaded 20 times.

So again the block of code that holds the two functions must be at the top of every page that will give a count of the downloads. Mine was my download page.

The next thing is the line that says <?php echo returnDls( "http://example.com/example.file" ); ?> this will output just a number for whatever the file put in it was. In this case it was http://example.com/example.zip. So if I wanted to say "This is a popular file it has been downloaded xx times" you would write:

<?php
        
            function sql_con() {
                $con = mysql_connect( "HOST" , "USERNAME" , "PASSWORD" );
                $db = mysql_select_db( "DATABASE_NAME" , $con );   
            }
            
            function returnDls( $file ) {
                sql_con();
                $q = mysql_query("SELECT * FROM counter WHERE file='$file'");
                $array = mysql_fetch_array( $q );
                echo $array['dls'];
            }
        
        ?>

<!-- Page content would go here and you would execute the following line where ever you wanted to display the number of downloads for the given file. -->

<p>This is a popular file it has been downloaded <?php echo returnDls( "filename" ); ?> times.</p>

Hope this makes more sense forget the database for now and just concentrate on adding the downloads count to your page.

Hi,

Sorry to be late at replying, I will try in the next day or so as something come up really important.

Now you going to probably kill me, but the connect.php file can you just copy and paste the code in a new file but only include what actually needs to be in there?

As this what caused me allot of confusion. That way when i want to do things in future i will understand what i need to do.

Something like this.

Connect.php - Is file for processing the clicks etc (only put code in file that is needed)

Thank you so much and yes i am new to PHP but in the past day or so i have done a fab job of learning. I will get there eventually.

Whilst i am at it, do you recommend best websites to learn php. Some websites are just to over the top and complicate things by not explaining very well or dont tell you everything.

Also i am going to add the database connection fields in a file called dbconnect.php that way the db connect settings are not viewable view the source. I am very sure thou i can do this no problem as i learnt it yesterday on how to do it.

May i also say you have inspired me to learn further. I mean everytime i tried learning in the past i would give up in a few hours but i don't know what it is but you have inspired me to learn and keep to it.

Thank you very much!

genieuk

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.