Astrid
Astrid

Reputation: 1312

php delete image from server after upload & display

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?

Upvotes: 4

Views: 4891

Answers (3)

cryocide
cryocide

Reputation: 741

When you echo the url of an image with img src you're just sending the browser the url of an image, not the actual image data. The image needs to remain on the server if you want it to be viewable by this approach.

You could use bwoebi's solution to pass the actual image data instead of a link, but a better solution is just to keep the images on the server and periodically delete old files.

Upvotes: 1

M8R-1jmw5r
M8R-1jmw5r

Reputation: 4996

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.

Upvotes: 3

bwoebi
bwoebi

Reputation: 23777

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'])

Upvotes: 6

Related Questions