Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php delete image from server after upload & display

Tags:

html

php

image

Sending an image in my php form, it gets saved onto my server and at the action.php page it gets displayed. Now when I try to:

echo '<div id="image"><img src="'.$target_path.'" width="280" height="280"></div>';

it works just fine... but if I add unlink($target_path); at the end of my php code it will not even display the image even though it gets deleted AFTER displaying the image...

So the question is, how can I display the image and deleting it at the same time so my server does not gets stuffed with user pictures?

like image 412
Laurent Avatar asked Oct 25 '25 00:10

Laurent


2 Answers

Try another thing: output the image base-64 encoded.

$contents = file_get_contents($file);
$base64 = base64_encode($contents);
echo '<div id="image"><img src="data:image/jpg;base64,'.$base64.'" width="280" height="280"></div>';

(instead of move_uploaded_file() etc, use as $file variable the $_FILES[...]['tmp_name'])

like image 174
bwoebi Avatar answered Oct 26 '25 14:10

bwoebi


You can achieve this by creating a little script that gets the image-filename and will delete it after it has been retrieved:

<?php
$file = image_file_from_parameter($_GET['image']); 
headers_for_file($file);
readfile($file);
unlink($file);

In your HTML output you then link to that script:

<img src="path/to/image.php?image=893sudfD983D" />

If you set nice caching headers, the user won't notice that your server did serve the file only once.

like image 36
M8R-1jmw5r Avatar answered Oct 26 '25 16:10

M8R-1jmw5r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!