I have a project where my users will be able to download a file (pdf,docs,txt,images etc.). So I am providing a link to download like this-
<li><a href="home.php?search=<?php echo $search_string; ?>&search_submit=Search&page=<?php echo $page; ?>&download=<?php echo $result_materialsID; ?>">
Download</a></li>
Then I check in my $_GET method I check a condition like this-
if(isset($_GET['download']))
{
$material_to_download = $_GET['download'];
$result_update_materials = mysqli_query($connection,"Update Materials SET numDownload=(numDownload+1) where materialsID = {$_GET['download']}");
if(!$result_update_materials)
{
die("Database update numDownload materials failed:".mysqli_error($connection));
}
$result_get_materials_l = mysqli_query($connection,"SELECT downloadLink FROM Materials where materialsID = {$_GET['download']}");
if(!$result_get_materials_l)
{
die("Database get materials failed:".mysqli_error($connection));
}
else
{
while($row = mysqli_fetch_array($result_get_materials_l))
{
download_file($row[0]);
}
}
}
It is under a nested ifs where I checked other $_GET variables. The function download_file is given below:
function download_file($file)
{
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
}
}
Problem: The problem is, when I click on a download link, the file downloads fine, and as the code goes, my database should increment numDownload by 1. But it increments by 2. numDownload is keeping track of the total number of downloads of that file. So I think that the update part of my code is actually running twice.
I tried unset($_GET['download'])
but it didn't help. Any idea what's going wrong? Thanks.