I am working on a wordpress cms. I have a little no-fancy php script which basically resizes the uploaded image to assigned limits, and outputs the resized image back to the visitor's browser, so he can right-click-download. Given below is a relevant portion of the script, but if need I shall provide complete code.
ob_start();
imagejpeg($new, null, 100);
echo '<img src="data:image/jpeg;base64,' . base64_encode(ob_get_clean()) . '">';
echo '<br><br>RIGHT CLICK AND SAVE IMAGE<br><br>';
imagedestroy($new);
Bottomline is I would like to force the download link for the resized image, once resize is done.
EFFORTS AND UPDATES:
First update
: I am currently going through this article on forced-download-links as suggested on another relevant thread on SO. But I am stcuk when it says - "First things first… we need to define the path to our file in PHP (as a string).". Problem is, since I do not want any image file saved on my server and so the second parameter of the imagejpeg() function is set to NULL
. So I cannot define a path to my file. Or can I ? How do I do this. Hope it was clear and concise. A solution would be great, if not please give me good starting pointers.
Second update
: According to the suggestion below I have made some progress. As you can see in the code below, I am able to now save the image, but i am still unable to echo out the output image as a download prompt. Please suggest a correction.
$filename = uniqid();
$file = 'uploads/'.$filename.'.jpeg';
$final_image = 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);
unlink($file);
Third Update
: Found out that I can use relative paths so I dont need to load wordpress load.php, changed the code accordingly. Issue still remains.
Fourth Update : Tried this code as suggested in solutions in this thread. Same result, prints out gibberish instead of offering a download link. This is getting frustrating, I must be getting close :).
Final Update : There was javascript parsing the output of the script, so I was getting all gibberish. I removed it now everything is okay.