[英]PHP - Delete file after upload
I've developed a small tool that allows a users upload a HTML file.我开发了一个允许用户上传 HTML 文件的小工具。 Once uploaded, I run an Ajax request which gets the content of that HTML file and outputs it to a textarea.
上传后,我运行一个 Ajax 请求,该请求获取该 HTML 文件的内容并将其输出到文本区域。
PHP: PHP:
if (move_uploaded_file($src, $dest . $uploadfile))
{
echo $uploadfile;
}
else
{
echo "Error Uploading file";
}
Ajax:阿贾克斯:
$.get( "uploads/" + response, function(data) {
$('#output').text(data);
});
Everything is working so far.到目前为止一切都在工作。
Now what I want to do is delete that file once the content has been outputted to the textarea.现在我想要做的是在内容输出到 textarea 后删除该文件。 I'm aware I could create a cron job to execute a script every X amount of minutes, however I would rather do it there and then.
我知道我可以创建一个 cron 作业来每 X 分钟执行一个脚本,但是我宁愿在那里然后做。
I tried using the following, but naturally this deletes the file before the Ajax request is executed.我尝试使用以下方法,但自然会在执行 Ajax 请求之前删除文件。
if (move_uploaded_file($src, $dest . $uploadfile))
{
echo $uploadfile;
if($delete) { // $delete is a boolean argument for the function
unlink($dest . $uploadfile);
}
}
So how would I go about deleting the file once the content has been retrieved?那么,一旦检索到内容,我将如何删除文件? Would I create another Ajax request to execute a delete function once the first request is complete?
一旦第一个请求完成,我会创建另一个 Ajax 请求来执行删除功能吗? Or is there a way I can do this all at once?
或者有什么方法可以一次完成这一切?
Make your ajax request to a php file, that echos the content then deletes the file:将您的 ajax 请求发送到一个 php 文件,该文件回显内容然后删除该文件:
//ajax
$.get( "/get-file.php?file=uploads/" + response, function(data) {
$('#output').text(data);
});
. .
//get-file.php
$file=$_GET['file'];
echo file_get_contents($file);
unlink($file);
Note that there are some security issues related to reading a user-submitted filename (they could pass in the filepath of a secure file, eg "passwords.php").请注意,有一些与读取用户提交的文件名相关的安全问题(它们可以传入安全文件的文件路径,例如“passwords.php”)。
Better would be to store and retrieve the value from SESSION:更好的是从 SESSION 存储和检索值:
if (move_uploaded_file($src, $dest . $uploadfile))
{
$_SESSION['uploadedfile']=$dest . $uploadfile;
echo 'success';//the return is no longer used
}
else
{
echo "Error Uploading file";
}
//ajax
$.get( "/get-file.php, function(data) {
$('#output').text(data);
});
. .
//get-file.php
$file=$_SESSION['uploadedfile'];
echo file_get_contents($file);
unlink($file);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.