Search code examples
phphtmlunlink

Stop $_GET being processed after reload


I'm creating a link which appends a $_GET variable to the end of it for use of deleting files / other PHP tasks.

<a href="test.php?delete_file=<?php echo $filename; ?>">Delete file</a>

Part of my PHP code looks for the variable and if it exists, it runs the unset function to remove the file, but when I reload the webpage, it obviously tries to remove the file again. Is there any way to remove the $_GET after it has been run once to stop the processing after a refresh?

<?php
if (isset($_GET['delete_file'])) {
    if (file_exists($full_path.$_GET['delete_file'])) {
        unlink($_GET['delete_file']);
    } else {
        echo "File ".$full_path.$_GET['delete_file']." doesn't exist";
    }
}
?>

<a href="test.php?delete_file=<?php echo $filename; ?>">Delete file</a>

Solution

  • You can use ajax to remove files so it won't refresh.

    <a href="javascript:deletefile('<?php echo $filename; ?>')">Delete file</a>
     <script>
            function deletefile(filename){
                    var data = {delete_file:filename };
                    $.ajax({ 
                            url: 'delete.php',
                            type: 'post',
                            data: data,
                            success: function(response) {
                                // .. do something with response ..
                                // you can use window.location to refresh page   
                               // or if you have js method to refresh page. you can call it here
                            }
                    }); 
            }
            </script>
    

    In php file you can retrive with post

    <?php
    if (isset($_POST['delete_file'])) {
        if (file_exists($full_path.$_POST['delete_file'])) {
            unlink($_POST['delete_file']);
        } else {
            echo "File ".$full_path.$_POST['delete_file']." doesn't exist";
        }
    }
    ?>
    

    But as the commenters say this is open to potential security issues. You need to take care of security if you use this approach in production.