Hi everyone,

So I could use some newbie advice on using the PHP Unlink() function.

The background info:

I have two different php scripts.

  1. Script "1" allows me to upload files (using file upload) to a given directory that I specify in the configuration.

  2. Script "2" allows me to view (view only) all files that have been uploaded via script 1.

I am currently in the process of modifying Script "2" so that I can delete any file that the user may designate. I am not setting this up to do multiple delte. Just a single file at a time.

I have added the word "delete" to each file detail line. My goal is to set this up so tha when the user "clicks" on the word "delete" on a given file line that file is delted.

The problem:

  1. I know that I need to use the PHP Unlink() function to accomplish this task. I know that that the model for this function is basically:
unlink ($fileToDelete) 
  1. I don't know how to associate this function to the word "delete" and make the function unique to that specified file.

Here is a snippet of my code to help explain what I have done:

Created a delete file function:

function deletFile (unlink($file));

Added a link called "DELETE" to the File "2" (phpDirList) Output

// Try to get a directory handle and continue if it returns TRUE.
if ($dir = @opendir("./")) {
    $output = ""; // Empty the HTML-output variable.
    while (($file = readdir($dir)) !== FALSE) { // Read the directory step by step and process the data.
        if (test_ext ($file)) { // Check if the entry should be displayed or not and continue if TRUE.
            $stats = @stat ( "./".$file); // Get the file stats.
            // And append a table row to the output variable.
            $output .= '
        <tr class="line">
            <td class="col2">DELETE</td>
            <td class="col1">
                <a title="'.$file.'" href="'.$file.'">'.$url.''.$file.'</a>
            </td>
            <td class="col2">'.number_format ($stats[7], 0, ",", ".").'</td>
            <td class="col3">'.str_replace (" ", " · ", date ("m.d.Y H:i", $stats[9])).'</td>
        </tr>'."\n";
        }
    } 
    closedir($dir); // Close the directory handle.
} else {
    $output = "<tr><td colspan=\"3\"><h1>Cannot open Directory!</h1></td></tr>"; // Display error message if there was no directory handle returned in the leading condition.
} 

So what's next?

I almost wish I could do something like

 <a onclick="<?unlink($file)?>">DELETE</a>

Am I going down the right path?

Any help, direction, or comments would be appreciated!


Thanks,
Rick

    unfortunately, you cant use a javascript onclick to execute php code. you will have to reload the php script, perhaps with the file name in the query string, along with an instruction to delete it so your script knows what exactly to do. it may look something like
    script.php?file=blah.txt&action=delete
    then when the script is loaded it checks $GET['action'] to see if its delete. if so it will call unlink on $GET['file']

      drew010 wrote:

      script.php?file=blah.txt&action=delete
      then when the script is loaded it checks $GET['action'] to see if its delete. if so it will call unlink on $GET['file']

      Drew....

      Thanks for providing some feedback... can you help me understand what you said a little better?

      Firstly... I am not using GET or POST to list the file to start with... I am using basic PHP File handling will you suggestion above work?

      Next.... Can I refine the function that I listed in my origianl post?

      function deletFile (unlink($file)); 

      Or better yet is this function formatted correctly?

      Next... how do I call a function to act on a action by the user?

      Sorry for all the dumb questions... I have been slowly teaching myself PHP and I still have a lot to learn :bemused:

      Any help you or anyone else could provide would be greatly appreciated!

        You gotta love "Advanced Search"...

        I did an advanced search on this board and came across this post:

        http://phpbuilder.com/board/showthread.php?t=10306769&highlight=unlink

        In this post a person asked a very similar question to mine and someone was kind enough to provide some code to get the person going in the right direction....

        The poster then was kind enough to reply with his finished version of code:

        $directory = opendir("../images/"); 
                              while($filename = readdir($directory)) { 
                                $ext = substr($filename, 0,2); 
                                if ($ext == $this->id . "_") { 
                                    unlink("../images/" . $filename);  
        } }

        This is almost exactly what I would like to do....

        So this leads me to my next question:

        How do I call this snippet of script to execute at the users request (clicking a link)??

          you can have that run by either making its its own php file, or using parameters from the query string to specify what they want to do...

          <?php
          
          if (isset($_GET['action']) && isset($_GET['file'])) {
            if ($_GET['action'] == "delete") {
              unlink($_GET['file']);
            }
          } else {
            //other default behaviour here.
          }
          
          ?>
          

          call that like script.php?action=delete&file=whatever.txt

          just make sure these urls are protected and cant be accessed otherwise anyone can delete your stuff.

            Drew...

            I took your advice and created a second php file called "fileDelete.php".

            Then on my original dirList.php file I added a check box to each line and gave it he name "deleteFile[]" and the value of "$filename".

            This means that I am building an array of items that have been selected to be deleted and then passing them using _GET to fileDelete.php.

            In fileDelete.php I have the following simple code:

            <?php 
            foreach($deleteFile as $key=>$filename) {
            	unlink($filename);
            	}
            foreach($deleteFile as $key=>$filename){
            	echo "File [$key]=$filename has been deleted!<br>\n";
            	}
            ?>

            The first "foreach" statement deletes the files identified in the array that was passed.

            The second "foreach" statement echos the number of itmes in the array and the file names.

            Thank you very much for your help! I really apprecaite it and I hope this can help someone else in the future!

              hey, no problem, im glad you got it all worked out. in that top snippet of code you can actually shorten it by just putting both of those lines in the same foreach. i.e.

              <?php 
              foreach($deleteFile as $key=>$filename) {
                  unlink($filename);
                  echo "File [$key]=$filename has been deleted!<br>\n";
              }
              ?> 
              

              doesnt make much difference but is a bit simpler to understand for new people.

                Write a Reply...