PHP, delete path from TXT file
I have, problem.. I display images from dir in ARRAY with button 'delete' - action delete.php..
If I click 'delete' file delete.php should delete image from dir and path from TXT file.. Below PHP code delete only file from dir, I don't know how I can delete PATH from TXT files - I need this script..
TXT file looking that:
../../gallery/glowna//thumb_1300625269.jpg|
../../gallery/glowna//thumb_1300625300.jpg|
../../gallery/glowna/开发者_开发知识库thumb_1300626725.jpg
And delete.php
<?php
$plik=$_POST['usun'];
$nowa = substr($plik, 6, 20);
unlink('../../gallery/glowna/'.$_POST['usun']);
unlink('../../gallery/glowna/'.$nowa);
header("location:usun.php");
?>
I trying use below code, but something is wrong, because TXT file are cleaning ALL:
$txt = "../../dynamic_ajax.txt";
$img = "../../gallery/glowna/".$_POST['usun'];
$file = file_get_contents($txt, true);
$file2 = explode('|', $file);
$search=array_search($img, $file2);
unset($search);
$separator = implode("|", $file2);
file_put_contents($txt, $separator);
Ok think I understand what you mean. This is something I jotted down, you might want to clean up the code a bit.
$q = 'thumb_1300625300.jpg';
$files = file_get_contents('files.txt');
$arr = explode('|', $files);
foreach ($arr as &$file) {
if (strpos($file, $q) !== false) {
$file = '';
break;
}
}
$files = implode('|', $arr);
$files = str_ireplace('||', '|', $files);
file_put_contents('files.txt', $files);
Pretty simple code.
- Opens up the file and splits it by |
- Then it loops through the arrray looking for the path that matches the image and makes it empty and then skips the loop
- Then you implode the string and then remove the double | because we removed an element
A couple of caveats. This script only looks for one instance of the path. If you have multiple, then let the loop run its course and remove the break
. You also need to modify str_ireplace('||', '|', $files);
so that it will look for multiple |
What about this?
$file = file_get_contents($txt, true);
$file2 = explode('|', $file);
$new_array = Array();
foreach ($file2 as $path) {
if (/* path should be preserved */) {
$new_array[] = $path;
}
}
$new_contents = implode("|", $new_array);
file_put_contents($txt, $new_contents);
But be aware that a little while after you put this on a public server, your TXT file will be gone. Imagine this:
- 1st process (thread) opens the file for writing (truncating it to 0 characters).
- 2nd process reads the empty file.
- 1st p. writes good file.
- 2nd process writes empty file.
You could get around that by using some lock mechanism, but consider other options. If you have only paths in that file, why not having a special folder for your images? Then just list that folder and you know which files are present. If you want to save some metadata with the images, database is your friend.
精彩评论