Chase Rocker
Chase Rocker

Reputation: 1908

Prevent IPs from downloading a file multiple times on server

I have a program that users can download from my site via a button which posts to a php page. The php logs the download request into my DB then serves up the actual program for them to download. However, I've noticed from time to time that certain IPs will download the program every half hour...sometimes hundreds of times over many days. Not sure what it is, assuming it's a bot, and the IPs are always in countries like Romania or Hungary.

Initially I was blocking IPs in my .htaccess, but I don't want to keep doing that every time. So I've added code to my php which only allows users to download the program a specific # of times each day. That works fine, however, it's easy enough for someone to just get the direct url to my program and download it that way bypassing the php logic.

1) Is there are way to prevent this? Can the .htaccess be modified to prevent direct downloads of the file but allow my php to serve it up?

2) Should I even be worried about this at all? I'm using a shared server so I'm really just concerned about the bandwidth impacts.

Upvotes: 0

Views: 1237

Answers (1)

Haotian Liu
Haotian Liu

Reputation: 886

If what you want is not allowing users to bypass the PHP logic, you can render and output the file with PHP script.

<?php
$file = some file from query;

if (some logic matches)
    die('Download forbidden');

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

See: http://php.net/manual/en/function.readfile.php

Suppose your file is stored in /files/, put the script in somewhere like /down.php, and add the following code in .htaccess in /files/.

Deny from all

More on this, you can see: Deny access to one specific folder in .htaccess

Besides, if you really care about the bandwidth, you can enhance your download prohibit logic, like create user system, or put the user IP into the database to manage/restrict the total download bandwidth of each user.

Upvotes: 1

Related Questions