I have a php code that will display the amount of files that i have in a folder.
Code: This will echo this on my page, "There are a total of 119 Articles"
$directory = "../health/";
if (glob($directory . "*.php") != false) /* change php to the file you require either html php jpg png. */ {
$filecount = count(glob($directory . "*.php")); /* change php to the file you require either html php jpg png. */
echo "<p>There are a total of";
echo " $filecount ";
echo "Articles</p>";
} else {
echo 0;
}
Question:
I am wanting to count the files from 27 or more folders and echo the total amount of files.
Is there away i can add a list of folders to open such as:
$directory = "../health/","../food/","../sport/";
then it will count all the files and display the total "There are a total of 394 Articles"
Thanks
Yes you can:
glob('../{health,food,sport}/*.php', GLOB_BRACE);
Undoubtedly, this is less efficient than clover's answer:
$count = 0;
$dirs = array("../health/","../food/","../sport/");
foreach($dirs as $dir){
if($files = glob($dir."*.php")){
$count += count($files);
}
}
echo "There are a total of $count Articles";
A simple answer is to just use an array and a loop. It is something you could have figured out yourself.
$directories = array('../health/', '../food/', '../sport/');
$count = 0;
foreach ($directories as $dir) {
$files = glob("{$dir}*.php") ?: array();
$count += count($files);
}
echo "<p>There are a total of {$count} articles</p>";
But #clover's answer is better.
As usual, it's often much better to divide your problem. E.g.:
Obtain the files (See glob).
Count the files of a glob result (Write a function that takes care of two the FALSE and Array cases.).
Do the output (don't do the output inside the other code, do it at the end, use variables (as you already do, just separate the output)).
Some Example Code:
/**
* #param array|FALSE $mixed
* #return int
* #throws InvalidArgumentException
*/
function array_count($mixed) {
if (false === $mixed) {
return 0;
}
if (!is_array($mixed)) {
throw new InvalidArgumentException('Parameter must be FALSE or an array.');
}
return count($mixed);
}
$directories = array("health", "food", "string");
$pattern = sprintf('../{%s}/*.php', implode(',', $directories));
$files = glob($pattern, GLOB_BRACE);
$filecount = array_count($files);
echo "<p>There are a total of ", $filecount, " Article(s)</p>";
You could use the opendir command explained here:
http://www.php.net/manual/en/function.opendir.php
combined with the example shown on previous link:
<?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);
}
}
?>
Basically opening the folder you first go through and in a loop count every singel item that is not a folder.
Edit:
Seems like someone has given a simpler solution than this.
Related
Im really new to PHP i searched google to find a correct script that loops through all subfolders in a folder and get all files path in that subfolder
<?php
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename. '<br/>';
}
?>
So i have folder 'posts' in which i have subfolder 'post001' in which i have two files
controls.png
text.txt
And the code above echos this
posts\.
posts\..
posts\post001\.
posts\post001\..
posts\post001\controls.png
posts\post001\text.txt
But i want to echo only the file paths inside these subfolders like this
posts\post001\controls.png
posts\post001\text.txt
The whole point of this is that i want to dynamically create divs for each subfolder and inside this div i put img with src and some h3 and p html tags with text equal to the .txt file so is this proper way of doing that and how to remake my php script so that i get just the file paths
So I can see the answers and they are all correct but now my point was that i need something like that
foreach( glob( 'posts/*/*' ) as $filePath ){
//create div with javascript
foreach( glob( 'posts/$filePath/*' ) as $file ){
//append img and h3 and p html tags to the div via javascript
}
//append the created div somewhere in the html again via javascript
}
So whats the correct syntax of doing these two foreach loops in php im really getting the basics now
See if this works :)
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if ((substr($file, -1) != '.') && (substr($file, -2) != '..')) {
echo $file . '<br/>';
}
}
<h1>Directory Listing</h1>
<?php
/**
* Recursive function to append the full path of all files in a
* given directory $dirpath to an array $context
*/
function getFilelist($dirpath, &$context){
$fileArray = scandir($dirpath);
if (count($fileArray) > 2) {
/* Remove the . (current directory) and .. (parent directory) */
array_shift($fileArray);
array_shift($fileArray);
foreach ($fileArray as $f) {
$full_path = $dirpath . DIRECTORY_SEPARATOR . $f;
/* If the file is a directory, call the function recursively */
if (is_dir($full_path)) {
getFilelist($full_path, $context);
} else {
/* else, append the full path of the file to the context array */
$context[] = $full_path;
}
}
}
}
/* $d is the root directory that you want to list */
$d = '/Users/Shared';
/* Allocate the array to store of file paths of all children */
$result = array();
getFilelist($d, $result);
$display_length = false;
if ($display_length) {
echo 'length = ' . count($result) . '<br>';
}
function FormatArrayAsUnorderedList($context) {
$ul = '<ul>';
foreach ($context as $c) {
$ul .= '<li>' . $c . '</li>';
}
$ul .= '</ul>';
return $ul;
}
$html_list = FormatArrayAsUnorderedList($result);
echo $html_list;
?>
Take a look at this:
<?php
$filename[] = 'posts\.';
$filename[] = 'posts\..';
$filename[] = 'posts\post001\.';
$filename[] = 'posts\post001\..';
$filename[] = 'posts\post001\controls.png';
$filename[] = 'posts\post001\text.txt';
foreach ($filename as $file) {
if (substr($file, -4, 1) === ".") {
echo $file."<br>";
}
}
?>
Result:
posts\post001\controls.png
posts\post001\text.txt
What this does is checking if the 4th last digit is a dot. If so, its an extension of three letters and it should be a file. You could also check for specific extensions.
$ext = substr($file, -4, 4);
if ($ext === ".gif" || $ext === ".jpg" || $ext === ".png" || $ext === ".txt") {
echo $file."<br>";
}
Problem:
I have a zip file that contains 13 xml files. Each file, except for the first one, contain a quiz question and several answers. When I upload the file to the below script it prints out the questions and the answers correctly, but NOT in order. The order of questions randomly shift each time I upload the zip-file.
Question:
Is there a way I can utilize the file names to tell the script to print out the questions in sequential order every time?
Zip-file contain:
imsmanifest.xml
item101008.xml
item101009.xml
item101010.xml
item101011.xml
item101012.xml
item101013.xml
item101014.xml
item101015.xml
item101016.xml
item101017.xml
item101018.xml
item101019.xml
PHP-script (warning, long script):
<?php
//Initialize counter
$i = 0;
//Go through each file
while (($file = readdir($dh)) !== false)
{
//Skipt the first loop
if ($i > 1)
{
//Ignore misc file
if ($file != 'imsmanifest.xml')
{
//Create new DOM document
$dom= new DOMDocument();
//Load XML file
$dom->load('uploads/' . $file);
//Do not preserve white space
$dom->preserveWhiteSpace = false;
//Check if correct answers should be displayed
if (isset($_POST['XMLAnswers']))
{
//Get correct answer
$correct = $dom->getElementsByTagName( "correctResponse" )->item(0)->nodeValue;
//Get question
$questions = $dom->getElementsByTagName('p')->item(0)->nodeValue;
//Print out question
echo '<h4>' . htmlspecialchars($questions) . '</h4>' . "\n";
//Get answers
$domTable = $dom->getElementsByTagName("simpleChoice");
//Loop through each answer
foreach ($domTable as $answers)
{
//Delete potential unnecessary tags
$pattern = array(
'<p xmlns="http://www.imsglobal.org/xsd/imsqti_v2p1">',
'</p>'
);
//Check if answer is correct one
if ($correct == $answers->getAttribute('identifier'))
{
//Print out correct answer
echo '<span style="color:red;">' . utf8_decode(str_replace($pattern, '', innerHTML($answers))) . '</span><br />' . "\n";
}
else
{
//Print out answer
echo utf8_decode(str_replace($pattern, '', innerHTML($answers))) . '<br />' . "\n";
}
}
}
}
}
//Increment counter
$i++;
}
?>
Rather than using opendir/readdir, use scandir. See http://www.php.net/manual/en/function.scandir.php. scandir returns you a sorted array of files in the directory. You should be able to drop this in and have your code work with minimal changes, other than replacing the outer while readdir loop with:
$files = scandir($dir);
foreach ($files as $file) {
//your current code
}
I have this php code that works great, but the only thing is that images that are loaded from the folder are random, and I need them to load numerically by order.
`
//Open images directory
$dir = opendir("../blogimg/luda_jesus");
//List files in images directoryb
while (($file = readdir($dir)) !== false)
{
if(substr( $file, -3 ) == "jpg" )
{
echo "<div class='container'><img class='lazy' id='background' src='../blogimg/loader.gif' data-original='../blogimg/luda_jesus/" . $file . "' width='884' height='587'></div>";
//echo "<br />";
}
}
closedir($dir);
?>`
Please help me
You can do this much more easily with glob:
$files = glob("../blogimg/luda_jesus/*.jpg");
natsort($files); // can also use other sort functions here, take your pick
foreach ($files as $file) {
echo '...';
}
I chose natsort as the sort function above because it will sort 2.jpg before 10.jpg, while plain sort will do the opposite. See comparison of array sorting functions for more information.
Assuming "numerically" means by filename, you can simply do you while loop and populate all files in an array, sort it, and then load the files.
Example:
//Open images directory
$dir = opendir("../blogimg/luda_jesus");
//List files in images directoryb
while (($file = readdir($dir)) !== false) {
if(substr( $file, -3 ) == "jpg" ) {
$filelist[] = $file;
}
}
closedir($dir);
sort($filelist);
for($i=0; $i<count($filelist)-1; $i++) {
echo "<div class='container'>
<img class='lazy' id='background'
src='../blogimg/loader.gif'
data-original='../blogimg/luda_jesus/" . $file . "'
width='884' height='587'>
</div>";
}
If you require different means of sorting, please mention so.
I need to find word count for all of the files within a folder.
Here is the code I've come up with so far:
$f="../mts/sites/default/files/test.doc";
// count words
$numWords = str_word_count($str)/11;
echo "This file have ". $numWords . " words";
This will count the words within a single file, how would I go about counting the words for all files within a given folder?
how about
$array = array( 'file1.txt', 'file2.txt', 'file3.txt' );
$result = array();
foreach($array as $f ){
$result[$f] = str_word_count(file_get_contents($f));
}
and using the dir
if ($handle = opendir('/path/to/files')) {
$result = array();
echo "Directory handle: $handle\n";
echo "Files:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..')
continue;
$result[$file] = str_word_count(file_get_contents('/path/to/files/' . $file));
echo "This file {$file} have {$result[$file]} words";
}
closedir($handle);
}
Lavanya, you can consult the manual of readdir, file_get_contents.
Assuming the doc files are plaintext and don't contain additional markup, you can use the following script to count all of the words in all of the files:
<?php
$dirname = '/path/to/file/';
$files = glob($dirname.'*');
$total = 0;
foreach($files as $path) {
$count = str_word_count(file_get_contents($path));
print "\n$path has $count words\n";
$total += $count;
}
print "Total words: $total\n\n";
?>
If you are using *nux than you can use system('cat /tmp/* | wc -w')
You can use $words = str_word_count(file_get_contents($filepath)) to get the word count of a text file, however this won't work for word docs. You'll need to find a library or external program that can read the .doc file format.
I have the following code which outputs the contents of text files held in a directory.
Ive been looking at the sort command in PHP but cant get it to work with the following code, I usually get an error about the input being a string and not an array.
How can I sort the directory of file before they are output?
$directory = "polls/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
list($tag, $name, $description, $text1, $text2, $text3, $date) = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
echo "<tr><td>$tag</td></tr>\n";
echo "<tr><td>$name</td></tr>\n";
echo "<tr><td>$description</td></tr>\n";
echo "<tr><td>$text1</td></tr>\n";
echo "<tr><td>$text2</td></tr>\n";
echo "<tr><td>$text3</td></tr>\n";
echo "<tr><td>$date</td></tr>\n";
echo '</table>';
}
}
closedir($dir);
First collect the entries in an array, sort it and then put it out:
$directory = "polls/";
$dir = opendir($directory);
$files = array();
while (($file = readdir($dir)) !== false) {
$files[] = $file;
}
closedir($dir);
sort($files);
foreach ($files as $file) {
// content of your original while loop
}
Another possibility is fetching the file names with glob(). Its output is sorted by default.
<?php
foreach(glob('polls/*.txt') as $file){
// ...
}
?>
Don't print it in the while loop, but store it in an array. Sort the array and then print it.
(On php.net you'll find enough different sorting functions to get the sorting method you need.)