douwen4125 2014-08-19 16:06
浏览 42
已采纳

PHP - 如果用户退出网页,则取消链接文件?

I've created a webpage that requires users to fill out a form, which includes uploading an image. To allow the users to view the uploaded image without refreshing the page, I store the image in a temporary directory using AJAX. If the form is not filled out correctly, on submission the image in the temporary directory gets deleted. However, if the user closes their web browser or refreshes the page after uploading the image without submitting the form, it stays in the temporary directory.

Is there a way of detecting whether the user has quit/refreshed the page and subsequently unlinking the image file in the temporary directory?

  • 写回答

2条回答 默认 最新

  • duanfu6160 2014-08-19 16:24
    关注

    Due to the nature of the client-server communication in HTTP there is no "simple" way to do that.

    The best practice would be to store the image in a temporary directory and then to either store a timestamp with the image and run a job that deletes all images older than 30 minutes (or whatever timeout you want) or link the image to the user-session and check if the session still exists - if the session dies for whatever reason, delete the image.

    You can set session-handlers with

    bool session_set_save_handler ( callback $open , callback $close , callback $read , callback $write , callback $destroy , callback $gc )

    Use the destroy and gc handlers to delete the files.

    You will have to call the script to define the session save handlers at least in every script that works with sessions. You could put the code in an include file and include it whenever needed, or use the auto_prepend_file directive in php.ini

    If you are using jQuery you can bind to the beforeunload event:

    $(window).bind("beforeunload", function() {
         //send a request to delete the file
    }
    

    You could of course also use Javascript to send keepalive-requests to your server (using AJAX for example) and delete the image when those keepalives stop. That would probably be the most difficult and unreliable method and I would not recommend it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?