Appending all files in a directory to one document - php

How can I get all the files in my directory on php and put them in one document called "combined.txt"
I had this code before:
file_put_contents("combined.txt", ""); // Empty the file first
foreach ($files as $my_file) {
file_put_contents("combined.txt", $my_file, FILE_APPEND);
}
But I get this error:
Warning: Invalid argument supplied for foreach() in /script2.php on
line 177
I think its because I didn't delceare which files, I just have this code before it:
$directory_with_files = './'.date('m-d-Y');
$dh = opendir($directory_with_files);
$files = array();
while (false !== ($filename = readdir($dh)))
{
if(in_array($filename, array('.', '..')) || is_dir($filename))
continue;
$files[] = $filename;
}
Any ideas?

You can achive this by using scandir() function
$directory_with_files = './'.date('m-d-Y');
$files = scandir($directory_with_files);
$valid_extension=array('txt','php','inc')// make a list of valid extention
foreach($files as $file)
{
$ext=explode('.',$file);
$ext=strtolower(array_pop($ext))
if(in_array($ext,$valid_extension))
{
include_once($directory_with_files."/".$file);
}
}

Related

How to delete file in PHP

I want to delete files in a specific directory in PHP. How can I achieve this?
I have the following code but it does not delete the files.
$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
unlink($file);
}
I think your question isn't specific, this code must clear all files in the directory 'files'.
But there are some errors in that code I think, and here is the right code:
$files= array();
$dir = dir('files');
while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
if ($file != '.' && $file != '..') {
$files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..)
}
unlink('files/'.$file); // This must remove the file in the queue
}
And finally make sure that you provided the right path to dir().
You can get all directory contents with glob and check if the value is a file with is_file() before unlinking it.
$files = glob('files/*'); // get directory contents
foreach ($files as $file) { // iterate files
// Check if file
if (is_file($file)) {
unlink($file); // delete file
}
}
If you want to remove files matching a pattern like .png or .jpg, you have to use
$files = glob('/tmp/*.{png,jpg}', GLOB_BRACE);
See manual for glob.

linking directories and files in php

Hello stackoverflow community;
I'm trying to display a few files in a directory using php and coming unstuck:
In my file ('salad') I have three recipe files ('recipe1.txt', recipe2.txt, 'recipe3.txt') and I want to display them so I'm writing the following:
$script = opendir('salad');
while(false !==($file = readdir($script))) {
if (is_file($file)) {
echo "<p>$file</p>";
}
}
Unfortunately this only echos to the screen .DS_store, what am i doing wrong?
You could use this:
<?php
$dir = "/tmp"; // put what suits you here
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
sort($files);
print_r($files);
rsort($files);
echo"$files";
?>
source:
http://php.net/manual/en/function.scandir.php

XAMPP rename function

I'm trying to write a bulk rename in this way:
if ($handle = opendir('../../upload_files')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(", ","_",$fileName);
rename($fileName, $newName);
$count++;
}
closedir($handle);
echo $count." files renamed";
}
But when I run the script, I get a warning:
Warning: rename(..,..) [function.rename]: No error in E:\WEBS\rename.php on line 6
What is causing the error?
If the target file already exists, PHP is known for such error under Windows environment.
There's a known bug for PHP 5.3 https://bugs.php.net/bug.php?id=48771 with similar error message.
I recommend trying out following modification of your code (it's based on your code, just with some corrections)
$dir = "../../upload_files";
if ($handle = opendir($dir))
{
while (false !== ($fileName = readdir($handle)))
{
if (!isset($count)) $count = 0;
if ($fileName == ".." || $fileName == ".") continue;
$newName = str_replace(", ","_",$fileName);
copy($dir.$fileName, $dir.$newName);
$count++;
}
closedir($handle);
echo $count." files renamed";
}

php readdir and is_dir

I am testing out the functions of directory handling. I have a fold/directory that contains the following:
0 File folder
false File folder
my_pictures File folder
MVI_3094 mov file
img01 jpeg image
etc...
I wrote the following code to traverse the directory and print out specific resutls
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($entry))
{
echo "Directory:$entry<br />";
}
}
My only problem is that the second "if" statement does not output the results of
echo "Directory:$entry<br />";
even though the entry is a directory. I have checked the entry manually with the "var_dump" function and it returns true as a directory.
Any suggestions would help
Try this and check. Just a try...
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
elseif(is_dir("files/".$entry))
{
echo "Directory:$entry<br />";
}
}
$entry is relative... is_dir expects an absolute path.
Try:
if(is_dir("files/".$entry))
readdir() is just returning the filenames. Your code is therefore looking for the files in the current directory rather than the subdirectory.
This will just probe the basename of whatever directory entry:
is_dir($entry)
The opendir() result list will be relative to the directory you gave for reading. So you need to use:
is_dir("files/$entry")
Your problem is that in elseif(is_dir($entry)) {, entry is equal to some string like "file.txt" or "somedirectory", which isn't a path pointing to a file at all. It needs to be "files/file.txt".
Try this:
$dir = "files/";
$handle = opendir($dir);
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($dir.$entry))
{
echo "Directory:$entry<br />";
}
}
Try using the DirectoryIterator:
$iterator = new \DirectoryIterator(realpath('files/'));
foreach($iterator as $file){
if($file->isDot())
continue;
if($file->isDir())
printf('Directory: %s <br/>', $file->getRealPath());
}

Get the files inside a directory

How to get the file names inside a directory using PHP?
I couldn't find the relevant command using Google, so I hope that this question will help those who are asking along the similar lines.
There's a lot of ways. The older way is scandir but DirectoryIterator is probably the best way.
There's also readdir (to be used with opendir) and glob.
Here are some examples on how to use each one to print all the files in the current directory:
DirectoryIterator usage: (recommended)
foreach (new DirectoryIterator('.') as $file) {
if($file->isDot()) continue;
print $file->getFilename() . '<br>';
}
scandir usage:
$files = scandir('.');
foreach($files as $file) {
if($file == '.' || $file == '..') continue;
print $file . '<br>';
}
opendir and readdir usage:
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..') continue;
print $file . '<br>';
}
closedir($handle);
}
glob usage:
foreach (glob("*") as $file) {
if($file == '.' || $file == '..') continue;
print $file . '<br>';
}
As mentioned in the comments, glob is nice because the asterisk I used there can actually be used to do matches on the files, so glob('*.txt') would get you all the text files in the folder and glob('image_*') would get you all files that start with image_
The Paolo Bergantino's answer was fine but is now outdated!
Please consider the below official ways to get the Files inside a directory.
FilesystemIterator
FilesystemIterator has many new features compared to its ancestor DirectoryIterator as for instance the possibility to avoid the statement if($file->isDot()) continue;. See also the question Difference between DirectoryIterator and FilesystemIterator.
$it = new FilesystemIterator(__DIR__);
foreach ($it as $fileinfo) {
echo $fileinfo->getFilename() , PHP_EOL;
}
RecursiveDirectoryIterator
This snippet lists PHP files in all sub-directories.
$dir = new RecursiveDirectoryIterator(__DIR__);
$flat = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($flat, '/\.php$/i');
foreach($files as $file) {
echo $file , PHP_EOL;
}
See also the Wrikken's answer.
Most of the time I imagine you want to skip . and ... Here is that with
recursion:
<?php
$o_dir = new RecursiveDirectoryIterator('.', FilesystemIterator::SKIP_DOTS);
$o_iter = new RecursiveIteratorIterator($o_dir);
foreach ($o_iter as $o_name) {
echo $o_name->getFilename();
}
https://php.net/class.recursivedirectoryiterator
The old way would be:
<?php
$path = realpath('.'); // put in your path here
$dir_handle = #opendir($path) or die("Unable to open $path");
$directories = array();
while ($file = readdir($dir_handle))
$directories[] = $file;
closedir($dir_handle);
?>
As already mentioned the directory iterator might be the better way for PHP 5.

Categories