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 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)
}
}
}
?>
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 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)
}
}
}
?>
Share
Improve this question
edited Nov 15, 2017 at 23:04
halfer
20.4k19 gold badges109 silver badges202 bronze badges
asked Nov 27, 2016 at 15:35
jackDjackD
8012 gold badges8 silver badges27 bronze badges
7
- 2 You cannot include php functions in javascript. You must call an endpoint, either through a submit or an ajax request, to a backend endpoint that will perform the action. – Taplar Commented Nov 27, 2016 at 15:39
- You mean to say I use submit rather than onclick events basically? – jackD Commented Nov 27, 2016 at 15:41
- 1 That or create an ajax request on click that sends the needed data to the endpoint so it knows what/how to rename/delete. – Taplar Commented Nov 27, 2016 at 15:42
- ok but how do i pass a new name for the filename? – jackD Commented Nov 27, 2016 at 15:45
- You'll have to get that from the user with some form of an input displayed to them when they need to provide that information. – Taplar Commented Nov 27, 2016 at 15:47
3 Answers
Reset to default 5You 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 remend storing the paths and filenames in a database.
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 bination 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 mands 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>
I am not sure how to include this functions dynamically
Based on your question and your code, it looks like you are capable of deleting or renaming the files but are looking for work flow advice.
I give the following suggestions. If you want code, I am happy to supply my solutions, but the scope of an interface is rather large and needs some clarification first. For example,
- Do you have directories that the user navigates?
- Do you want the user to have checkboxes to check individual files (remended) OR do you want them to be able to enter a file pattern as you example shows (dangerous!)?
My remendations:
Use a table to display the files. Above the table include buttons to "Delete Selected", "Cancel"
Include the following columns in the table:
- Checkbox (for selecting multiple files if this is desired)
- Filename (just text and can be the label portion of the checkbox)
- Editable input with filename allowing user to rename
- Input Button = "Rename" (to rename individual file)
- Input Button = "Delete" (to delete individual file)
- Thumbnail image which they can click on to see a full sized image.
The table is within a form so that each <input>
with a name
property will end up in $_POST
For example, the inputs for renaming a file and submitting it looks like this:
<td><input type=text name=filer-<?php echo encodestr($filefull) ?> value='<?php echo $name ?>'></td>
<td><input type="submit" name="fprename-<?php echo encodestr($filefull) ?>" value="Rename" onClick='return confirm("Do you want to rename this file?");'></td>
where $filefull
is the full existing path to the file and $name
is without the path. When clicking on the Rename button, $_POST
will contain elements with each filename prefixed with filer-
so I can easily recognize them. I know which one to rename or delete based on which submit button was pressed which I can tell from the var which is prefixed with fprename-
.
So if I get back from $_POST
a var named $_POST['fprename-/path/myfile.jpg']
, I look for the input var $_POST['filer-/path/myfile.jpg']
and rename the file to the value contained in it (of course checking first that a file with that name doesn't already exist).
Work Flow:
For deleting multiple files
- User selects items using checkboxes for deleting and submits form by clicking on the
Delete Selected
submit button. - The form
onSubmit
gives a javascriptalert()
to allow cancelling the delete request. - After user confirms, you want to do a Post/Redirect/Get (to prevent multiple form submission). This involves submitting the form to another php (e.g. processFiles.php) which processes the unlink() code you have then redirects back to the userInterface.php.
For deleting or renaming individual files
- User clicks on a submit button in the table next to the individual files.
- The button
onclick
gives a javascriptalert()
to allow cancelling the delete or rename request. - After user confirms, the form will submit. Again, you want to do a Post/Redirect/Get where another php (e.g. processFiles.php) processes the unlink() or rename code then redirects back to the userInterface.php.
In the following example, I don't allow deleting multiple files, only Selecting multiple files - hence the "Select" button at the top instead of a "Delete Selected".