How can PHP be used to track and limit the number of downloads for a file?

To track and limit the number of downloads for a file using PHP, you can create a database table to store download counts for each file. Whenever a user requests to download a file, you can increment the download count in the database. You can also check the download count before allowing the user to download the file and limit the number of downloads based on a predefined threshold.

<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "downloads";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get file ID from URL parameter
$file_id = $_GET['file_id'];

// Check download count for file
$sql = "SELECT download_count FROM files WHERE id = $file_id";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $download_count = $row['download_count'];

    // Limit downloads to 5
    if ($download_count < 5) {
        // Increment download count
        $new_download_count = $download_count + 1;
        $sql = "UPDATE files SET download_count = $new_download_count WHERE id = $file_id";
        $conn->query($sql);

        // Allow file download
        // Add code to serve the file here
    } else {
        echo "Download limit reached for this file.";
    }
} else {
    echo "File not found.";
}

$conn->close();
?>