I am trying to download a zip file through php. The filename is stored in a database and all the files are stored in a folder named "products". This is the code I am using:
function downloadProduct($id, $connection){
$sql = "SELECT filename FROM productdata WHERE id = '$id'";
$query = mysqli_query($connection, $sql);
if(mysqli_num_rows($query) == 1){
$file = basename(mysqli_fetch_assoc($query)["filename"]);
$filePath = "products/" . $file;
if(file_exists($filePath)){
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($filePath);
exit;
}
echo("<script>alert('This file (' + '$file' + ') does not exist.')</script>");
}
else{
echo("<script>alert('Can not download this file.')</script>");
}
}
The filepath is always the correct one (when I alert it), but when the file is read, it does not stop displaying these characters on the bottom of my page:
.I*��9UZ��3�8s�A��u�sz]���~������x�����9&NU�""c$M��.��^��N���U�ַΣ�p�hc��K��b�>�Sզ�<��k��l��rofz
~���ۛ9�[��͜���֡�\�n�z�y��϶T�W�;�᧔e���{qO #m�/�#�L�=�a�_��e��l)5�e�q�&�#��g��s-������{L|i�[8�ZV�|v+�\��G���I�iDShS�g�n(7���� W���˛������T�k�p�K���/]�^��7��,Uwf�ZѼ�"U���L\T%���7<�MP���,_���S�3�>M�9�>ǩ_�V��ᯇ.�iUι�a����F�K�ڦéc�9��ܗki�KK�u��\�u�F䨪���b������3��q���ָ~�e\o����:G�U�q��K���V��
I also tried different headers, but it didn't changed anything. The code seems to be correct for me. I hope someone can help me. Thank you.