Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit a filename and delete the image from a folder?

Tags:

javascript

php

I am trying to add edit option for image filename and also delete option for the images. All the images are in a folder and I haven't used database at all. I am able to display the image filenames along with button for edit and delete adjacent to every image name.

But I am not sure how to go forward. I know PHP has a unlink() and rename() functions. but I am not sure how to include this functions dynamically.

<?php
echo "<div class='container'>";
if(isset($_POST["submit"])) {
    $files = glob("images/Kwebsite/". $_POST['path']."/*.*");
}

echo "<div class='col l5'>";
echo "<h3>Image Filename&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Actions</h3>";
echo "</div>";

for ($i=0; $i<count($files); $i++){
    $num = $files[$i];
    $filenamewithextension = basename($num);
    $fileextenstion = pathinfo($filenamewithextension, PATHINFO_EXTENSION);
    $filename = basename($num,$fileextenstion);

    echo '<div class="imagename">';
    echo $filename; 
    echo '<button type="submit" class="btn-flat" value="Delete"  onClick="Delete()">Delete</button>';

    if(isset($_POST["submit"])) {
        $imgfile = glob("images/Kanishk website/". $_POST['path']."/*.*");

        foreach $imgfile as $img {
            unlink($img)
        }
    } 
}
?>
like image 216
jackD Avatar asked Nov 27 '16 15:11

jackD


People also ask

How do you delete the image file in document?

Navigate to the document file or image you wish to delete. Right-click on the item and a menu will appear. Delete option. A dialog box will appear asking if you're sure you want to delete the file.

How do I remove something from a folder?

Delete keyLocate the item you want to delete, highlight it by left-clicking the file or folder with your mouse once, and press Delete . You can browse the location of the file or folder using My Computer or Windows Explorer.

How do I delete all files from a certain name?

To delete matching files: enter *_bad. jpg in the search box, select the results and press Delete or Del.


2 Answers

You have to pass the file path to unlink(). If you want to remove multiple files, you will have to call unlink multiple times. If you push the file paths to an array you can loop over the paths.

$paths['/files/file1.jpg','/files/file2.jpg']
foreach $paths as $file {
   unlink($file)
}

If you want to rename the file, you also have to provide the full path, otherwise you will create a new file somewhere else:

rename ("/files/file1.jpg", "/files/file_1.jpg");

This info has to be provided by a user, at least in most cases. I would recommend storing the paths and filenames in a database.

like image 139
Jorn Avatar answered Oct 02 '22 21:10

Jorn


First of all, this a dangerous thing you are doing there and you should avoid it. Imagine what could happen if someone gives some level up dots combination like this ../../; the script would have listed all the files 2 levels up. In order to prevent such behavior, we need to check the path input string for slashes and backslashes and do not execute the glob function if some slashes found. Here is the regular expression to validate the path query:

// Check for backslash, level up dir .. and wildcards 
$isValidPath = !preg_match('#([\\\.\?\*])#', $path);

I made a very simple example based on your code. All the commands are passed to PHP by posting form data to the server (not AJAX). When the user clicks on delete button, a message confirmation appears and if the user clicks OK, then the form posts the delete button data, which are its name="delete" and the value="path/filename.ext". We'll have a $_POST['delete'] == "path/filename.ext" value in PHP. If we detect the delete in our POST data, then we call the unlink and we delete the file. For the renaming functionality, we use the same method but with the javascript prompt this time, which prompts and asks the user to type a new filename. If the new filename is different from the original, then it updates a hidden field with the new filename and posts the form fields to our PHP server script; the POST data will have these values for the rename function $_POST['rename'] == "path/oldfilename.ext" and $_POST['renameto'] == "newfilename.ext". Then we just call the rename function at the beginning of our script.

Tip: Use PHP print_r function to print the $_POST array inside an HTML <pre></pre> to debug post data on each page refresh:

<pre><?php print_r($_POST) ?></pre>

The final working script

<pre><?php print_r($_POST) ?></pre>

<?php 

$hasPath = isset($_POST['path']);
$basePath = __DIR__."/images/Kwebsite/";
$path = '';
$files = array();

if(isset($_POST['rename']) && isset($_POST['renameto'])) {
    $fileToRename = $basePath.$_POST['rename'];
    $renameTo = dirname($fileToRename).'/'. $_POST['renameto'];
    rename($fileToRename, $renameTo);
}

if(isset($_POST['delete'])) {
    $fileToDelete = $basePath.$_POST['delete'];
    unlink($fileToDelete);
}

if($hasPath) {

    // Check for backslash, level up dir .. and wildcards 
    $path = $_POST['path'];
    $isValidPath = !preg_match('#([\\\.\?\*])#', $path);

    if($isValidPath) {
        $searchPath = $basePath.$path.'/*.*';
        $files = glob($searchPath);
    }
}

?>

<form method="post">
<label>Search directory: </label>
<input type="text" name="path" value="<?php echo $path ?>"/>
<button type="submit">Search</button>

<hr>

<table border="1">
 <thead>
  <tr>
   <th>Image Filename</th><th>Actions</th>
  </tr>
 </thead>
 <tbody>
  <?php if($hasPath && $isValidPath && count($files) > 0): ?>
  <?php foreach($files as $file): 
    $filenameWithExtension = basename($file);
    $fileExtenstion = pathinfo($filenameWithExtension, PATHINFO_EXTENSION);
    $filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
  ?>
  <tr>
   <td><?php echo $filename ?></td>
   <td>
    <button type="submit" name="delete" value="<?php echo "{$path}/{$filenameWithExtension}" ?>" onClick="Delete(event)">Delete</button>
    <button type="submit" name="rename" value="<?php echo "{$path}/{$filenameWithExtension}" ?>" onClick="Rename(event)">Rename</button>
   </td>
  </tr>
  <?php endforeach; ?>
  <?php endif; ?>
 </tbody>
</table>

<input type="hidden" id="renameto" name="renameto"/>

</form>

<script type="text/javascript">

function Delete(e) {
    var event = e || window.event,
        filename = event.target.value.substr(event.target.value.lastIndexOf('/') + 1);

    if(!confirm("Are you sure you want to delete this file '"+filename+"'?"))
        event.preventDefault();
}

function Rename(e) {
    var event = e || window.event,
        oldFilename = event.target.value.substr(event.target.value.lastIndexOf('/') + 1),
        newFilename = prompt("Enter a new filename", oldFilename);

    if(newFilename != null) {
        if(newFilename == oldFilename) {
            alert("You must give a different filename");
            event.preventDefault();
        } else {
            document.getElementById('renameto').value = newFilename;
        }
    } else {
        event.preventDefault();
    }
}

</script>
like image 23
Christos Lytras Avatar answered Oct 02 '22 23:10

Christos Lytras