4

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?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Code Lover
  • 8,099
  • 20
  • 84
  • 154
  • 7
    Did you run this code? Muhahaha. :) – Jason McCreary Nov 08 '12 at 18:25
  • you;; have to rethink your implementation slightly. One method would be to pass the filename to a PHP script that does the unlinking. This would be passed and called via a JS function that would make the request via AJAX. But you definitely _dont_ want to pass it _FILE_. You might want to look that constant up in the PHP manual ;) – thescientist Nov 08 '12 at 18:26
  • ewww. what if i mistakenly click the link? – itachi Nov 08 '12 at 18:27
  • 2
    @itachi Well right now, you won't even have to click the link. – woz Nov 08 '12 at 18:28
  • @JasonMcCreary I have run this code and it is deleting itself and that is the reason I am posting here. But I am feeling like StackOverflow is only for expert people and not for beginner or who just stepped in to any particular language. Even after collection this much of points and reputation I just surprised with your Muhahaha :) behavior. – Code Lover Nov 08 '12 at 18:31
  • If we beginner don't come with the code expert say did you try anything? come with code. If we come with code than we got this type of great response. So this is now giving such feeling that StackOverflow is just only for experts – Code Lover Nov 08 '12 at 18:32
  • @BenCarey, First appreciate with some detail reply. In addition. I have tried with simple href and result was the same as you said. Now my situation is not allowing to create separate page only for deleting the file. So is there any way to make in the same page? – Code Lover Nov 08 '12 at 18:35
  • @pixelngrain, it was not my intention to insult. I found the code to be funny. My *Muhahaha :)* was in good fun. **Josh**'s answer will help you get started in understanding the difference between PHP and JavaScript. – Jason McCreary Nov 08 '12 at 18:36
  • *continued* Understanding this is one of the first steps to web programming. Dont worry about people giving you a little lip on the stack :-). A lot of us (me included) like to think that we know it all, but sometimes we do have to remember that we had to learn this all as well :-). If you would like me to demonstrate a jQuery or PHP solution, let me know and I will post up an answer :-) – Ben Carey Nov 08 '12 at 18:38
  • @JasonMcCreary, It's okay. I don't mind but sometime get frustrate when I am trying to learn and solve some issue and came here with lot of faith. So pls take it easy. I also apologies if I did anything wrong – Code Lover Nov 08 '12 at 18:42
  • @BenCarey I completely agree with your comment. I will do as you said. Thanks :) – Code Lover Nov 08 '12 at 18:43
  • @pixelngrain take it with a pinch of salt. no need to get frustrated. After all, the same people will help you. – itachi Nov 08 '12 at 18:44
  • @pixelngrain Have upvoted to give you as much support as I can :-) – Ben Carey Nov 08 '12 at 18:51
  • @BenCarey, Thank you so much. I really appreciate your and everyone's help. – Code Lover Nov 08 '12 at 18:55
  • I found solution with the selected answer. I appreciate everyone to help me. I also apologies to evreyone and specially JasonMcCreary. Thanks a lot :) – Code Lover Nov 08 '12 at 19:07

6 Answers6

9

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__);
    }
?>
Jocelyn
  • 11,209
  • 10
  • 43
  • 60
  • `when they click on delete link only`.... that's the criteria. – itachi Nov 08 '12 at 18:29
  • 1
    @itachi It will delete the file ONLY if you click the link! – Jocelyn Nov 08 '12 at 18:30
  • @itachi You're not reading this (correct) answer correctly. – Josh Nov 08 '12 at 18:30
  • can't i just append it(the variable) in url i.e. `$_GET['delete']`. i.e. `?delete` what will happen? – itachi Nov 08 '12 at 18:33
  • @itachi I am not sure it will work without the `=` sign after the variable. $_GET would not contain the variable, and the file would never be deleted. – Jocelyn Nov 08 '12 at 18:36
  • @itachi Test what? My current code is working, why do you ask me to test YOUR code? – Jocelyn Nov 08 '12 at 18:40
  • that **test** was for your statement `I am not sure it will work without the = sign after the variable. $_GET would not contain the variable, and the file would never be deleted`. – itachi Nov 08 '12 at 18:42
  • @itachi I still fail to understand your point. You still have not given any proof that my code was not working, or that my answer was not solving the problem explained in the question. – Jocelyn Nov 08 '12 at 18:46
  • @Jocelyn I didn't say your code is **not** working. I only said it does not fit the crtieria given by OP. – itachi Nov 08 '12 at 18:47
  • @itachi And why do you think so? – Jocelyn Nov 08 '12 at 18:48
  • @Jocelyn the only criteria was `when they click on delete link only`. In your code snippet, i just need to append `?delete` in the url and on execution, it will delete the file _though i did not click the link._ – itachi Nov 08 '12 at 18:51
  • Let me try to tell that this code works perfectly as I want. When user click on the link that time only it is deleting file. But now I am not sure either it is secure way or not as with this php file I am running sql query to install database. – Code Lover Nov 08 '12 at 18:51
  • @pixelngrain in that case, you shouldn't have put that criteria. **note:** do not initiate a delete process by clicking links. Use POST method with necessary credentials. Why? Think what will happen if crawlers crawl into your site? – itachi Nov 08 '12 at 18:54
  • @pixelngrain Many install scripts use this kind of code to automatically delete themselves when installation is complete. It prevents anyone else to run the script again, and cause trouble. – Jocelyn Nov 08 '12 at 18:55
  • @itachi Ah! I am not sure either it is different than my criteria. As I want file to be deleted once user click on Delete now link and this code is doing the same. If it is something different please learn me. I am not sure what is the difference – Code Lover Nov 08 '12 at 18:56
  • @Jocelyn Yes you are right and that is simple to do. but in that case where user is not from the web development background and just run website like Wordpress blog they might get confused once they do some update or etc. I am not sure either it is correct way to do or not. – Code Lover Nov 08 '12 at 18:58
  • @pixelngrain There is no security risk since the file will be on your server just long enough for you to install your database. Crawlers won't be able to visit your install script, since it is not linked from any of your public pages, and because it will be on the server only a very short time anyway. – Jocelyn Nov 08 '12 at 19:00
  • @pixelngrain difference is above. if it is in public pages, you will be creating lots of vulnerabilities. – itachi Nov 08 '12 at 19:02
  • @itachi, no this file is in plugin directory and only admin will be able to access this file. – Code Lover Nov 08 '12 at 19:04
  • @Jocelyn Thanks to clarify. In fact your code works for me for delete file on click. – Code Lover Nov 08 '12 at 19:04
5

You need to load this action via Javascript. If you're using jQuery you can't try something like that

Your Javascript

<script type="text/javascript">

$('.delete').live('click',function(){ 
  deleteFile( $(this).attr('id') );
});

function deleteFile(id){
    $.ajax({
        url: 'deletefile.php?fileid='+id,
        success: function() {
            alert('File deleted.');
        }
    });
}
</script>

Your deletefile.php look like that.

<?php
    $fileid = $_GET['fileid'];
    //HERE IS THE LOGIC TO FIND THE PATH OF YOUR FILE
    unlink($file); //You can add more validations or full paths
?>

And your link must have the following structure

printf("<a id='%s' class='delete'>Delete</a>",$youridfile);
eusoj
  • 374
  • 3
  • 12
  • You have some errors in your javascript, and there is no need to use `fid`, just use `id`! Otherwise, this is the right answer – Ben Carey Nov 08 '12 at 18:53
  • Thanks for your comment, I change the javascript in the live("click") . – eusoj Nov 08 '12 at 19:53
  • 3
    I know this is more then 3 years old, but the live command is deprecated. Better use .on() – Adam Apr 15 '16 at 15:37
3

You're not understanding the separation between client and server code. Javascript can't just call PHP like that. The PHP will run immediately as the page is being built on the server, not stored for later use.

You'll need to make an AJAX request to delete onClick, or, make a new page like /delete/$ID/ that will delete for you, or, as Jocelyn just beat me to, make the same page able to delete if a GET / POST parameter is set.

Although, it's worth noting that __FILE__ is the file that that code is in, so, it's going to kill itself.

Josh
  • 12,448
  • 10
  • 74
  • 118
  • 1
    Yes that is the problem. From top to bottom every one is trying to make me understand what you are saying. :) – Code Lover Nov 08 '12 at 18:47
3

Is this PHP? You can't run a PHP function from inside javascript. Instead you need to load/redirect/post to a php file.

echo '<h3><a href="deleteScript.php" >Delete Now!</a></h3>';

edit:

function table_exists($tablename, $database = false) {

if(!$database) {
    $res = mysql_query("SELECT DATABASE()");
    $database = mysql_result($res, 0);
}

$res = mysql_query("
    SELECT COUNT(*) AS count 
    FROM information_schema.tables 
    WHERE table_schema = '$database' 
    AND table_name = '$tablename'
");

return mysql_result($res, 0) == 1;

}

if(table_exists('my_table_name')) {
    // do something
}
else {
// do something else
}
alloyking
  • 341
  • 3
  • 10
  • Yes this is php file and I wan to delete same (self ) file which is running sql query – Code Lover Nov 08 '12 at 18:47
  • So to be clear. You have a php file that contains code for running an sql query... and you would like that php file to delete itself? This sounds very unconventional. Are you sure you want to do this? – alloyking Nov 08 '12 at 18:51
  • Query is to install database nothing more than that. So it is checking if table exists than return false else insert table that's all – Code Lover Nov 08 '12 at 19:00
2

You cannot run a PHP function as an onclick, javascript event. You need to run that function in a fashion like so:

<?php
    if (isset($_GET['delete'])) {
        unlink($_GET['delete']);
    }
?>
<html>
   <a href="?delete=/PATH/TO/FILE">Delete Now</a>
</html>
Darius
  • 612
  • 2
  • 11
  • 23
1

You need a post request that php processes...or an ajax/javascript function that runs a php script...

Here is an example with ajax http://www.website-php.com/de/tutorials/treeview/treeview-04.html

Jurudocs
  • 8,595
  • 19
  • 64
  • 88