Reputation: 67
Is there a way to count how many views a specific file has had on my server?
So for example I've some file on data/
directory, data1.pdf
, data2.pdf
, data3.pdf
. And the URLs are, for example, https://www.example.com/data/data1.pdf
. How can I count the total number of view on data1.pdf
?
In my case, the user access to resource by QR code scan. So I need to catch this action to count the total number of view by specific resources.
Moreover I need to update count value in a MySQL database, for example data1.pdf
: 10 views, data2.pdf
: 8 views, data3.pdf
: 6 views.
What's the best way to do this?
Upvotes: 0
Views: 151
Reputation: 683
You need to intercept the "intent" of the user before giving her the files she requested.
There are multiple ways to do that. Since you already have an interface to the link (the QR-Code), you can use it to first send the user to a first "counter page" at the url www.example.com/serve.php?f=data/data1.pdf
(that would be the url encoded in the QR-Code)
The file would look like that :
<?php
$requested_file = $_GET['f'];
$conn = //init your connexion
$conn->execute("UPDATE counters SET counter = counter + 1 WHERE filename = ?", requested_file);
header("Location: "+$requested_file);
exit;
In that case, it will be a little more tricky because you still want to intercept the user before she reaches the file but she already has a direct link.
I woul suggest using a .htaccess
file that redirect all the request in a directory to our serve.php
. Be aware that by default this htaccess file will redirect ALL traffic in the data
folder to our php file so you will certainly need to do some extra work to integrate it inside your domain
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} ^/data [NC]
RewriteRule ^(.*)$ /serve.php?f=$1 [NC,L,QSA]
and serve.php
will be changed to :
<?php
$requested_file = $_GET['f'];
$conn = //init your connexion
$conn->execute("UPDATE counters SET counter = counter + 1 WHERE filename = ?", requested_file);
$content = file_get_contents($server_path_to_requested_file);
header("Content-type: application/pdf"); //change that if you handle multiple files
echo $content;
exit;
Drawback here again is that you need PHP to read and spit out the content of the file (that will be slower than directly serving the file)
Upvotes: 1