Jasmine22 Jasmine22 - 2 months ago 10
PHP Question

Appending all files in a directory to one document

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?

Answer

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);
  }
}
Comments