Pass a js filename to php using a cookie and unlink it

I want to pass a js filename to php using a cookie and unlink it.

PHP FILE REMOVER: EXTERNAL PHP SCRIPT = ‘purge.php’

purge.php:

<?php 
$cookie_name = "target";
if(!isset($_COOKIE[$cookie_name])) {
 echo "Cookie named '" . $cookie_name . "' is not set!"; return;
} else {
 echo "Cookie '" . $cookie_name . "' is set!<br>";
 $gone = $_COOKIE[$cookie_name];
 unlink($gone);
}

?>
<script>

function OK_delete (filename) {
let result = confirm('Are you sure you want to delete ' +filename +' ?'); 
if (!result) {return;} 
if (result)	{ Cookies.set('target', filename, { expires: 1 }); 
test = Cookies.get('target'), alert (test); // WORKS OK!


// HERE I WANT TO ACCESS 'purge.php' AND RUN IT
// BUT I DON"T HAVE A CLUE HOW TO DO THAT!
// ANYBODY HAVE A SIMPLE, CORRECT SOLUTION ?

// FETCH
 fetch("purge.php", { method: "POST", body: data })
 .then(res => res.text())
 .then(txt => console.log(txt))
 .catch(err => console.error(err));
 return false;
}

}
}

filename = 'myfile.txt';

OK_delete (filename);

</script>

Hi @verlager, you have an odd closing bracket in your JS, and the data you’re trying to send as the POST body in the fetch() call is not defined. After fixing those issues it’s working fine for me.

That said, why don’t you actually send the filename in the POST body, rather than setting it as a cookie?

Well, it’s a computer which use variables. I have 1000’s of files, and only some need to be deleted

Okay but what I meant is why not just send the filename directly in the POST body, like e.g.:

function OK_delete(filename) {
  const data = new FormData()
  data.append('target', filename)

  fetch("purge.php", { method: 'post', body: data })
    .then(res => res.text())
    .then(console.log)
    .catch(console.error)
}

OK_delete('myfile.txt')

And then access it in your PHP script with $_POST['target']… no need to persist the filename as a cookie as far as I can tell. ^^

2 Likes

Your improvement is a very good and succinct solution. Of course, I will use it. Much appreciated!

1 Like