PHP ::如何在读取后从服务器删除文件.之前执行Unlink()

Dan*_*iel 5 php temporary-files unlink

我想在第一次显示后从服务器删除图片(.jpg).但是在显示之前删除了文件(unlink();).我已经尝试过sleep(),但这只会延迟加载,并且在显示之前删除所有文件.

Joh*_*man 6

您可以使用mod_rewrite将jpg请求重定向到将图像加载到内存中的脚本,删除文件,然后提供图像.IMO,这是最简单,最简单的解决方案.以下不安全的例子......

示例.htaccess文件:

# Turn on URL rewriting
RewriteEngine On

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]
Run Code Online (Sandbox Code Playgroud)

的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;
}
Run Code Online (Sandbox Code Playgroud)


Chu*_*ess 0

这是因为所有 PHP 在渲染输出之前都在堆栈中执行。您需要设置一个函数来标记文件以在下一页加载时删除。

或者您可以设置一些 AJAX 在文档加载后删除图片。