UPDATE:
- I’d like to thank a friend who detected this bug:
Microsoft Windows users, please change the following line:
if (realpath($allowedfilepath).”/$file” …
to,
if (realpath($allowedfilepath).”\\$file” …
Serving files through PHP is basically needed in two cases:
1) When you want to count the number of times it has been downloaded.
2) When you don’t want to give direct access to the file from your server. (Hiding or protecting file path)
-Being able to serve files through PHP can also be useful when you want only specific users to download the files in your server, for example: Only registered users, or users who pays for the file, like online PDF books.
-You can also use it to ban or allow specific files to your users.
It gives you full control over transferring of files in your server.
Here is a code snippet to serve a file using php script.
Step1: Copy the following code and save it as, getfile.php:
To use the code:
1) Make a subfolder inside inside your home directory named ‘files’.
2) Put all your files that you want to server through php, inside that folder.
3) Copy and save the program as ‘getfile.php’ on your home directory.
4) Restrict direct access to all the files inside the sub-folder (files) you just created.
Restricting direct access your files:
If you do not restrict direct access to the files you wan to server through your PHP program, people can directly access/download the file like:
http://your-site.com/files/book1.pdf
Step2: To prevent this, make a file named ‘.htaccess’ inside the ‘files’ directory and write following text on that file:
#deny all access
deny from all
IndexIgnore *
Now, your files won’t be accessible directly like mentioned above, users will only be able to access the file like:
http://your-site.com/getfile.php?file=book1.pdf
That is, if you have allowed this on getfile.php.
You can also make a database to store number of times a particular file has been downloaded.
If you want a code to do this, please comment below and let me know.
!Cheers









Thanks guru,
Wow it rocks man, I was worried how to hide real path of my ebooks that i sell.
It just rocks!