I have a list of file paths that I want to delete. I placed the file paths in a plaintext file in the root directory of the server. For example:
files_to_be_removed.txt
/path/to/bad/file.php
/path/to/another/bad/file.php
In the same directory, I have another file:
remove.php
$handle = #fopen("files_to_be_removed.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
if (unlink($buffer))
echo $buffer . ' removed.';
}
fclose($handle);
}
When I run my script, nothing is output. Simply, the files in the list aren’t being deleted. Why is that?
$files = file('files_to_be_removed.txt', FILE_IGNORE_NEW_LINES);
foreach ($files as $file) {
if (#unlink($file)) {
echo $file, ' removed', PHP_EOL;
} else {
$error = error_get_last();
echo 'Couldn\'t remove ', $file, ': ', $error['message'], PHP_EOL;
}
}
I'm guessing files are not being deleted because "you already have a LOCK on it" [just a guess] -- since you open it and check it's content.
You can avoid all the stress and simply adjust your entire script to a few lines:
foreach($filepaths as $filepath){
$status = #unlink($filepath);
#the # is there for error suppression -- in case the file doesn't exist
if($status){
#do what you want -- it was successful
}
}
Related
I have a textfile ($file) that contains the path to other files. My goal is to read the content of those files and print it in a table. When reading the paths from $file, only the last line path works correctly.
<?php
$file = "log2.txt";
if(file_exists($file)) {
$handler = fopen($file,'r');
while(!feof($handler)) {
$lines = fgets($handler);
$wordarray = explode(' ', $lines);
#echo $wordarray[0]." ".$wordarray[1]." ".$wordarray[2];
if (strpos($lines, 'NOK') !== false) {
echo "<tr><td>".$wordarray[0]."</td></tr>";
if(file_exists($wordarray[2])){
$log = fopen($wordarray[2], 'r');
#echo "FILE EXISTS ".$log;
$logtext = fread($log,filesize($wordarray[2]));
echo "<tr><td>".$logtext."</td></tr>";
fclose($log);
} else {
echo "<tr><td>"."FILE ".$wordarray[2]." FAILED TO LOAD"."</td></tr>";
}
}
}
fclose($handler);
} else {
echo "FILE DOES NOT EXISTS";
}
?>
Here is an exemple of how log2.txt would look like:
POE NOK poelog.txt
LINK-ERRORS OK OK
LATENCIES NOK latencieslog.txt
VOLATILE NOK volatilelog.txt
I think that the problem could be about line endings or so, but cannot get the point.
You're right. The $wordarray[2] contains also new line character so before using it pass it through trim() function and store it in a variable ($filename in my case).
Updated inner if:
if (strpos($lines, 'NOK') !== false) {
echo "<tr><td>".$wordarray[0]."</td></tr>";
$filename = trim($wordarray[2]);
if (file_exists($filename)){
echo "FILE EXISTS ".$filename;
$log = fopen($filename, 'r');
$logtext = fread($log, filesize($filename));
echo "<tr><td>".$logtext."</td></tr>";
fclose($log);
}
else{
echo "<tr><td>"."FILE ".$filename." FAILED TO LOAD"."</td></tr>";
}
}
This short function works like a sharm:
function displayFileContent( $fileName )
{
$arrayWithFileNames = file ( $fileName );
echo "<table>";
foreach ( $arrayWithFileNames as $singleFileName )
{
# remove the trailing \n on Linux - windows has 2 character as EOL
$singleFileName = trim(preg_replace('/\s\s+/', ' ', $singleFileName));
$contentOfFile = file_get_contents( $singleFileName );
echo "<tr><td>{$contentOfFile}</td></tr>";
}
echo "</table>";
}
You use it like this:
displayFileContent ("path-to-your-file");
Remark: There is no check if the file does exist....
I want to add string text (ip adress) in end of file if not exist.
I have a database with IP Adress, I want to add ip if not exist in my text file.
$rows=mysql_num_rows($resultcheck);
$fields=mysql_num_fields($resultcheck);
for ($i=0;$i<$rows;$i++){
for($j=0;$j<$fields;$j++){
//echo '<b>Date : </b>'.date("Y-m-d").' IP : ';
//echo long2ip(mysql_result($resultcheck,$i,$j)).'<br>';
$file=fopen("ff.txt","a+");
fputs($file,long2ip(mysql_result($resultcheck,$i,$j)).":");
$line=file('ff.txt');
foreach($line as $line){
$arr=explode(':',$line);
if ($arr[0] != long2ip(mysql_result($resultcheck,$i,$j))){
fputs($file,long2ip(mysql_result($resultcheck,$i,$j)).":");
}
}
}
}
For add strings to end of file open file with flag "a"
For compare string - you can open file with function file. It return array of lines in file. For find similar string just use foreach by this array from file.
In other words - show your code
Read line by line from file
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
Append to file
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
I am taking data from text file( data is: daa1 daa2 daa3 on separate lines) then trying to make folders with exact name but only daa3 folders is created. Also when i use integer it creates all folders, same is the case with static string i.e "faraz".
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$line =0;
while ( $line < 5 )
{
$a = fgets($f, 100);
$nl = mb_strtolower($line);
$nl = "checkmeck/".$nl;
$nl = $nl."faraz"; // it works for static value i.e for faraz
//$nl = $nl.$a; // i want this to be the name of folder
if (!file_exists($nl)) {
mkdir($nl, 0777, true);
}
$line++;
}
kindly help
use feof function its much better to get file content also line by line
Check this full code
$file = __DIR__."/dataFile.txt";
$linecount = 0;
$handle = fopen($file, "r");
$mainFolder = "checkmeck";
while(!feof($handle))
{
$line = fgets($handle);
$foldername = $mainFolder."/".trim($line);
//$line is line name daa1,daa2,daa3 etc
if (!file_exists($foldername)) {
mkdir($foldername, 0777, true);
}
$linecount++;
unset($line);
}
fclose($handle);
output folders
1countfaraz
2countfaraz
3countfaraz
Not sure why you're having trouble with your code, but I find it to be more straightforward to use file_get_contents() instead of fopen() and fgets():
$file = __DIR__."/dataFile.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
foreach ($lines as $line) {
$nl = "checkmeck/". $line;
if (!file_exists($nl)) {
echo 'Creating file '. $nl . PHP_EOL;
mkdir($nl, 0777, true);
echo 'File '. $nl .' has been created'. PHP_EOL;
} else {
echo 'File '. $nl .' already exists'. PHP_EOL;
}
}
The echo statements above are for debugging so that you can see what your code is doing. Once it is working correctly, you can remove them.
So you get the entire file contents, split it (explode()) by the newline character (\n), and then loop through the lines in the file. If what you said is true, and the file looks like:
daa1
daa2
daa3
...then it should create the following folders:
checkmeck/daa1
checkmeck/daa2
checkmeck/daa3
Okay. Every file exists, is readable, and is writable. ZIP produces no errors, and outputs: "numfiles: 140 status:0".
the code reads a log, checks for specific text, then imports a number of images into a zip folder. everything runs great except the zip folder is always empty. I've read a lot of threads about this, and they all were resolved by changing permissions, modifying paths and checking for read/write/exist/errors. but... nothing has worked. whats up?
<?php
$file = fopen("log.log", "r") or exit("Unable to open file!");
$zip = new ZipArchive();
$filename = "E:/Web Sites/whatever/order_stream/images.zip";
$try_file = $zip->open($filename,ZIPARCHIVE::OVERWRITE);
if ($try_file !== true) {
exit("cannot open <$filename>\n");
}
while(!feof($file)) {
$line = fgets($file);
$results = explode(": ", $line);
if ($results[0] == "Copying" || $results[0] == "File already exists, overwriting") {
$file_name = substr($results[1],19);
$to_zip = "E:/Web Sites/whatever/catalog/pictures/".$file_name;
$to_zip = trim($to_zip);
if (file_exists($to_zip)) {
$zip->addFile($to_zip);
}
}
}
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
fclose($file);
?>
The ZipArchive::addFile() method accepts the path to the file as its first parameter, but not all paths are created equal. addFile() method silently rejects (bug?) the file and you never know what went wrong. An alternative approach would be:
// $zip->addFile($file);
$content = file_get_contents($file);
$zip->addFromString(pathinfo ( $file, PATHINFO_BASENAME), $content);
In addition to getting the code working, file_get_contents() also generates decent error messages if you made an error in the path. In this example
$file = $full_directory_path_ending_with_slash.$filename;
Since in the above question, you have the parts in your fingers, the code could simply become:
$content = file_get_contents($to_zip);
$zip->addFromString($filename, $content);
I made some kind of PHP file to organize my Images from an old website. The admin of that old site didn't use subfolders so I got thousands of Images in one dir.
I got a csv File with filenames and categories, now I want to just copy this filenames line by line and let PHP copy them to a destenie directory.
This is on XAMPP on my local machine, maybe this is the problem?
Here is what I have already:
<?php
$source = "";
$destination = "Kompaniefest05/";
$handle = fopen($source."names.txt", "r");
$buffers[] = "";
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
array_push($buffers, $buffer);
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
};
foreach ($buffers as $buffer){
echo "Copy ".$source.$buffer." to ".$destination.$buffer;
if(copy($source.$buffer, $destination.$buffer)){
echo "</br>True</br>";
}else{
echo "</br>False</br>";
};
};
?>
The code runs through as expected, and I get list with all filenames inside the .txt file, but always with "False", and the destination directory stays empty.
Is this a configuration problem with XAMPP or do I have some mistakes in my code?
// Edit: Sample of the .txt file
_1_20081008_2089220027.jpg
_2_20081008_1467211531.jpg
_3_20081008_1388589383.jpg
_4_20081008_1327719202.jpg
_5_20081008_1691023977.jpg
_6_20081008_1494910005.jpg
_7_20081008_1101725852.jpg
_8_20081008_1123823020.jpg
_9_20081008_1092805517.jpg
_10_20081008_1752481220.jpg
_11_20081008_1420860420.jpg
_12_20081008_1803761675.jpg
_13_20081008_1199173697.jpg
_14_20081008_1877520136.jpg
_15_20081008_1344646088.jpg
_16_20081008_1918096785.jpg
_17_20081008_1895142423.jpg
_18_20081008_1841060330.jpg
_19_20081008_1438833482.jpg
_20_20081008_1871628956.jpg
_21_20081008_1141581267.jpg
_22_20081008_1416565613.jpg
_23_20081008_1868584205.jpg
_24_20081008_1265588276.jpg
_25_20081008_2023422375.jpg
_26_20081008_1410663038.jpg
_27_20081008_1398533505.jpg
_28_20081008_1413417063.jpg
_29_20081008_1827605061.jpg
_30_20081008_1883399407.jpg
_31_20081008_1468535188.jpg
_32_20081008_1742608861.jpg
_33_20081008_1818421650.jpg
_34_20081008_1682119571.jpg
_35_20081008_1066121950.jpg
Try this, i checked it on localhost with some sample files and its working.
You can also use your own code with a small change.
Just change array_push($buffers, $buffer); to array_push( $buffers, trim( $buffer ) );
Because your file name contains a new line at the end, that stopping you from copying the files.
And always turn on error_reporting while coding :)
<?php
$source = "";
$destination = "Kompaniefest05/";
if ( !file_exists( $destination ) ) {
mkdir( $destination, 0755 );
}
$buffers = file( $source."names.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
foreach( $buffers as $buffer ) {
$fcopy = $source.trim( $buffer );
$tcopy = $destination.trim( $buffer );
echo "Copying ".$fcopy." to ".$tcopy." - ";
if ( file_exists( $fcopy ) ) {
if ( copy( $fcopy, $tcopy ) ) {
echo "SUCCESS";
}
else {
echo "FAILED";
}
}
else {
echo "FILE MISSING";
}
echo "<br />";
}
?>