dre26973 2013-03-06 04:17
浏览 25
已采纳

使用Silex / Symfony提交响应后删除文件

I'm generating a pdf using Knp\Snappy\Pdf in my Silex application. the file name is random and saved to the tmp directory.

$filename = "/tmp/$random.pdf"
$snappy->generate('/tmp/body.html', $filename, array(), true);

I think return the pdf in the response,

$response = new Response(file_get_contents($filename));
$response->headers->set('Pragma', 'public');
$response->headers->set('Content-Type', 'application/pdf');

return $response;

The pdf is displayed in the web browser correctly. The file with the random filename still exists when the request is finished. I can't unlink the file before returning the response. I've tried registering a shutdown function with register_shutdown_function and unlinking the file from there. However that doesn't seem to work. Any ideas?

  • 写回答

3条回答 默认 最新

  • dongyao2022 2013-03-06 05:15
    关注

    You can use the finish middleware for that:

    A finish application middleware allows you to execute tasks after the Response has been sent to the client (like sending emails or logging)

    This is how it could look:

    $app->finish(function (Request $request, Response $response) use ($app) {
        if (isset($app["file_to_remove"])) {
            unlink($app["file_to_remove"];
        }
    });
    
    //in your controller
    $app["file_to_remove"] = $filename;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题