I need to create a full page gallery showing only the last 4 images from a directory, i don't have idea how to introduce only the last 4 images saved in the directory, any idea?
<?php
$directory= "img";
$dirint = dir($directory);
while (($archivo = $dirint->read()) !== false){
if (!preg_match('/gif/i', $archivo)
|| !preg_match('/jpg/i', $archivo)
|| !preg_match('/png/i', $archivo)) {
for($x = 0; $x < 3; $x++) {
echo '<img src="'.$directory."/".$archivo.'">'."\n";
echo "<br>";
$x++;
}
}
}
$dirint->close();
?>
Hi i resolve my problem with a slice to the array dirint, thanks for the help here my solution:
<?php
$img_dir = "THEPATHTOYOURDIRECTORY";
$images = scandir($img_dir);
$imageslast = array_slice($images,-4,6);
rsort($imageslast);
with imagelast i make a slice to the array counting the "." and ".." i sorted in reverse to take the last image.
Related
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 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.
This is my first project using PHP and I've been stuck on this for almost 2 days now!
I want to get all my PHP files from a directory and any sub directories and display them in iframes.
I've managed to get it to display all the files in the directory, but I only want the PHP files, please see below. Thanks in advance for any help/advice.
<?php
$path[] = 'work/*';
while(count($path) != 0)
{
$v = array_shift($path);
foreach(glob($v) as $item)
{
if (is_dir($item))
$path[] = $item . '/*';
elseif (is_file($item))
{
printf(
"<iframe width=420 height=150 frameborder=0 src='$item'></iframe>",
($file),$target);
}
}
}
?>
Change your glob pattern from work/* to work/*.php.
Change:
elseif (is_file($item))
To
elseif (is_file($item) && substr($item, -4) == '.php')
You can also use PHP's directory iterators, but the above is all you really need to do to get it working.
Eh, for fun, here's the iterator approach:
$dir = new RecursiveDirectoryIterator('work');
$iter = new RecursiveIteratorIterator($dir);
$regex = new RegexIterator($iter, '/^.+\.php$/');
foreach($regex as $filename)
{
// do something with $filename
}
Simple...replace $path[] = 'work/*'; with $path[] = 'work/*.php';
You're already using glob, this is the simplest way.
You should have better code :)
I specially did not add iframe so you can edit it by yourself to get a bit more experience :)
<?php
$iterator = new RecursiveDirectoryIterator('work/');
$files_count = 0;
foreach( new RecursiveIteratorIterator($iterator) as $filename => $cur) {
$file_info = pathinfo($filename);
if($file_info['extension'] === 'php') {
$files_count++;
echo $filename . "<br />";
}
}
echo "Total: $files_count files<br />";
?>
I would like to stick a php code (readdir and print links to page) into a Dynamic Ajax Content script like below. Is this even possible as I am getting errors? Any help would be very appreciated.
TEXT HERE DOES NOT MATTER
This is the PHP script I want to use to scan the directory and print links to page.
<?php
// These files will be ignored
$excludedFiles = array (
'excludeMe.file',
'excludeMeAs.well'
);
// These file extensions will be ignored
$excludedExtensions = array (
'html',
'xslt',
'htm',
);
// Make sure we ignore . and ..
$excludedFiles = array_merge($excludedFiles,array('.','..'));
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] =
strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] =
strtolower($excludedExtensions[$i]);
// Loop through directory
$dir = 'dir_1/dir_2/';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
$extn = explode('.',$file);
$extn = array_pop($extn);
// Only echo links for files that don't match our rules
if (!in_array(strtolower($file),$excludedFiles) &&
!in_array(strtolower($extn),$excludedExtensions)) {
$count++;
print("".$file."<br />\n");
}
}
echo '<br />';
closedir($handle);
}
?>
I think you might be missing a html element with the id of rightcolumn?
You need to add a div or some other container on the page with the id of rightcolumn. The script will then populate this container with the output of your php script.
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.