I'm looking for a small script that I can use to limit the number of downloads per day for a specified file, or limit the bandwidth for said file per day.

Any Ideas?
:D

Dani AI

Generated

Two practical ways to solve this — and which to pick depends on whether you need a global per-file/day quota (application-level) or raw per-connection/per-request bandwidth throttling (server-level). was right to suggest checking the web server first: server modules can throttle cheaply; an app-level script gives precise per-file or per-account daily limits.

Server-level (best for bandwidth)

  • Use the webserver or a fronting proxy/CDN to throttle. Examples: Apache has rate-limiting modules (mod_ratelimit / third-party modules), nginx supports limit_rate/limit_conn, and CDNs can enforce transfer caps. These are efficient because the webserver handles streaming; they are not great if you need a single shared daily quota across many requests unless the server module explicitly supports per-resource accounting.
  • Offload file serving with X-Sendfile/X-Accel-Redirect so PHP only checks policy and the server streams the bytes.

Application-level (best for per-file/day counts or byte quotas)

  • Implement a single download.php?id=... endpoint that:
    1. validates the id and maps to a safe filesystem path,
    2. atomically checks/updates a per-day counter in a DB,
    3. denies the download when the count or daily bytes exceed the limit,
    4. delegates serving to the webserver (X-Sendfile) or streams in chunks if necessary.
  • Table example:
    CREATE TABLE download_counts (
    file_id VARCHAR(255) NOT NULL,
    day DATE NOT NULL,
    count INT UNSIGNED NOT NULL DEFAULT 0,
    bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
    PRIMARY KEY (file_id, day)
    );
  • Atomic increment pattern:
    INSERT INTO download_counts (file_id, day, count, bytes)
    VALUES ('file123', CURRENT_DATE, 1, 12345)
    ON DUPLICATE KEY UPDATE count = count + 1, bytes = bytes + 12345;

Notes and cautions

  • Use DB atomic ops or transactions to avoid race conditions under concurrent downloads.
  • Count bytes served (not just requests) if enforcing bandwidth limits; account for Range requests/resumes.
  • Don’t throttle per-byte in PHP with sleeps for production — it wastes CPU and ties up PHP processes. Server modules or CDNs are the scalable choice.

Recommended Answers

All 3 Replies

I'm sure I could come up with a hack job of a way, but I know there is a better way (maybe with the web-server's configuration?)

do you know where i could get a php script that would do this?

Did you check if the webserver's settings could do this?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.