PHP, delete path from TXT file - php

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.

Related

Deleting multiple file and its name variants with PHP from a text file list

I need to create a script to delete a bunch of images in a wordpress directory. As you may already know, a single image file can have multiple variants, depending on how the images are rendered.
Anyway, i have a list of images in a text file, which contains the following:
wp-content/uploads/2018/09/L_14BQ-FK1
wp-content/uploads/2018/09/L_15EKP160VIBROBT-KIT
wp-content/uploads/2018/09/L_29DS15172GB
wp-content/uploads/2018/09/L_29DS18172GB
wp-content/uploads/2018/09/L_29DS2415
For example i need to delete L_14BQ-FK1.jpg and its variants such as L_14BQ-FK1-100x100.jpg, L_14BQ-FK1-200x200.jpg, etc.
So far i have tried the foreach inside a foreach but its not working:
$list = file('list.txt');
if ($list === false) {
die('Cannot open file');
}
foreach($list as $file){
$theFile = glob($file.'*.jpg');
foreach ($theFile as $single){
echo $single."<br>";
}
}
Surprisingly the echo only produced the last list and its variants, L_29DS2415-100x100.jpg, L_29DS2415-100x200.jpg, etc
Can someone help please?
Reading at the file manual at php.net, I just realised that the array returned from the function FILE include the new line, so revising my original code by adding the flags of 'FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES' works perfectly.
So the final code will be:
$list = file('list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($list === false) {
die('Cannot open file');
}
foreach($list as $file){
$theFile = glob($file.'*.jpg');
foreach ($theFile as $single){
echo $single."<br>";
}
}

On creating zip file by php I get two files instead of one

I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php

PHP search inside loaded text file, converted as array

I need to find a *.jpg name in a text document. For example I have a folder with pictures file1, file2 , file3 and a text document with file1, file, file3 each on a new line. I need to write near each *.jpg the text from the file, but first I need to find the corresponding row in the text document.
<?php
$arrayF = explode("\n", file_get_contents('myTxt.txt'));
// arrayF should the the array with each text line from the txt file.
while(($file = readdir($opendir)) !== FALSE)
{
if($file!="." && $file!="..")
{
$string=$file;
$arrayS = explode('.', $string);//get the name only without .jpg extension
$search=$arrayS[0];
$key = array_search($search, $arrayF);
echo $key;
}
$string=file_get_contents($file);
file_get_contents
Or if you want it line by line, just open, read and close
$fp = fopen($file, 'r');
while ($line = fread($fp)) {
//do comparision stuff
}
fclose ($fp);
Below is an example to iterate through a directory using DirectoryIterator which provides viewing contents of filesystem directories.
Example:
foreach(new DirectoryIterator($dir) as $file_info)
{
// sleep a micro bit (up to 1/8th second)
usleep(rand(0, 125000));
// disregard hidden, empty, invalid name files
if($file_info == null or $file_info->getPathname() == ''
or $file_info->isDot())
{
continue;
}
// check if its a file - log otherwise
// code omitted
// get filename and filepath
$filepath = $file_info->getPathname();
$filename = $file_info->getFilename();
// my answer to read file linked here to avoid duplication
// below "read/parse file into key value pairs"
}
read/parse file into key value pairs
To elaborate new DirectoryIterator( path to dir ) provides an iterator which can be also written as:
$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
// do stuffs
}
Hope this helps, indirectly.

Selecting file to be edited

i have an application that is used to edit .txt files. the application is made up of 3 parts
Displays contents of a folder with the files to be edited(each file is a link when clicked it opens on edit mode).
writing in to a file.
saving to file.
part 2 and 3 I have completed using fopen and fwrite functions that wasn't too hard. the part that i need help is part one currently I open the file by inputing its location and file name like so in the php file where i have the display function and save function:
$relPath = 'file_to_edit.txt';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath ! ");
but what i want is for the file to open in edit mode when clicked instead of typing in the files name every time.
$directory = 'folder_name';
if ($handle = opendir($directory. '/')){
echo 'Lookong inside \''.$directory.'\'<br><br>';
while ($file = readdir($handle)) {
if($file !='.' && $file!='..'){
echo '<a href="'.$directory.'/'.$file.'">'.$file.'<a><br>';
}
}
}
this is the code that ti use to display the list of files that are in a specified folder.
Can anyone give me some pointers how I can achieve this ? any help will be greatly appreciated.
To get content of file use file_get_contents();
To put content of file use file_put_contents(); with FILE_APPEND flag for editing.
To recieve list of files in directory you can use DirectoryIterator
Example:
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
If you don't want to put filenames you can put read files once put in db assign ids to them and use links with id param. The other solution is to store files in session array and assign keys for them. When you want to get a file you just need to provide key instead of whole filename and path.
Example with $_SESSION
$file_arr = array();
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
$file_arr[] = array("path" => $fileInfo->getPathname(), 'name' => $fileInfo->getFilename());
}
$_SESSION['files'] = $file_arr;
then in view you can use
foreach($_SESSION['files'] as $k=>$file)
{
echo "<a href='edit.php?f=".$k."'>'.$file['name'].'</a>";
}
and edit.php
$file = (int)$_GET['f'];
if(array_key_exits($file, $_SESSION['files'])
{
$fileInfo = $_SESSION[$file'];
//in file info you have now $fileInfo['path'] $fileInfo['name']
}

How to give a .php file unique name at top of page, and display unique name on index.php file

I have a question and it's probably a simple one. What I would like to do is be able to place a unique name at the top of each .php file in a folder in the php code area. I would then like a script on the index.php file to look in that folder, pull out the unique names of each .php file found at the top of each page in the php code, and display them in a list on the index.php page.
Would I have to do something like this at the top of the page:
< ?
{{{{{uniquenamehere}}}}}
? >
And If so, what would the code look like for grabbing uniquenamehere and displaying in on the index.php page?
Thanks in advance, let me know if I need to be any more clear in my question. Sorry if it's a really simple question, I'm stumped!
EDIT
Getting this warning when using answer below:
Warning: file_get_contents(test.php) [function.file-get-contents]: failed to open stream: No such file or directory in /path/index.php
Here's the code I am using,
<?php
// Scan directory for files
$dir = "path/";
$files = scandir($dir);
// Iterate through the list of files
foreach($files as $file)
{
// Determine info about the file
$parts = pathinfo($file);
// If the file extension == php
if ( $parts['extension'] === "php" )
{
// Read the contents of the file
$contents = file_get_contents($file);
// Find first occurrence of opening template tag
$from = strpos($contents, "{{{{{");
// Find first occurrence of ending template tag
$to = strpos($contents,"}}}}}");
// Pull out the unique name from between the template tags
$uniqueName = substr($contents, $from+5, $to);
// Print out the unique name
echo $uniqueName ."<br/>";
}
}
?>
Not tested, but it should be roughly something like this.
<?php
// Scan directory for files
$fileInfo = pathinfo(__FILE__);
$dir = $fileInfo['dirname'];
$files = scandir($dir);
// Iterate through the list of files
foreach($files as file)
{
// Determine info about the file
$parts = pathinfo($file);
// If the file extension == php
if ( $parts['extension'] == "php" )
{
// Read the contents of the file
$contents = file_get_contents($file);
// Find first occurrenceof opening template tag
$from = strpos($contents, "{{{{{");
// Find first occurrenceof ending template tag
$to = strpos($contents,"}}}}}");
// Pull out the unique name from between the template tags
$uniqueName = substr($contents, $from+5, $to);
// Print out the unique name
echo $uniqueName ."<br/>";
}
}

Categories