I'm trying to delete a picture (.jpg) from server after the first time showed. But the file is deleted (unlink();) before showed. I've already tried with sleep() but this only delay the loading and after all the file is deleted before showed.
Asked
Active
Viewed 7,680 times
5
-
1If you post your relevant code, this is most likely an easy fix. Without seeing your code, you probably won't get any (useful) answers. – Wesley Murch Apr 22 '11 at 23:35
3 Answers
6
You could use mod_rewrite to redirect jpg requests to a script that loads the image into memory, deletes the file, then serves up the image. IMO, this is the simplest and easiest solution. Unsafe example below...
Example .htaccess file:
# Turn on URL rewriting
RewriteEngine On
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]
index.php
<?php
$image_file = $_SERVER['PATH_INFO'];
// clean data, strip current/parent directory to block transversal, etc...
if (file_exists('images/' . $image_file))
{
$image_data = file_get_contents('images/' . $image_file);
// determine image mimetype using phps mimetype functions
unlink('images/' . $image_file);
header('Content-Type: image/jpeg');
echo $image_data;
}

John Himmelman
- 21,504
- 22
- 65
- 80
-
1I'm not convinced that the OP wants to delete _all_ JPG images after first viewing. Additionally, your `.htaccess` seems completely unrelated to the question/answer? – Lightness Races in Orbit Apr 23 '11 at 04:05
-
@Tomalak, I assumed OP wanted a one-time-view image scripts. Above code is only an example, he'd need to modify it to reflect the correct images path, add mimetype detection, etc. It uses htaccess to essentially proxy requests through a php script. The script returns the image and deletes it (some image hosts have a single-view, its useful if you want to share an image with a single person, and don't want it to become a permanent fixture on the internet). – John Himmelman Apr 25 '11 at 14:22
-
1Perhaps the answer ought to include that as a caveat, before he comes back complaining that we deleted all of his photos :) – Lightness Races in Orbit Apr 25 '11 at 23:08
2
- Copy the image contents from the file into memory;
- Delete the image file;
- Stream the original contents from memory to output.
Best I can do with the vagueness, I'm afraid.

Lightness Races in Orbit
- 378,754
- 76
- 643
- 1,055
0
This is because all PHP is executed in the stack prior to rendering the output. You will need to set up a function to flag the file for deletion on the next page load.
OR you can set up some AJAX to delete the picture after the document has loaded.

Chuck Burgess
- 11,600
- 5
- 41
- 74
-
Output is rendered _during_ PHP execution. That's what PHP scripts do. – Lightness Races in Orbit Apr 23 '11 at 04:04