Search code examples
phpunlink

Delete file onclick with PHP


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?


Solution

  • 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__);
        }
    ?>