Note: Please have a good grasp of the question and my efforts before you are tempted for any negative reaction. If there is a mistake in my approach anywhere gie me a chance to correct it.
I have a little php script on a site running on wordpress. It basically resizes the uploaded image and force offers the resized image as download prompt. Please note that I do not have any download link on the concerned page. The script works well, resizes and creates image and all, except for the part that when the downloaded image is opened in a general windows software like windows photo viewer it says "Windows photo viewer cannot open this picture, as it doesn't support this file format", but when I open it in Photoshop it displays really well. I have opened the downloaded image also in Firefox browser 24.0, wherein it says "the image file /path/to/file/" cannot be displayed because it contains errors.
Here is relevant php snippet in order to know what is happening. If needed I will write the whole code. It will be great if you can point out the mistake in the code while I am doing my own research efforts.
// create a new image resource to be utilized by imagejpeg
$new = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
$filename = uniqid();
$file = 'uploads/' .$filename. '.jpeg';
imagejpeg($new, $file, 100);
$size = filesize($file);
header("Content-Type: application/force-download; name=\"" . basename($file). "\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
header("Expires: 0");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
readfile($file);
EFFORTS UPDATES :
First update : I read this thread and based on it's suggestions tried to add ob_end_clean()
before the readfile($file);
and also comment out the $size, still getting corrupt images.
Second Update : I have also tried the code given below, as was suggested in the solution here. Apart from this, please keep in mind that I have also tried minor corrections after having read other numerous threads here, and i am still looking.
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, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
This last effort makes me think that maybe something is wrong with the way I am assigning the image-extension in my original code. Currently I am assigning it as $file = 'uploads/' .$filename. '.jpeg';
which could be wrong. If I am how should I correct it ?