Jump to content
Larry Ullman's Book Forums

Ch. 11 Using Unlink() With A Reset Button Possible?


Recommended Posts

Hi group and Larry:

I was wondering if there was a way, after I have uploaded a certain file to my uploads directory, to be able to then delete it by using the 'reset' button on the form and connecting this somehow to an unlink() function? I have seen on StackOverflow where they use a link to Delete here: http://stackoverflow.com/questions/4844382/php-delete-file-script

 

but I can't get it to work either way, with a Delete link or what I think would be more sensible, just using Reset to empty the directory entirely.

 

Any thoughts?

 

Thanks!

 

Vick

Link to comment
Share on other sites

This can absolutely be done via GET. What you would do is using IDs as the get value. Save the filenames to an array on the form ID => "name". You then build links the same way, but with ?remove=$ID. You cast $_GET['id'] to an integer, find the filename in array by using the ID, build a full path where you add the filename, then use unlink() to delete the file.

 

An easy way to do this would be something like:

 


$handle = ""; // open file

$file_array = array(); // The file names

while ( ($file = readdir($handle)) !== false )
{
   if ($entry != "." && $entry != "..")
   {
   $file_array[] = $file;
   } // Read files to array
}

// Simple delete
if ( ! empty($_GET) )
{

   $upload_dir = "uploadsDirectoryHere/"; // Upload dir
   $file_id = (int) $_GET['delete']; // File_array ID

   // Make sure file is found
   if ( array_key_exists($file_id, $file_array) )
   {
	 $delete_file = $upload_dir . $file_array[$file_id];

	 // Make sure file exists
	 if ( file_exists($delete_file) )
	 {
		  unset(file_array[$file_id]); // Remove from file array
		  unlink($delete_file); // Actually delete file here
	 }
   }

// Print out file names and links for deleting them
foreach ( $file_array as $id => $filename )
{
   echo $filename . '<a href="page.php?delete='.$id.'">Delete file</a>;
}

 

Not tested, but that should be the basic idea. Sorry about errors/etc. Beginning to get tired here.

  • Upvote 3
Link to comment
Share on other sites

 Share

×
×
  • Create New...