I have a site where I want a user to be able to download some data as a text file, without permanently saving the file on my server. The approach I'm trying is to use JavaScript to send a POST, using PHP to generate and save a text file. On success, JavaScript will open that file in a separate window. After a few seconds delay, it will then send a POST with the file to delete.
I have most of it working, but for some reason, when I try to delete the file, I keep getting an error - No such file or directory. I don't know why, especially since using a test file to delete in the same directory works fine. Here's what I'm using on the javascript side:
////CREATE FILE
function exportGroup() {
$.post("../Modules/Export_Mod/export_mod.php",
{ submit:'export',
groupIndex: groupSelect.value,
userRole: 'admin',
serial: <?php echo $serial;?>
},
function(data,status){
//open created file in new window
window.open("../Modules/Export_Mod/"+data);
removeExport(data);
});
};
//////REMOVE FILE
function removeExport(filename) {
///After 1 second, send post to delete file
setTimeout(function() {
$.post("../Modules/Export_Mod/export_mod.php",
{ submit:'removeExport',
file: filename
},
function(data,status){
data;
});
}, 1000);
}
and my PHP:
//I'm creating the file successfully with this
...
$filename = $groupName."_group_export.txt";
$content = $header.$dataStr;
$strlength = strlen($content);
$create = fopen($filename, "w");
$write = fwrite($create, $content, $strlength);
$close = fclose($create);
But when I try to delete a second (or more) later using this:
if (($_POST)&&($_POST['submit']=='removeExport')){
$file = $_POST['file'];
unlink($file); ///works when using an already-existing file in the same directory ... unlink('test.txt');
}
I get the error. The first thing am wondering is if I'm approaching this the right way. If not, is there a better way to do it? And then the second thing I'm wondering is why I'm getting this error and what I need to change to make it work.