PHP:: How to delete a file from server after is read. Unlink() is executed before

。_饼干妹妹 提交于 2019-12-07 04:49:59

问题


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.


回答1:


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;
}



回答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.




回答3:


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.



来源:https://stackoverflow.com/questions/5760969/php-how-to-delete-a-file-from-server-after-is-read-unlink-is-executed-befor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!