06.05.2022

Selected files counter. Installing the download counter - an overview of plugins for WordPress. Earnings on writing articles, comments on forums


On many sites you can see links to download files. For example, manufacturing firms place 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 get acquainted with its functions and operation.

When exposing a particular file 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 information for the end user.

How to set a download counter on a WordPress site?

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

Kama Click Counter Plugin

Free Plugin Kama Click Counter provides all the necessary tools to accurately count the number of downloads of a particular file. So, firstly, you need to install and activate it. For example, on the record page, display a link to pdf-file, for which we will count the number of downloads. It should be noted that files are uploaded to the site in standard ways. media libraries WordPress ( Media Files -> Add New). Next, you need to open the post or page for editing. In the content part, you need to put the cursor in the place where the link to the file will be placed, and click the button that appears in the toolbar of the visual editor.

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

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

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 (button Refresh) 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 the widget. Note that the default plugin does not show specific numbers in the widget, what and how many times it was downloaded. Only a list of the most frequently downloaded files is displayed. To do this, go to the admin section Appearance -> Widgets and drag the widget KSS:Top Downloads to the desired sidebar location.

It can be seen that several options are available in the widget that allow you to modify the list.

Here you can set the following basic parameters:

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

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

After all widget settings have been made and saved (button Save), you can see the result on the site.

In today's article, we will create a simple but reliable file upload tracking system. Each file will have a corresponding row in the database where the total number of downloads of that file will be stored. PHP will update the MySQL database and redirect users to the appropriate files.

To track the number of downloads, all you need to do is upload the files to the right folder and use a specific URL to access them.

Step 1 - XHTML

First we need XHTML markup. It is very simple - this is a common block file-manager, containing a bulleted list in which a link to each file will be located inside the element li.

Files for which the number of downloads will be counted must be uploaded to the folder files located in the root directory of the script (you can see how the file structure is organized in the example archive). PHP will loop through all the files in the folder, and add each file as a separate li element, to a bulleted list.

demo.php

  • photoShoot-1.0.zip 0 download

Note that the attribute href at the link passes the name of the uploaded file as a parameter for the file download.php. This is where downloads will be counted, as you'll see later.

You do not have to use this particular interface to organize download counting. You can just link to download.php on blog or website pages, and all downloads will be counted correctly.

Step 2 - CSS

Once our XHTML markup is ready, we can concentrate on the look and feel of our script. The CSS styles below assign the appearance to the file-manager block, via its ID, since we only have one on the page. The remaining elements are styled through class names.

style.css

#file-manager( background-color:#EEE; border:1px solid #DDD; margin:50px auto; padding:10px; width:400px; ) ul.manager li( background:url("img/bg_gradient.gif") repeat-x center bottom #F5F5F5; border:1px solid #DDD; border-top-color:#FFF; list-style:none; position:relative; ) ul.manager li a( display:block; padding:8px; ) ul.manager li a:hover .download-label( /* When a list is hovered over, show the download green text inside it: */ display:block; ) span.download-label( background-color:#64B126; border :1px solid #4E9416; color:white; display:none; font-size:10px; padding:2px 4px; position:absolute; right:8px; text-decoration:none; text-shadow:0 0 1px #315D0D; top :6px; /* CSS3 Rounded Corners */ -moz-border-radius:3px; -webkit-border-radius:3px; border-radius:3px; ) span.download-count( color:#999; font-size: 10px; padding:3px 5px; position:absolute; text-decoration:none; )

Note that here the “download” caption is hidden by default, with the property display: none. It is displayed through display:block, only when you hover over the link, no JavaScript. A bit of CSS3 is used to round off the corners of the caption.

Step 3 - PHP

As we said above, PHP loops through the entire folder files, and outputs each file as an li element of a bulleted list. Let's take a closer look at how this happens.

demo.php - Top

// Error reporting: error_reporting(E_ALL^E_NOTICE); // Including the DB connection file: require "connect.php"; $extension=""; $files_array = array(); /* Opening the thumbnail directory and looping through all the thumbs: */ $dir_handle = @opendir($directory) or die("There is an error with your file directory!"); while ($file = readdir($dir_handle)) ( /* Skipping the system files: */ if($file(0)==".") continue; /* end() returns the last element of the array generated by the explode() function: */ $extension = strtolower(end(explode(".",$file))); /* Skipping the php files: */ if($extension == "php") continue; $files_array =$file; ) /* Sorting the files alphabetically */ sort($files_array,SORT_STRING); $file_downloads=array(); $result = mysql_query("SELECT * FROM download_manager"); if(mysql_num_rows($result)) while($row=mysql_fetch_assoc($result)) ( /* The key of the $file_downloads array will be the name of the file, and will contain the number of downloads: */ $file_downloads[ $row["filename"]]=$row["downloads"]; )

Notice how we select all records from the download_manager table with mysql_query() and then add them to the array $file_downloads, with the array key filename, and the value downloads. Thus, further in the code, we can write $file_downloads['archive.zip'], and display the number of downloads of this file.

Below is the code that is used to generate the li elements of a bulleted list.

demo.php - Central part

Foreach($files_array as $key=>$val) ( echo "

  • ".$val." ".(int)$file_downloads[$val]." download
  • "; }

    Everything is very simple - we go through the cycle foreach by array $files_array, and display the necessary data on the page in the appropriate markup.

    Now let's take a closer look at how download accounting works.

    download.php

    // Error reporting: error_reporting(E_ALL^E_NOTICE); // Including the connection file: require("connect.php"); if(!$_GET["file"]) error("Missing parameter!"); if($_GET["file"](0)==".") error("Wrong file!"); if(file_exists($directory."/".$_GET["file"])) ( /* If the visitor is not a search engine, count the downoad: */ if(!is_bot()) mysql_query(" INSERT INTO download_manager SET filename="".mysql_real_escape_string($_GET["file"])."" ON DUPLICATE KEY UPDATE downloads=downloads+1"); header("Location: ".$directory."/".$_GET[" file"]); exit; ) else error("This file does not exist!"); /* Helper functions: */ function error($str) ( die($str); ) function is_bot() ( /* This function will check whether the visitor is a search engine robot */ $botlist = array("Teoma" , "alexa", "froogle", "Gigabot", "inktomi", "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory", "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot", "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp", "msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg" ", "rabaz", "Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot", "Mediapartners-Google", "Sogou web spider", "WebAlta Crawler","TweetmemeBot", "Butterfly"," Twitturls","Me.dium","Twiceler"); foreach($botlist as $bot) ( if(strpos($_SERVER["HTTP_USER_AGENT"],$bot)!==false) return true; // Is a bot ) return false; // Not a bot )

    Here, you definitely need to check if the visitor is a search engine robot crawling your links. Robots are good visitors because they help get your site listed in search engines, but in our case, they can skew download statistics. That's why the database is only updated after the visitor passes the verification is_bot().

    Step 4 - MySQL

    As we mentioned in the previous step, the number of downloads is recorded as a string in the download_manager table of the MySQL database. First, let me explain how this part of the query works:

    download.php

    INSERT INTO download_manager SET filename="filename.doc" ON DUPLICATE KEY UPDATE downloads=downloads+1

    The first part of the query tells MySQL to insert a new row into the table. download_manager, and set the field value filename equal to the name of the requested file to be loaded. In addition, the field filename defined as a unique table index. This means that a line with a specific file name can only be inserted once, otherwise a duplicate key field error will occur.

    It is in this case that the second part of the request comes into effect - ON DUPLICATE KEY UPDATE, which increases the value of the field downloads by one if the file is already in the database.

    This way, new files will automatically be inserted into the database the first time they are uploaded.

    Step 5 - jQuery

    In order to make our download counter more visual, it would be nice to add the ability to update the counter next to the file name as soon as the user starts downloading. So far, in order to see the new values ​​of the counters, the user needs to reload the page.

    This can be fixed with a small piece of code:

    script.js

    $(document).ready(function()( /* This code is executed after the DOM has been completely loaded */ $("ul.manager a").click(function()( var countSpan = $(".download -count",this); countSpan.text(parseInt(countSpan.text())+1); )); ));

    We just assigned an event handler to the click on the link. Each time the user clicks on the link, we increment the current downloads value by one.

    Step 6 - htaccess

    We have one more thing to do before we can call the job finished. You may have already noticed that some types of files, the default browser tries to open immediately. Instead, we need to start downloading the file. This is pretty easy to do by adding a few lines inside the file .htaccess located in the folder files:

    ForceType application/octet-stream

    That's it, our download counter is ready.

    Conclusion

    To run this example on your own server, you'll need to create a download_manager table in a MySQL database, which of course you have access to. In the archive with an example, there is a file table.sql, which contains the necessary SQL code that will create the desired table.

    After that, just specify your database connection details in the file configuration.php.

    The next question that I recently became interested in when setting up my unpretentious author's project was the question of how to count the number of downloads of a particular file posted here. It was most logical to assume that this requires another plugin, some kind of download manager, or, more simply, a download counter. Having searched the Internet, it turned out that, as usual, these plug-ins are a wagon and a small cart. But their reviews - again, no. What to choose is absolutely not clear, and as usual, I had to test everything on myself. And according to the results of testing, this reviewer turned out. It was written for a very long time, while the goal was not a thorough testing of all the above plugins with a full review of their settings, so you will not find detailed screenshots of each, but here are the key settings. I didn’t want to talk about some at all - they were so stupid, but if I had already looked, it was a pity not to write anything at all.

    Introduction.

    So, the task was to count the number of downloads of a particular file by setting the download counter for WordPress. Upon closer examination, it broke up into several subtasks, or rather, wishes for a plugin that would perform it. Here is a short list of them:

    • It is necessary that the number of downloads be displayed somewhere in the admin panel, with the ability to sort - how many were downloaded per day, per week, month, year, total
    • It is desirable that you can see graphs / diagrams of downloading files relative to each other
    • It is desirable that you can see graphs / diagrams of downloading files over time
    • It is desirable that statistics be kept on when the file was last downloaded
    • The ability to display information next to the link about how many times the file was downloaded, as well as its size, and the download date for the user who is just about to download it. Well, or not to display - at the request of the admin
    • The ability to insert the code responsible for this with a separate button in the posting panel of the TinyMCE editor (I don’t like to use quicktags)
    • Ability to limit download speed (so, just in case)
    • Attaching the upload function to this plugin (uploading files to the server) - on the contrary, did not give up. FTP works fine for me too. But if it doesn't interfere much, then let it stay
    • It would be nice to be able to stick a beautiful button to the download link - although I only need to write class = "button"

    ABAP

    Download file!

    • Well, if you count the number of downloads not only from your site, but simply from a link
    • Possibility to prohibit direct download of a file without showing where it is located on the server.

    This is such a small list.

    Review

    After we have decided on the TOR, we will begin to consider what is directly offered to us.

    1. Plugin Download Counter 1.2, downloaded from here.

    Initially, the plugin page was located, but the author has not supported it for more than 4 years. We create another folder for it in the plugins directory for me - download-counter, throw both files there. As a result - where would you think? - settings for it appear in the records. Very original, but okay.

    We go inside, write the path to the download-manager.php file (I really don’t like to throw any nonsense right at the root). And look what we got. We upload the file, check if it is downloaded manually, if you enter a direct link in the browser, enter the path in the plugin to create a counter. In theory, an ID should be created, which then will need to be inserted everywhere. But nothing happened - it gives an error "Error - Unable to save the record." Well, ok, we persuaded, we transfer it to the download-manager.php root - nothing again, the same error. Well, to hell with you, goldfish, it was not enough for me to understand plugins that the author didn’t give up. Moreover, the functionality is practically zero.

    2. Plugin Download Counter Advanced 1.1, downloaded the same.

    I will say right away that it didn’t really work for me either, so you can read about its installation and configuration only out of academic interest. In fact, this is the same plugin, only slightly modified. Thank God, even though the instruction is not translated, you can read it normally, and not try to understand what the translator meant. By the way, in the admin panel - it seems to be a completely different plugin, offering to update (yes, figs). Similar to the previous plugin, its page was located, and in the same way the author has not supported it for more than 4 years. By analogy, we create another folder for it in the plugins directory, mine is download-counter, we throw all the files there. The settings look, of course, richer, although the download speed is limited immediately for all files, and is not set for each one individually. Where is the download-manager..php file (do not forget the file name at the end, but where all the downloads are - I guessed it the first time, which plunged me into terrible amazement. As it turned out later, I guessed it with the name of the directory in which to lay downloads, here my logic worked 100% the same as the author of the plugin.

    We add the names of the folders that we have on the server in the downloads directory (in the “categories and directories” settings) to make it easier to choose the path to the files. If you do not add them, then you will have to download everything to the downloads root. Save, you can add downloads. Here's what we roughly get.

    Now we try to insert into the post. We add a link, in it we change our link to the code, which is issued directly in the plugin settings. And then ... And figs to you! HTTP Error 500 (Internal Server Error): An unexpected situation occurred while the server attempted to fulfill the request. Well, I was just going to tell you how to add a counter directly to the post, what if the link inside to make it happen

    ABAP

    < ahref= "http://chewriter..jpg" />

    then you can display the download button - crooked, really. Here is the plugin for you, wasted your time. He doesn’t particularly keep statistics, because where the glitch is, we won’t figure it out.

    This is exactly the plugin to which the above Download Counter Advanced was proposed to be updated. Well, he offers - and okay, let's download, let's see. The plugin has not been updated for more than 3 years, and some users even made corrections to its code themselves. It is installed quite successfully, the asceticism of the settings does not inspire optimism. By the way, well done too, they guessed where to place the settings - no worse than in the previous case. We add counters on the settings page, everything seems to be highlighted, as it should.

    Let's see what we have with the addition to the post. Yep, no buttons. And, well, of course, I forgot right there, everything is intuitive. Let's go to the instructions. It is necessary to block a complex structure consisting of shortcodes like , downloaded , and at the same time (probably due to NC) it doesn’t really count anything.

    Therefore, it will not be further considered, together with the Download Counter Chart plugin that goes to it, which displays information in a graphical form, we will not carry out.

    Written by our compatriot, but unfortunately all he can do is display the number of downloaders of the file next to its name - neither statistics nor any other goodies are provided. However, if you are a fan of minimalism, this is what you need. Just don't forget, there are no buttons, a shortcode like


    do-it-yourself download counter for wordpress

    will have to be entered manually. It is very good that the author painted everything in detail, I did not have to test it for myself.

    Well, if we are talking about plugins written by our people, then we cannot fail to mention one more. Its huge plus is that it allows you to count not only the number of downloads of files, but also just clicks on links - it doesn’t matter if they lead to any file, or just to another page. Or to a file on someone else's page 🙂 He will also calculate this, or rather, theoretically, he should calculate it. His statistics are also not so hot, there are no buttons on the editing panel, there are no restrictions on downloads either. But it's still interesting to see. So download and install. In principle, a fairly detailed description is on the author's website, so I won't spread it too much. You must constantly keep in mind that if you want to set a counter on a file or on a link, then you should either use a shortcode of the type, or insert the class = "count" class in the link. This, of course, is annoying, with a button it would be much more convenient. But the most annoying thing is that after all the gestures, I still couldn’t get it to work adequately - if the shortcode was used, then the download link itself was not displayed, and if the class was used, the link statistics did not appear in the admin panel. Screenshots can be viewed from the author - if you like the idea itself - try it, maybe you will succeed.

    Indeed, very simple. No shortcodes, etc. required. However, this plugin provides statistics only for the author, but for visitors, next to the link to the file, it is not displayed.

    However, it should be noted that detailed statistics are kept of who downloaded which file and when. However, it is not very convenient to use it.

    The settings include the following:

    • You can specify the directory from which files are allowed to be downloaded
    • You can specify the types of files that are allowed to download
    • Disable file download as author
    • Set in seconds the interval during which repeated clicks on a link from the same IP will be counted only once
    • Limit the number of files that can be downloaded from one IP per day
    • Use some intermediate page with information that the download will now begin

    However, all this only works if you either (how to put it simply...) have permission to edit the .htaccess file, or if you specify the link directly by inserting it into

    However, since it didn’t have the ability to display statistics for users, and I didn’t want to remember the type of link, I stopped reviewing it, deciding to return only if the other plugins in the queue could not solve the task.

    In terms of displaying information, this plugin is very similar to the one discussed in the previous paragraph. It differs in that it allows you to view statistics separately weekly, monthly, for any period and just top 10. In terms of its capabilities, it is much more miserable, there are no statistics on the last download, or on a specific file, not to mention the ability to impose restrictions on downloading files. There is no clear documentation at all. I got the impression that this is just some kind of misunderstanding, and not a plugin. I don’t even want to give screenshots, but to be objective, I’ll still give them, copyright.

    Well, we got to something more or less worthy. Nearly half a million downloads is saying something. The plugin's official page is here. In order to insert a file into a post, you need to use the arrow above the visual editor (the icon does not appear in it itself)

    And in the window that appears, select the required file (this is an example if it has already been uploaded via FTP)

    Then, click on the "Save new download" button

    and, going to the next screen, select the download format, and click on Insert into post. It is possible that nothing will happen. The plugin is slightly buggy with the latest versions of WordPress. Therefore, you must additionally click on the link View Downloads

    And already then choosing the download format first, click on the Insert link next to the file you want to insert.

    After that, the corresponding shortcode of the type will appear in the post

    ABAP

    [downloadid="7592" format="1"]

    The plugin requires fine manual configuration, but no WYSIWYGs are provided. Good thing you only need to set it up once. Detailed documentation is on the author.

    Here is an example setup:

    ABAP

    (title)

    < ahref= "(url)" title="(!LANG:Downloaded (hits,"ни разу","1 раз","% раза"}">{title}!}

    It should be noted that declensions are not supported, ie. if the file was downloaded 21 times, and you have “times” in your template, then it will sound somewhat un-Russian.

    And here's the button option:

    ABAP

    - (description), (size), Downloaded (date,"Y-m-d"), Downloaded (hits) times

    < ahref= "(url)" title="(!LANG:Downloaded (hits,"ни разу","1 раз","% раза"}">!} - (description), (size), Downloaded (date,"Y-m-d"), Downloaded (hits) times

    Looks like that:

    Well, after some refinement, it began to look like this (still without buttons):

    Line code:

    ABAP

    (filetype_icon) (title)(File size: (size), Uploaded: (date,"d.m.Y"), Downloaded (hits) times)
    (description)

    The list of possibilities is quite wide:

    • You can upload files both with its help (by clicking on the arrow), and indicate the place where they are, if they were uploaded earlier via FTP, you can simply specify the URL
    • Hides the true location of the file, you can substitute any necessary URL combination
    • You can use the download button, including your own
    • Do not count downloads by the admin, and all unnecessary IPs included in the counter exclusion list
    • Whether to count repeated downloads within a certain time from the same IP
    • You can set several formats - with a picture, with a counter, without a counter, etc., and use each of them in the appropriate situation
    • There is an upload of the download log in the form of a csv file

    If any mp3 or video file is uploaded, you need to specify for them, force download, or not. If force - then by clicking on it, it will be downloaded, if not ticked - played, then saving - with the right mouse button. I want to note that the files uploaded with its help are not placed where your special directory for files is created, but in the wp-content/uploads/downloads/ created by it - you need to remember this, as well as the fact that when deleting them from the statistics - physically files are also deleted from the server. With those that are uploaded via FTP - everything is OK. Plus, if you insert a link in different posts to the same file, then I didn’t understand whether it would summarize them. Unfortunately, it does not support any download restrictions, except for the fact that you can prevent everyone from downloading, except for registered users. When you want to display the file name in the bottom line of the browser, or you need to change it to its ID - you need to remember to go to the settings-> permalinks, and save the configuration there so that everything is correctly registered in .htaccess - Without this, the files will not be downloaded.!

    Statistics are displayed in three places at once - in the console, in information about files, and in download logs. This creates certain inconveniences, for example, when you need to see when a file was last downloaded, but you can upload statistics in the form of a csv file, and then sort it out in Excel. Taking into account the fact that Excel has the devilish ability to build the necessary tables and charts, then maybe this is not bad. However, I think the screenshots will say more:

    Well, a screenshot of the log itself:

    At the same time, a huge plus is that a widget appears in the console with statistics like this:

    In general, we can say that after a little tweaking, the plugin does its job just fine.

    This plugin was written by the same author as the WP-Polls plugin that I use on this site, for example. Although it enjoys, in comparison with it, an order of magnitude less popular. But let's see if it's deserved. All documentation can be found on the author's website. At its core, the plugin is absolutely identical to the previous one - the template is written in the same way, there are no restrictions on the download, except for registered-unregistered users, it is also required to use a shortcode of the form

    ABAP

    [downloadid="7592"]

    and for the rest of the points:

    • You can upload files both with its help (up to two Mb, well, or how many you have specified in php.ini), and specify the place where they are, if they were uploaded earlier via FTP, you can simply specify the URL
    • Hides the true location of the file, but it is not possible to substitute any necessary URL combination, there are only a few fixed options, the main one did not work for me
    • Can be configured in such a way that information is displayed to visitors about the size of the file, how many times it was downloaded, when it was downloaded
    • You can display an icon for the corresponding file types
    • You can reset the counter, or set the desired value

    However, there are also some differences. Firstly, there is no button in the visual editor that can be used to insert a shortcode. Rather, there is a button, but in order to use it, you must first add a counter for the file in the plugin settings, and then this button will add the ID of the counter directly to the post. Secondly, there is only one template, and it will not work to display different information for different files. Of the pluses of statistics, it shows when the file was last downloaded, otherwise there are only minuses - no uploading to a csv file, no viewing of who downloaded (there are no IPs), no distribution by date.

    But the icons are prettier (I later attached them to the previous plugin). The result of his work is as follows:

    Also, when deleting a record from the database, it asks if it is also necessary to delete the file itself, or leave it. But in terms of the totality of properties, I liked it less than the previous one - at least by the fact that you need to insert the file separately outside the post, however, it doesn’t have any special minuses - the choice between them is a matter of taste, the first one has more options, more detailed statistics, the second - slightly more convenient (albeit poorer) statistics, and fewer features.

    The heavy artillery went into action. The plugin is mostly Russified, and is a download manager, not a counter. It is possible to limit the download speed, and the number of downloads per person per day.

    But I would say that some of the features of this plugin are redundant, and statistically necessary ones are not enough. There are a lot of settings, download widgets, a complex synchronization system, a system for displaying mp3 tags, displaying flv files, organizing a mini-file storage, displaying all the files specified on the page at the beginning or end of the post, etc., etc.

    I don't even want to give screenshots of all the settings.

    However, with all this - in order to beautifully display the template in the post - I had to edit the style file in it, reducing the width. Plus, in order to display the default template, it is necessary after inserting the shortcode with the button

    enter the name of the template into the code with pens. Some conflict with the Russian name. By the way, it looks like this (I will give three variants of templates at once):

    Counts - through a stump-deck (well, or more than one download from IP does not count, I don’t know). The statistics are a little less than completely poor, very similar to the plug-in just discussed above.

    In general, I was left with an impression - healthy, but stupid. Suitable for some file storage, and even then - if in conjunction with any other plugin. I looked at him - yes, and demolished.

    Frankly, when I read his description, I thought - that's it, what I need!

    Counter, password protection, shortcode inserted by button, editable button, etc.

    And it looks like this (he gave two used three templates at once):

    However, in order to add a file, you first need to add a counter for it in plugins. Secondly, there are practically no statistics at all.

    Thirdly, you cannot set the display of the file size for the user. Fourthly, there is no download speed limit, there is only password protection for the file. Templates cannot be edited. And a big inscription with an offer to buy a premium version for 45 bucks. Well, in general, you understand. Everything delicious is for grandmas. Deactivated and demolished. And beautiful frames, buttons, etc. - I myself will prescribe in styles when I want.

    Summary

    Install in the standard way (by copying to the directory wp-content/plugins/download-monitor/, let update, replace all icons with icons from the archive in the directory wp-content/plugins/download-monitor/img/filetype_icons/ and activate.

    In the future, if I get my hands on it, I'm thinking of making links into nice frames using css3, which I will most likely also write about. Stay with us 🙂

    Upd. Now the author has redesigned the WordPress Download Monitor plugin, and created a completely different version from the original. I checked it out, but I liked it a lot less because the form template of what the download link would look like is now not so easy to edit. The author decided that ready-made preset views would be enough. For example, if in the downloads menu, then - settings, select the desired view from the six preset ones, click save

    Then when choosing the second option, you get something like this:

    Those. on the new version, using the line I provided in the description will not work, but it will be necessary to write a special php file that this output template would describe. But the saddest thing is not even this - but the fact that this php file, if put in the directory with the plugin, will be overwritten every time the plugin is updated. And if you put it in the directory with the theme, then when you change the theme (although this, of course, happens much less often). But in any case, writing it is a rather laborious task, and so far I have no desire to do it. So the only plus of the updated plugin

    For a long time there were no lessons about PHP and MySQL. Today we will create a simple but effective download counter.

    Each file will have an entry in the row of the database table. The same table will store the number of file downloads. PHP will update the database MySQL and redirect the user to the required file.

    To track the number of downloads of any file, you need to put it in a folder files and use a special URL to access it.

    Step 1 - XHTML

    The first step is to create the markup for our script. It is very simple - we have div file-manager, which contains an unordered list in which each element of the list is responsible for a file.

    The files that you want to track downloads are placed in the folder files in the root folder of the script. PHP then iterates through all the files and adds each one as a list item ( li ) to an unordered list.

    demo.php


    • photoShoot-1.0.zip 0 download

    Note that the attribute href links passes the file name as a parameter to download.php. This is where download tracking comes in.

    You don't have to display everything the same way - you can just link to download.php on your pages and all downloads will not pass by.

    Step 2 - css

    After the markup, let's move on to the design. css the rules below apply to div file-manager with id (# symbol), since it occurs only 1 time on the page, and to the rest of the elements by class names.

    styles.css

    #file-manager( background-color:#EEE; border:1px solid #DDD; margin:50px auto; padding:10px; width:400px; )
    ul.manager li( background:url("img/bg_gradient.gif") repeat-x center bottom #F5F5F5; border:1px solid #DDD; border-top-color:#FFF; list-style:none; position:relative ; ) ul.manager li a( display:block; padding:8px; ) ul.manager li a:hover .download-label( /* On hover, show green download text: */ display:block; ) span. download-label( background-color:#64B126; border:1px solid #4E9416; color:white; display:none; font-size:10px; padding:2px 4px; position:absolute; right:8px; text-decoration:none ; text-shadow:0 0 1px #315D0D; top:6px; /* CSS3 Rounded Corners */
    -moz-border-radius:3px; -webkit-border-radius:3px; border-radius:3px; ) span.download-count( color:#999; font-size:10px; padding:3px 5px; position:absolute; text-decoration:none; )

    Step 3 -PHP

    As I said before, PHP looks for files in the files folder and lists each file as a list item in an unordered list. Let's take a look at how it goes

    demo.php- top part

    // Coo reporting errors: error_reporting(E_ALL^E_NOTICE); // : require "connect.php"; $extension=""; $files_array = array(); /* Open the folder and go through all the files: */ $dir_handle = @opendir($directory) or die("There is an error with your file directory!"); while ($file = readdir($dir_handle)) ( /* Skip system files: */ if($file(0)==".") continue; /* end() returns the last element of the array generated by the function explode(): */ $extension = strtolower(end(explode(".",$file))); /* Skip php files : */ if($extension == "php") continue; $files_array=$file; ) /* Sort files alphabetically*/ sort($files_array,SORT_STRING); $file_downloads=array(); $result = mysql_query("SELECT * FROM download_manager"); if(mysql_num_rows($result)) while($row=mysql_fetch_assoc($result)) ( /* Array key $file_downloads will be the name of the file, and will contain the number of downloads: */ $file_downloads[$row["filename"]]=$row["downloads"]; )

    Notice how we select all the rows from the download_manager table with mysql_query(), and later add them to the $file_downloads array with the file name as the key to the number of downloads. So, later in the code, we can write $file_downloads["archive.zip"] and print the number of downloads.

    Below you can see the code that generates the elements of the list:

    demo.php- middle part

    Foreach($files_array as $key=>$val) ( echo "

  • ".$val." ".(int)$file_downloads[$val]." download
  • "; }

    Everything is done simply with a foreach loop of the $files_array array. After that, everything is output using echo.

    Now let's take a closer look at how file tracking works.

    download.php

    // Error checking : error_reporting(E_ALL^E_NOTICE); // Enable the db connection file: require("connect.php"); if(!$_GET["file"]) error("Missing parameter!"); if($_GET["file"](0)==".") error("Wrong file!"); if(file_exists($directory."/".$_GET["file"])) ( /* If and the visitor is not a search bot, count downloads: */ if(!is_bot()) mysql_query(" INSERT INTO download_manager SET filename="".mysql_real_escape_string($_GET["file"])."" ON DUPLICATE KEY UPDATE downloads=downloads+1"); header("Location: ".$directory."/".$_GET["file"]); exit; ) else error("This file does not exist!"); /* function helpers: */ function error($str) ( die($str); ) function is_bot() ( /* This check function on the robot*/ $botlist = array("Teoma", "alexa", "froogle", "Gigabot", "inktomi", "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory", "Ask Jeeves", "TECNOSEEK ", "InfoSeek", "WebFindBot", "girafabot", "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp", "msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz", "Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot", "Mediapartners-Google", "Sogou web spider", "WebAlta Crawler" ,"TweetmemeBot", "Butterfly", "Twitturls", "Me.dium", "Twiceler"); foreach($botlist as $bot) ( if(strpos($_SERVER["HTTP_USER_AGENT"],$bot)!==false) return true; // Is a bot ) return false; // Not a bot)

    It is important to check whether your visitor is a human or a search engine robot. Robots are nice, but let's not let them distort our statistics. That is why the row in the database is updated only after the is_bot() check.

    Step 4 -MySQL

    As we noted in the last step, the number of downloads is stored as a row in the download_manager table. First, let's explain how this query works:

    download.php

    INSERT INTO download_manager SET filename="filename.doc" ON DUPLICATE KEY UPDATE downloads=downloads+1

    It tells MySQL to insert a new row into the download_manager table, and set the filename row field to the value of the file called for download. However, the filename field is designated as a unique index in the table. This means that each row can only be inserted once, otherwise a duplicate key error will occur.

    This is where the second part of the query will work - ON DUPLICATE KEY UPDATE will tell MySQL to add one to the downloads column if the file already exists in the database.

    Thus, new files will be automatically added to the database during the first download.

    Step 5 - jQuery

    In order to make real-time tracking, it would be good to update the counter next to the file name after each download.

    We'll do this with jQuery:

    script.js

    $(document).ready(function()( /* The code is executed after the page is loaded*/ $("ul.manager a").click(function()( var countSpan = $(".download-count",this); countSpan.text(parseInt(countSpan.text())+1); ) ); ));

    We simply assign a click handler to links that lead to files, and on each click we add a value.

    Step 6 -htaccess

    There is one more thing that needs to be done. Download.php will redirect the user to the requested file, which was passed as a parameter. However, you may have noticed that browsers try to open some types of files directly. We also need to initiate their download. This can be done with a few lines inside the .htacess file, which is located in the files folder.

    ForceType application/octet-stream

    Now our counter is completely ready!

    Conclusion

    In order for the demo to work, you need to recreate the download_manager table in the MySQL database. You can find the required SQL code in the sources.

    After that, add your data for connecting to the database in the configuration.php file.

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

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

    Number of jumps:

    We have created a button with id="btnSend" , we will display the counter in a span with id="countView" , 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. This is necessary to display from the file where the counter writes, the number of downloads already made and display them in a span with id="countView"

    /*get the current number of downloads*/ $(document).ready(function()( //prohibit cache ajax request //otherwise the counter will fail $.ajaxSetup((cache: false)); var html; $.ajax (( //how we will pass data type: "GET", //where we pass url: "count.php", //what data we pass data: (flag: 2), //event after receiving a response from count.php success : function(data)( html=data; //output the current number of downloads $("#countView").html(html); ) )); /*hang an event on the file download button*/ var clickevent=false; //click check flag //click handler $("#btnSend").click(function()( if(!clickevent)( $.ajax(( //how we will send data type: "GET", //where we pass url: "count.php", //what data to send data: (flag: 1), //event before sending ajax beforeSend: function()( //if the button was clicked then true clickevent=true; ), //event after receiving the response, //get the data in data success: function(data)( //after performing the actions, allow again //processing click the button clickevent=false; html=data; //output 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"); ) )); ) return false;//prohibit processing the event on click )); ));

    To prevent repeated erroneous pressing of the submit button, I introduced the clickevent flag into the script. Until the response from count.php is returned with the updated counter data, clicking on the button will be prohibited. I think the work of the code after clicking on the button is more or less clear. After clicking on the download button, the data is transferred to the count.php file, where they are processed and the updated counter data is returned, a redirect to the download link occurs and, accordingly, the file is downloaded.

    Let's now break down the heart of our script, namely the count.php file.

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

    Here I think the same thing 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 issue more simply. I needed a counter for one page. I took the count.php file and transferred it to the joomla template that is currently connected (at the root of the site templates/your_template). Do not 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 are creating, and the js code can also be embedded into the page, or connected as a separate file. For example, I have a separate file (it is located in the template js folder). In the template itself, in the header, the connection is made through the code

    And don't forget to get with an ajax request, we are accessing the url: "/index.php?tmpl=count" and not the url: "count.php", . Just like that, I just screwed the file download counter to joomla.


    2022
    maccase.ru - Android. Brands. Iron. News