Jump to content

Delete a file when click button


ashrobbins87

Recommended Posts

I am trying to display the contents of a folder and place a delete button next to each file. Then I want to be able to press the button and delete the file, but instead, when I refresh the page to view my changes, all of the files are deleted even though I dont touch the buttons. The code is below...

<?php 
if ($handle = opendir("../Images/")) {  
    while (false !== ($file = readdir($handle))) {   
        if ($file != "." && $file != "..") {   
		$myfile = "../Images/".$file;
            echo "<a href=\"../Images/".$file."\">".$file."</a>";   
		echo "<img src=\"../Images/".$file."\" width=\"70\" height=\"50\">";
		echo"<input type=\"button\" value=\"Delete\" onClick=\""; unlink($myfile); "\"><br />";

        }   
    }  
    closedir($handle);   
}  
?>

Link to comment
Share on other sites

This line is the error:

echo"<input type=\"button\" value=\"Delete\" onClick=\""; unlink($myfile); "\"><br />";

 

It's not printing the html after the unlink function..

echo '<input type="button" value="Delete" onClick="'.unlink($myfile).'"><br />';

Link to comment
Share on other sites

echo '<input type="button" value="Delete" onClick="'.unlink($myfile).'"><br />';

 

This is not the issue at all. You cannot call a php function within a javascript event handler.

All you are doing is looping through the files and the function unlink() will remove each file.

 

You should replace with a hyperlink that calls an action when clicked. Example code i.e.

 

<?php
   // user has clicked a delete hyperlink
   if($_GET['action'] && $_GET['action'] == 'delete') {
       unlink($_GET['filename']);
       header("Location:files.php");
       exit();
   }
?>
<a href="files.php?action=delete&filename=xyz.jpg">delete file</a>

Link to comment
Share on other sites

first off, you have not trigger, ie something that must be true in order to have it run the delete. You could use a $_GET variable to trigger the deletion...

having the function in the link does not work my friend because html/javascript cannot simply execute php

if you had

if($_GET['delete'] > ''){ unlink("dir/".$_GET['delete']; }

then have your links look like this

<?php
echo '<input type="button" value="Delete" onClick="if(confirm('Are you sure?')){ window.location=\'CHANGE_TO_FILENAME.php?delete='.$myfile.'\'; }"><br />';
?>

that is untested code, so you may have a problem, I don't think you would though.

 

Link to comment
Share on other sites

Ok I'm using Brian's code and have muddled it into something like this...

<?php 
if ($handle = opendir("../Images/")) {  
    while (false !== ($file = readdir($handle))) 
{   
        if ($file != "." && $file != "..") 
	{   
		$myfile = "../Images/".$file; 
		echo "<td><a href=\"../Images/".$file."\"><img src=\"../Images/".$file."\" width=\"70\" height=\"50\"></a></td>";

		if($_GET['delete'] > '')
		{ 
			unlink("dir/".$_GET['delete']); 
		}
		echo "<input type=\"button\" value=\"Delete\" onClick="
		if(confirm('Are you sure?'))
		{ 
			window.location="".$myfile."?delete=".$myfile.""; 
		}
		"><br />";		   
        }   
    }  
    closedir($handle);   
}  
?>

Where am I going wrong now?

Link to comment
Share on other sites

if(confirm('are you sure')) is js, not php...

<?php 
if ($handle = opendir("../Images/")) {  
    while (false !== ($file = readdir($handle))) 
   {   
        if ($file != "." && $file != "..") 
      {   
         $myfile = "../Images/".$file; 
         echo "<td><a href=\"../Images/".$file."\"><img src=\"../Images/".$file."\" width=\"70\" height=\"50\"></a></td>";
         
         if($_GET['delete'] > '')
         { 
            unlink("dir/".$_GET['delete']); 
         }
         echo "<input type=\"button\" value=\"Delete\" onClick=\"
         if(confirm('Are you sure?'))
         { 
            window.location="".$myfile."?delete=".$myfile.""; 
         }
         \"><br />";         
        }   
    }  
    closedir($handle);   
}  
?>

All I did was add a slash to the quotes around the if(confirm()) chunk... try that

Link to comment
Share on other sites

put this in your loop that displays each of the files.  for each file it will display a Delete button. when pressed it will reload the page and delete that file that was selected

<form name="deleteSomething" action="<?php echo $_SERVER['PHP_SELF'].'?delete=true';?> >
<input type="button" name="fileToDelete" value="<?php echo $file; ?>">
<input type="submit" value="Delete">

 

and this goes near the top of your page

<?php
if(isset($_GET['delete']) && $_GET['delete']=='true') {
   unlink("/dir/".$_POST['fileToDelete']);
}
?>

Link to comment
Share on other sites

Your code to delete the file should not be contained with the loop.

It should be at the very top of the page - before you start printing anything to the screen.

Once you have deleted the file reload the page. Check my post above.

 

It would also be a lot easier to use a standard hyperlink to action the delete rather than a form which is not needed as the other posts suggest however it is upto you.

Link to comment
Share on other sites

Right I think we're nearly there!! It now deletes a file, but whichever button I press it always deletes the last file in the folder, IOW the one the loop gets to last.

<?php
if(isset($_GET['delete']) && $_GET['delete']=='true') {
   unlink("../Images/".$_POST['fileToDelete']);
}
?>
<?php 
if ($handle = opendir("../Images/")) {  
    while (false !== ($file = readdir($handle))) 
{   
        if ($file != "." && $file != "..") 
	{   
		$myfile = "../Images/".$file; 
		echo "<td><a href=\"../Images/".$file."\"><img src=\"../Images/".$file."\" width=\"70\" height=\"50\"></a></td>";

		echo "<form method=\"post\" name=\"deleteSomething\" action="?><?php echo $_SERVER['PHP_SELF'].'?delete=true';?><?php echo" >
		<input type=\"text\" name=\"fileToDelete\" value=".$file." >
		<input type=\"submit\" value=\"Delete\">";
        }   
    }  
    closedir($handle);   
}  
?>

Link to comment
Share on other sites

yeah, could do this without the js onclick, but it wouldn't be as cool :-p

sorry, I see the problem now

<?php 
if ($handle = opendir("../Images/")) {  
    while (false !== ($file = readdir($handle))) 
   {   
        if ($file != "." && $file != "..") 
      {   
         $myfile = "../Images/".$file; 
         echo "<td><a href=\"../Images/".$file."\"><img src=\"../Images/".$file."\" width=\"70\" height=\"50\"></a></td>";
         
         if($_GET['delete'] > '')
         { 
            unlink("dir/".$_GET['delete']); 
         }
         echo "<input type=\"button\" value=\"Delete\" onClick=\"
         if(confirm('Are you sure?'))
         { 
            window.location='this_page.php?delete=$myfile'; 
         }
         \"><br />";         
        }   
    }  
    closedir($handle);   
}  
?>

in there where it says "this_page.php", that should be the name of the file you are working on, as in the php file the code is in...

basicaly what we are doing is saying, if they confirm they want to delete it, send them to this same page with an additional parameter attached telling it to delete that file. When they get to that page and $_GET['delete']

is specified, then it will delete it...

Link to comment
Share on other sites

That is odd.  Right click your page and view source.  see what the values are for the <input type="button">  each one should have a unique filename which is the same as as the file that was just displayed

 

Right I think we're nearly there!! It now deletes a file, but whichever button I press it always deletes the last file in the folder, IOW the one the loop gets to last.

<?php
if(isset($_GET['delete']) && $_GET['delete']=='true') {
   unlink("../Images/".$_POST['fileToDelete']);
}
?>
<?php 
if ($handle = opendir("../Images/")) {  
    while (false !== ($file = readdir($handle))) 
{   
        if ($file != "." && $file != "..") 
	{   
		$myfile = "../Images/".$file; 
		echo "<td><a href=\"../Images/".$file."\"><img src=\"../Images/".$file."\" width=\"70\" height=\"50\"></a></td>";

		echo "<form method=\"post\" name=\"deleteSomething\" action="?><?php echo $_SERVER['PHP_SELF'].'?delete=true';?><?php echo" >
		<input type=\"text\" name=\"fileToDelete\" value=".$file." >
		<input type=\"submit\" value=\"Delete\">";
        }   
    }  
    closedir($handle);   
}  
?>

Link to comment
Share on other sites

I think I've solved it. I was being a bit of a spud and forgot to close the form. I put in a </form> tage and it now seems to be working. Thank you so much for all your help guys, there should be a thanks or Rep button on this forum and you could all have some!!  ;D

Link to comment
Share on other sites

One little niggly thing though, every time the page is refreshed I get the error: Warning: unlink(../Images/Image018.jpg) [function.unlink]: No such file or directory in C:\wamp\www\Site_Pages\cms\Untitled-1.php on line 15

 

The filename is the file that was first in the loop the last time the page was loaded, even though this file may have been deleted.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.