Search code examples
phpweb-serviceswebmodx

Web Server - How to execute PHP script when accessing a file?


I would like to run a PHP code when a file on the web server is accessed (e.g. /../../somefile.pdf).

I need to display a disclaimer when a user access the website for the first time. I made this possible executing a PHP script every time a webpage is accessed but I don't know how to run the script when a file instead is accessed of a webpage. Is this possible?

Thank you!


Solution

  • When you want to track downloads, there are two ways:

    1. Change the download URL to go via a PHP file i.e. instead of <a href="/../../somefile.pdf">..</a> try <a href="/download.php?file=/../../somefile.pdf">..</a>
    2. Use rewrite in .htaccess (Apache Rewrite mod) to redirect the download URL to a PHP file first, for example: RewriteRule ^download_directory/(.*)$ /download.php?file=$1 [L,QSA]

    In your file, download.php you have two options again:

    1. Read the file using the Path in the file param, and use PHP to echo the output. (This method is insecure as the user may modify the path in the file param and get a file he is not supposed to access.)
    2. Since your files are in the webroot (i.e. they can be access directly) it is best to redirect the user to the actual file once your tracking code completes execution using header('Location: ' . $_GET['file']);