I am trying to download uploaded files over https and, while the files themselves download, they cannot be viewed.
I have tried JPG, DOC and XLS files and all give the same problem and, in all cases, if I download via FTP they open perfectly and they open fine in the browser pre-download using the script.
Here is a subset of the script showing the code I am trying to use? Any idea why it downloads garbage?
$_file = sanitiseData($_GET['doc']);
$filename = '/doc_uploads/'.$_file;
if (file_exists($filename)) {
header('Content-type:image/jpg');
header('Content-Disposition: attachment; filename="'.$_file.'"');
echo file_get_contents($filename);
} else {
echo "The file $_file does not exist";
}
Here is a sample of the garbage when trying to view a downloaded JPG via browser:
����JFIF��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90 ��C ��C ��R�”�� ���}!1AQa”q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq”2�B���� #3R�br� $4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������?�P��q\�O�^�-�C�z�z����o�N��P;��.i�~k+Զ���|�7`�’e����G�>+���_�6�%�Ԓ��Y�w���P�~.�����2E�� ��”��ڗȌ��ms����[���?��%|”�R5�s�c������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=?V��>���IG�=?V��>���I_Q@w����o���������o����������=GU��>���� �N�v������%|!E~�xO� �ỹx_P����j(�z����_
Your best bet is to use readfile(…). PHP’s website has a nice example that should help you. I use it on my website and it works like a charm: