It is a question for which I already have an answer, but I thought that it could be good for more than one person and in several cases. Of course, I accept new answers with other methods.
It is about being able to save the impressions of the images in an already existing site in which I cannot/must modify the src of the same because it is complex or extensive, for example.
The objective is to save a counter in the database of an image of an html with the following form:
<img src="img/foto.jpg" alt="foto">
I have the database with a table "images" and with an autonumber id, the path and name of the image and a default counter set to 0.
Since you cannot modify the paths of the images and put, for example, in the src: track.php?img=foto1.jpg
It occurred to me to do it as follows:
I create an image.php file with the following content, in this example, I do it only for .jpg type images:
Watch out! since I have omitted some basic security steps to make it simpler.
This file will receive a variable with the image to display and will be in charge of saving in the database, an increment in the impressions field and then it will return the image.
Now it is about capturing the images and for this, I create an .htaccess file with the following content:
And that's it, now every time an image is loaded, either in the src, directly or through javascript, the .htaccess rule will take care of redirecting to image.php passing the img parameter with the image to display.
This, of course, can be done with any file, be it a .js, an .html or within a specific folder.