How to print all the txt files inside a folder with php? - php

How to write all the txt files contents in a folder to an html page, besides i don't know the files names, i tried this but it didn't work:
<?php
$files=scandir("D:\\new\places");
foreach (files as value)
echo (files);
?>

you can use following php code to get content of the files.
$path='../innovation';
$files=scandir($path);
//print_r($files);
foreach ($files as $key => $value) {
if($value!="." && $value!="..")
{
print_r(file_get_contents($path."/".$value));
}
}

readfile is ideal for this, since it streams the files directly to the output buffer, which will avoid memory issues for large files.
<?php
$path = 'myDirectory';
$files = glob("{$path}/*.txt");
foreach ($files as $file)
{
readfile($file);
}

If you want to list all the text files (.txt) from a directory to HTML using PHP you can use this code to do it:
<?php
echo '<ul>';
// set the path to the directory...
$dirname = "directory/";
$files = glob($dirname."*.txt");
foreach($files as $file) {
echo '<li>'.$file.'</li>';
}
echo '</ul>';
?>

You can try this:
$directory = "./foldername";
$files = glob($directory . "*.txt");
foreach($files as $file){
$file = fopen($directory . '/' . $file,'r');
while ($line = fgets($file)) {
echo($line);
}
fclose($fh);
}

Use glob() to get all *.txt files in a directory. After loop through every file with a foreach loop and get the content of each file using file_get_contents() and put the content into the target file with file_put_contents()
<?php
$files = glob("path/*.txt");
$output = "output.txt";
foreach($files as $file) {
$content = file_get_contents($file);
print_r($content);
}
?>

Related

php script to delete file names not matching a dynamic text file

I have created a text file (images.txt) located in /home/users/images.txt, the File contain names of jpeg files. for example:
1.jpeg
12.jpeg
33.jpeg
This file is updated regularly and new image filenames are added
I am looking for a php script that can help in reading the filenames from the .txt and deleting any files from /home/user/images/ directory that does not match the filenames in the .txt file
I have tried the below code and cant get it to work
$array = explode("\n", file_get_contents('/home/user/images.txt'));
$directory = "/home/user/images/";
$files = glob($directory . "*.*");
foreach($files as $file)
{
if (!in_array($file, $array)) {
unlink($directory . $file);
}
}
The names returned by glob() include the directory prefix, but the names in $array don't have them. You need to remove the prefix before searching, and you don't need to add it when calling unlink().
$array = file('/home/user/images.txt', FILE_IGNORE_NEW_LINES);
$directory = "/home/user/images/";
$files = glob($directory . "*.*");
foreach($files as $file)
{
if (!in_array(basename($file), $array)) {
unlink($file);
}
}

How to Save Results from Foreach into Txt File

I would like to write all files from specific folder into .txt file. The output working just fine, but I'm getting only one file saved into my txt file. Any idea? Thanks!
$fileList = glob('C:\users\John\Documents\*pdf');
foreach($fileList as $filename){
if(is_file($filename)){
echo $filename, '<br>';
$save_files = fopen("list.txt", "wb");
fwrite($save_files,$filename);
fclose($save_files);
}
}
Here is one way to do it...
foreach($fileList as $filename){
if(is_file($filename)){
echo $filename, '<br>';
$list[] = $filename;
}
}
$capture = implode("\r\n",$list);
file_put_contents("list.txt",$capture);

List with array only some formats files n folder and subdirectory php on Ubuntu Server

I need to list all files for example mp4 or avi in my folder /Files and relative subdirectories and after that insert into <a href={$filename}><\a> tag so I need a array i suppose.
I tried with find command but I receive a string and not a Array so I've to split the string and this isn't practical.
Any suggestion?
or use class RecursiveDirectoryIterator - For example :
$dir_iterator = new RecursiveDirectoryIterator(dirname(__FILE__));
$iterator = new RecursiveIteratorIterator($dir_iterator);
foreach ($iterator as $filename)
{
if (dirname($filename) != dirname(__FILE__))
{
if(is_file($filename)) {
$path_parts = pathinfo($filename);
if($path_parts['extension'] == 'mp4' )
{
print ''.basename($filename)."<br />";
}
}
}
}
<?php
$dir ="/Files";
$files = scandir($dir);
foreach($files as $file) {
$fullname = "/Files/" . $file;
echo '<a href='.$fullname.'>File</a>;
}
This should work for you.

loop through the files in a folder in php

i have searched through the Internet and found the scrip to do this but am having some problems to read the file names.
here is the code
$dir = "folder/*";
foreach(glob($dir) as $file)
{
echo $file.'</br>';
}
this display in this format
folder/s0101.htm
folder/s0692.htm
for some reasons i want to get them in this form.
s0101.htm
s0692.htm
can anyone tell me how to do this?
Just use basename() wrapped around the $file variable.
<?php
$dir = "folder/*";
foreach(glob($dir) as $file)
{
if(!is_dir($file)) { echo basename($file)."\n";}
}
The above code ignores the directories and only gets you the filenames.
You can use pathinfo function to get file name from dir path
$dir = "folder/*";
foreach(glob($dir) as $file) {
$pathinfo = pathinfo($file);
echo $pathinfo['filename']; // as well as other data in array print_r($pathinfo);
}

Display contents of multiple text files

I have a number of text files held in directory
/results/...
All the text files are named with unixtime stamps, inside each of the following files there is:
#text¬test¬test1¬test2¬test3¬test4¬1262384177
Each piece of text is seperated by '¬'.
I'd then like to feed the contents of the text file into an array and output it, in for example a table, but for each of the files (Perhaps loop-like?)
If have this but it only works for one file and fixed file name:
$filename = "results/unixtime.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$array01 = explode("¬",$contents);
$count = count($array01);
echo "<table width = 500 border=1 cellpadding=4>";
$i=0;
for ($i=0;$i<$count;$i++) {
echo "<tr><td>";
echo $array01[$i];
echo "</td></tr>";
}
echo "</table>";
I suggest the fairly-unknown glob function to detect all your files. Then with all the filenames in a handy array, just iterate through and open up/read each one. Sort of like this:
$files = glob('*.txt');
while(list($i, $filename) = each($files)){
//what you have now
}
A couple of things:
Unless you're dealing with really large files just use file_get_contents() to load files. It's a one-liner versus three lines of code that you just don't need;
Loop over arrays using foreach unless you explicitly need a loop counter. The loop condnition/counter is just another area where you can make simple errors;
Use opendir(), readdir() and closedir() for reading directory contents; and
Directories will contain entries like "." and "..". Use filetype() and/or a check on the name and/or extension to limit it to the files you're interested in.
Example:
$directory = "results/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
foreach ($items as $item) {
echo "<tr><td>$item</td></tr>\n";
}
echo '</table>';
}
}
closedir($dir);
You can get all the files located in "result" via opendir.
There is also an example ...
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
Grab the files in the directory and read each filename.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$filename = $file;
//your code
}
}
closedir($handle);
}
?>
source: http://php.net/manual/en/function.readdir.php
Here is a more elegant way of writing brianreavis solution, also use file_get_contents instead of fopen, fread and fclose, it's faster and less verbose.
foreach (glob('*.txt') as $filename)
{
$contents = file_get_contents($filename);
}
Use this code, replace DOCROOT with directory you want to scan.
foreach (scandir(DOCROOT.'css') as $dir) {
echo $dir . "<br>";
echo file_get_contents(DOCROOT . 'css/' . $dir ) . "<hr />";
}

Categories