Page 1 of 1

[Solved] Deleting MP3'S

Posted: Wed Apr 02, 2008 7:17 am
by Addos
Hi, I hope it's okay to ask the following. I'm looking for a simply script that will show a list of mps.3 in a folder so that I can select to delete a specific mp3. Can anyon point me to one? I have been reading up but a lot are very complex for my level of PHP.
Thanks

Re: Deleting MP3'S

Posted: Wed Apr 02, 2008 7:30 am
by Chris Corbyn
So maybe we need to start at the beginning ;) Can you write code to list the MP3's even if it doesn't "do" anything?

Re: Deleting MP3'S

Posted: Wed Apr 02, 2008 7:41 am
by Addos
Yep! And this works okay for me. Thanks

Code: Select all

<?
    // Define the full path to the folder whose contents you want to list
    $path = "../../tutti_audio/";
    // Open the directory
    $dir_handle = @opendir($path) or die("Error opening $path");
    // Loop through the files
    while ($file = readdir($dir_handle)) {
      if($file == "." || $file == ".." || $file == "index.php" ) { continue; }
    
      echo "<a href=\"$file\">$file</a><br />";
    }
    // Close
    closedir($dir_handle);
?>

Re: Deleting MP3'S

Posted: Wed Apr 02, 2008 9:51 am
by John Cartwright

Code: Select all

echo '<a href="?delete='. urlencode($file) .'">Delete '.$file .'</a><br />";
 
Then someone on the page to detect whether a delete has been requested,

Code: Select all

 
 
$dir = $_SERVER['DOCUMENT_ROOT'] . '/files/mp3/';
$file = isset($_GET['delete']) ? basename(urldecode($_GET['delete'])) : false;
 
if ($file && file_exists($dir . $file)) {
   unlink($dir.$file);
}
A couple things to consider in the example I've provided,

#1 urlencode() the links filename since it may contain some invalid url characters (and urldecode when using it)
#2 check that the requested file exists in the correct folder using file_exists()
#3 apply basename() on the requested file to avoid users trying to pass invalid filepaths

I'm sure theres a couple things I forgot to consider

Re: Deleting MP3'S

Posted: Wed Apr 02, 2008 11:52 am
by Addos
Thanks for all the help. Another little bit learned thank you!
B