Delete file onclick with PHP

Code Lover picture Code Lover · Nov 8, 2012 · Viewed 24.4k times · Source

I want to delete a file when a user clicks on a delete link. But when I go to my page, the file gets deleted and I don't know why:

echo '<h3><a onclick="'.unlink(__FILE__).'">Delete Now!</a></h3>';

What am I doing wrong?

Answer

Jocelyn picture Jocelyn · Nov 8, 2012

This code will delete the current file when the user clicks the link:

<h3><a href="?delete=1">Delete Now!</a></h3>

<?php
    if(isset($_GET['delete']))
    {
        unlink(__FILE__);
    }
?>

If you prefer to use POST instead of GET method, use this code:

<form method="post">
   <input name="delete" type="submit" value="Delete Now!">
</form>    

<?php
    if(isset($_POST['delete']))
    {
        unlink(__FILE__);
    }
?>