Skip to content
PHP Logo

What are some potential ways to implement a download counter in PHP for a filebase system?

When working with a filebase system in PHP, you may want to implement a download counter to track the number of times a file has been downloaded. One way to achieve this is by updating a counter in a database each time a file is downloaded. This can be done by incrementing a counter associated with the file's ID in the database.

php
// Assuming you have a database connection established

// Get the file ID from the URL or form submission
$file_id = $_GET['file_id'];

// Update the download counter in the database
$update_query = "UPDATE files SET download_count = download_count + 1 WHERE id = $file_id";
mysqli_query($connection, $update_query);

// Retrieve the file path from the database based on the file ID
$file_query = "SELECT file_path FROM files WHERE id = $file_id";
$file_result = mysqli_query($connection, $file_query);
$file_row = mysqli_fetch_assoc($file_result);
$file_path = $file_row['file_path'];

// Serve the file for download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
readfile($file_path);