Installing a download counter - review of plugins for WordPress. Creating a file download counter using PHP and MySQL File download counter html

// Remove magic quotes mode conversion $_POST["content"] = addslashes($_POST["content"]);

// Rewrite the contents of the file file_put_contents($_POST["filename"], "$_POST");

4.9. File download counter

The operation of all file download counters is based on the fact that the visitor is not given the file itself as a download link, but a link to a script that takes into account the download and sends the file to the user’s browser.

We will build our counter in such a way that links to download a file are links to the current page, passing the file name as a parameter, for example, index.php?down=archive.zip . The script will check to see if the down parameter is passed, and if so, it will log the archive download in filecount.txt. When the page is reloaded, the counter values ​​for each archive will be extracted from the file for output to the browser window. The file will be transferred for download by sending the HTTP Location header to the visitor indicating the path to the downloaded archive. The file download counter script might look like the one shown in Listing 4.31.

Listing 4.31. File download counter

// Set the error handling level error_reporting(E_ALL & ~E_NOTICE);

// Register file names in an array

$file_name = array("archive1.zip","archive2.zip","archive3.zip");

// Name of the file where statistics are stored $countname = "filecount.txt";

// If the file exists,

// read current statistics into an array if(file_exists($countname))

// Get the contents of the counter

$content = file_get_contents($countname);

// Unpack the array

$count = unserialize($content);

// If there is no such file, create it,

// and reset the statistics

// Fill the $count array with zero values ​​foreach($file_name as $file)

$count[$file] = 0;

// Pack the array and place it in the counter file_put_contents($countname, serialize($count));

// Check if the value of the down parameter is passed

// via the GET method

if(isset($_GET["down"]))

// Check if the value of the $_GET["down"] parameter is included

// into the $file_name array

if(in_array($_GET["down"],$file_name))

// Register the fact that this file has been downloaded

//Increase the value of the counter with the key

// $_GET["down"] by one

$count[$_GET["down"]]++;

// Overwrite the counter file file_put_contents($countname, serialize($count));

echo "The file $file was loaded ".intval($count[$file])." times
";

The names of downloaded files are stored in the $file_name array; adding a new archive results in its automatic registration in the system. Pre-registration in the array is necessary for several reasons. First, when accepting an array name via the down parameter, you need to check whether it is among the files allowed to be loaded. Secondly, it is much more convenient to process file names in an array. Thus, the $count array, which stores the number of file downloads, is automatically built based on the array of files registered in the system,

It is convenient to pack an array into a string using the serialize() function, and then unpack it back into an array using the unserialize() function.

NOTE

It is important to remember that all HTTP headers must be sent before the main content is sent, otherwise they will not be sent and the PHP interpreter will issue a warning "Warning: Cannot modify header information - headers already sent by"

(Warning: It is not possible to modify the header information - the headers have already been sent). This is dictated by the HTTP protocol: the headers are sent first, then the contents of the document, so any output to the browser window is perceived as the end of sending the headers and the beginning of sending the body of the document. If output to the browser window is unavoidable before the headers are sent, you must resort to output control functions, placing all output in a buffer and sending it at the end of the script.

As you can see in Listing 4.31, the script handles the first-run situation where the filecount.txt file is missing - it is automatically created on the first page load, triggered by zero values ​​for each file in the $file_name array. The result of the script from Listing 4.31 can be seen in Fig. 4.4.

Rice. 4.4. The result of the file counter

4.10. Saving text and graphic files

Following a link to text or HTML files results in them being displayed in the browser window, which is not always convenient, especially if the file is intended to be downloaded. The same fate awaits graphic files and, in general, any files that the browser can display. The visitor's browser "learns" about the contents of the file from the server, since each file is accompanied by HTTP headers that inform the client about the content, the size of the downloaded file, the need to set a cookie, etc. If the file type could not be determined, it is sent simply as binary stream.

You can suppress this behavior by sending the HTTP headers shown in Listing 4.32.

Listing 4.32. A script that allows you to save text and graphic files

$filename = basename($_GET["down"]); header("Content-Disposition: attachment; filename=$filename"); header("Content-type: application/octet-stream"); header("Content-length: ".filesize($_GET["down"]));

echo file_get_contents($_GET["down"]); ?>

The script in Listing 4.32 takes a filename as a GET parameter, for example,

index.php?down=filetext.txt. The basename() function retrieves the name

file (in case the GET parameter down contains the path to the file). The Content-Disposition HTTP header specifies the name of the file to be saved, which is determined by the filename attribute. In the above script, the filename parameter is the same as the name of the file being sent, however, an arbitrary name can be passed as the filename parameter. The Content-type HTTP header indicates that the data being transferred is binary and should not be interpreted by the browser. The Content-length HTTP header conveys the size of the file to the client. The last line displays the file contents passed through the $_GET["down"] parameter, which are retrieved using the file_get_contents() function. The result of the script from Listing 4.32 is shown in Fig. 4.5.

NOTE

It is important that after outputting the contents of the file, nothing else is output to the stream: neither by the echo construct nor by direct output - otherwise everything will be appended to the end of the file. This applies to both possible spaces and newlines after the ending ?> tag.

Rice. 4.5. Dialog box for downloading a file

I decided to see how many times one of my scripts was downloaded from the site. To do this, I decided to write a file download counter for the site. There are many implementations of this problem on the Internet, but nevertheless, check out my solution.

The logic behind the download counter is quite simple. To implement it we will use my favorite ajax. We attach to the button when the clik event occurs a call via ajax to the php file of the counter. In php, the ajax request is processed and the total number of races is written to a text file. After a successful recording, a response is returned with a total download counter and the user is redirected to the link to download the file (the file is downloaded). This is such simple logic. Now let's start implementing it. Let's create a downloadable file test.zip in advance. Let's code the button and show the race counter.

Download file Number of races:

We created a button with id="btnSend" , we will display the counter in a span with id="countView" , and we will store a link to the downloaded file in the data-download attribute

Now let's attach a click handler to the button. Here we will already use js and jquery. You can read about how to implement clik using jquery. But before installing the click handler, we will ajax access the count.php file, which will contain all the work of the counter. You can read more about ajax data transfer.

/*get the current number of downloads*/ $(document).ready(function())( //prohibit caching of the ajax request //otherwise the counter will fail $.ajaxSetup((cache: false)); var html; $.ajax (( //how we will transfer data type: "GET", //where we will transfer url: "count.php", //what data we will transfer data: (flag: 2), //event after receiving a response from count.php success : function(data)( html=data; //display the current number of downloads $("#countView").html(html); ) )); /*attach an event to the download file button*/ var clickevent=false; //click test flag //click handler $("#btnSend").click(function())( if(!clickevent)( $.ajax(( //how we will transfer data type: "GET", //where we will transfer it url: "count.php", //what data are we passing data: (flag: 1), //event before sending ajax beforeSend: function())( //if the button was clicked then true clickevent=true; ), //event after receiving the response, //receive the data in data success: function(data)( //after completing the actions, we allow it again //to process the click on the button clickevent=false;

html=data; //display a new counter $("#countView").html(html); //get the link from data-download //redirect to the download link, download the file window.location.href = $("#btnSend").data("download");

) ));

Function clearInt ($date)( //reduce date to a non-negative number return abs((int)$date); ) if($_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest") ( //check which flag was received if (clearInt($_GET["flag"]==1)) ( //open the file for reading $f=fopen("mycount.txt","a+"); //closes access to the file from other programs flock($ f,LOCK_EX); //get the counter value from the file $count=fread($f,100); //add the counter @$count++; //overwrite the file ftruncate($f,0); //write the new counter value fwrite ($f,$count); //close the file fclose($f); //return the value echo $count; ) if(clearInt($_GET["flag"]==2)) ( $c=fopen(" mycount.txt","a+"); flock($c,LOCK_EX); $festc=fread($c,100); fclose($c); //return the value echo $festc; ) )

Here I think the same thing, everything is simple. If flag 1 comes, then we rewrite the counter. If flag 2 comes, then data on the number of downloads is simply returned. Everything else, I think, is clear from the comments in the code.

Joomla download counter

I decided to attach a similar counter to one of my Joomla projects. In theory, of course, you need to write either a separate module, or integrate the code into the controller of the com content component, so that the counter data is written not to a file, but to the database and for each article separately. But there is no time for such development and I solved the problem more simply. I needed the counter for one page. I took the count.php file and transferred it to the Joomla template, which is currently connected (in the root of the site templates/your_template). Don't forget to insert the code defined("_JEXEC") or die at the very top of count.php. (this is for Joomla). We insert the download button into the page we create, and the js code can also be embedded in the page, or connected as a separate file. For example, I have it as a separate file (it is located in the js folder of the template). In the template itself, in the header, the connection occurs through code

Therefore, the request should be rewritten a little so that it has the correct structuring for receiving the transmitted data. You may have already guessed that we will need a condition that will be based on the variable being passed counter.

On many sites you can see links to download files. For example, manufacturing companies post instructions for a particular product on their official pages. In addition, software developers also offer to download their program for free, thus allowing the user to become familiar with its functions and operation.

When making a file available for free download, it is important to know how many times it has been downloaded. This is necessary, first of all, for statistics, the analysis of which will help determine the usefulness of the information for the end user.

How to set a download counter on a WordPress site?

There is no way to see these statistics among the WordPress tools. Therefore, we will use a third-party solution - the Kama Click Counter plugin.

Kama Click Counter plugin

The free Kama Click Counter plugin provides all the necessary tools to accurately count the number of downloads of a particular file. So, firstly, it needs to be installed and activated. For example, we will display on the post page a link to a pdf file, for which we will count the number of downloads. It should be noted that files are uploaded to the site using standard WordPress Media Library methods (Media -> Add New). Next, you need to open the post or page for editing. In the content part, you need to place the cursor in the place where the link to the file will be placed, and click the button that appears in the visual editor toolbar.

In a pop-up window, the plugin will ask you to select the previously downloaded file. To do this, click the button with the magnifying glass icon.

In the media file library, select the desired file and click the Select file button.

As a result, a special shortcode will be inserted into the content part of the post or page, which serves to display a link to download the file.

After updating the material (Update button), you can go to the site to view it.

The plugin is also able to show download statistics in the user part of the site – in a widget. Note that by default the plugin does not show specific numbers in the widget about what was downloaded and how many times. Only a list of the most frequently downloaded files is displayed. To do this, go to the admin section Appearance -> Widgets and drag the KSS:Top Downloads widget to the desired location in the sidebar.

You can see that the widget has several options available that allow you to modify the list.

Here you can set the following basic parameters:

  • widget title (Title field);
  • number of output files in the list (how many links to show?);
  • sorting the results (how to sort the result?);
  • customizing the appearance of the template (Template and CSS blocks of the template).

A special feature of the plugin is its flexible template customization. Here you can use so-called tags, in place of which this or that information will be displayed.

After all the widget settings have been completed and saved (Save button), you can view the result on the website.