Search code examples
phpimagetemporary-filestmp

Showing temporary images with PHP


I've got a function set up that decrypt AES encrypted images into its original files. For making a long story short, you would call it like this: DecryptFile($pathtofile)

This would create a file on folder tmp/ with the decrypted image and will return the path, for beeing able to insert the image via <img src="path">. I just need to show it on the current execution of the script, and delete it as soon as posible.

What I tried to do is unlink("path") for deleting the file at the end of the script, but if I do this there isn't enough time for the browser to load up the image, and anything will show up.

I checked out if I could manage with the tmpfile() function, but it seems that is suited for temporary download handling, as I can't think about a way of showing any image with <img> using this function.

Any ideas out there guys?


Solution

  • One possible solution would be to store the image data directly in the tag with a data URI. But then if someone were to copy down the source code they would essentially have the image, likewise if something was caching your page content... The again I suppose thats no different that "Save image as" or doing a full page download. But it would save you from having to mess with copy/mv/symlink/unlink.

    <?php
    
    $decrypted = DecryptFile($pathtofile);
    $data = base64_encode(file_get_contents($decrypted));
    $info = getimagesize($decrypted);
    $image = sprintf('data:%s;base64,%s', $info['mime'], $data);
    ?>
    
    <img src="<?php echo $image; ?>" />