I have a php code which uses every image in a folder and echos the url on my page.
what i need help with is making the php code randomize the list of urls each time the page is loaded.
The code that i have is:
<?php
if ($handle = opendir('images')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$thelist .= '<div data-delay="5"><img src="images/'.$file.'"></div>';
}
}
closedir($handle);
}
?>
<?=$thelist?>
many thanks
Easiest solution would be to put all filenames into an array and then use shuffle() to mix it up. Then you can iterate over the array and output the images. It should look something like this:
<?php
$thelist = "";
if ($handle = opendir('images')) {
$images = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
array_push($images, 'images/'.$file);
}
}
closedir($handle);
shuffle($images);
foreach ($images as $image) {
$thelist .= '<div data-delay="5"><img src="'.$image.'"></div>';
}
echo $thelist;
}
?>
By using glob() instead of opendir() you could shorten the code significantly, as glob() returns an array and then you only would need to shuffle that one.
put your file links into an array and shuffle it with the function shuffle()
<?php
if ($handle = opendir('images')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach($fileTab as $file) {
$thelist .= '<div data-delay="5"><img src="images/'.$file.'"></div>';
}
}
?>
<?=$thelist?>
Instead of directly creating divs in the while loop, use it only to store all urls in an Array. Then shuffel that array, and use a foreach loop in order to populate $thelist.
Why don't you use glob()?
$images = glob('images/*.{jpg,png,gif}', GLOB_BRACE);
shuffle($images);
foreach($images as $image) {
echo '<div data-delay="5">
<img src="', $image ,'">
</div>';
}
Related
I'm using the following PHP code to list all files and folders under the current directory:
<?php
$dirname = ".";
$dir = opendir($dirname);
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "index.php"))
{
echo("<a href='$file'>$file</a> <br />");
}
}
?>
The problem is list is not ordered alphabetically (perhaps it's sorted by creation date? I'm not sure).
How can I make sure it's sorted alphabetically?
The manual clearly says that:
readdir
Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.
What you can do is store the files in an array, sort it and then print it's contents as:
$files = array();
$dir = opendir('.'); // open the cwd..also do an err check.
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..") and ($file != "index.php")) {
$files[] = $file; // put in array.
}
}
natsort($files); // sort.
// print.
foreach($files as $file) {
echo("<a href='$file'>$file</a> <br />\n");
}
<?php
function getFiles(){
$files=array();
if($dir=opendir('.')){
while($file=readdir($dir)){
if($file!='.' && $file!='..' && $file!=basename(__FILE__)){
$files[]=$file;
}
}
closedir($dir);
}
natsort($files); //sort
return $files;
}
?>
<html>
<head>
</head>
<body>
<h1> List of files </h1>
<ul class="dir">
<? foreach(getFiles() as $file)
echo "<li name='$file'><a href='$file'>$file</a></li>";
?>
</ul>
</body>
</html>
Using glob and sort it should work.
You could put all the directory names inside an array like:
$array[] = $file;
After that you can sort the array with:
sort($array);
And then print the links with that content.
I hope this help.
<?php
$dirname = ".";
$dir = opendir($dirname);
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "index.php"))
{
$list[] = $file;
}
}
sort($list);
foreach($list as $item) {
echo("<a href='$item'>$item</a> <br />");
}
?>
I'd recommend moving away from the old opendir()/readdir(). Either use glob() or if you encounter a lot of files in a directory then use the DirectoryIterator Class(es):
http://www.php.net/manual/en/class.directoryiterator.php
http://www.php.net/manual/en/function.glob.php
Regards
You can use this beautiful script:
http://halgatewood.com/free-php-list-files-in-a-directory-script/
the code is
<?php
$files = array();
$dir = opendir('/xampp/htdocs/myfun/template/home');
while(($file = readdir($dir)) !== false) {
if($file !== '.' && $file !== '..') {
$files[] = $file;
}
}
closedir($dir);
//sort($files);
$i=0;
foreach($files as $key) {
echo "<iframe align='center' width='100%' height='605px' src='$key' title='$files[$i]'></iframe>";
break;
}
?>
i want to show templates onclick next/prev button.horizontally.
like slider.
please help
Correct logic to iterate a directory in while loop is false != ($file = readdir($dir)), where you assign file name first and check it's not false.
Also you can print title with $key itself. $files[$i] and $i variable is not required.
In order to iterate through all files of directory remove break, this will cause to end the loop after first iteration.
<?php
$files = array();
$dir = opendir('/xampp/htdocs/myfun/template/home');
while(false != ($file = readdir($dir)))
{
if($file !== '.' && $file !== '..')
{
$files[] = $file;
}
}
closedir($dir);
//sort($files);
foreach($files as $key)
{
echo "<iframe align='center' width='100%' height='605px' src='$key' title='$key'></iframe>";
}
?>
Ok I have a directory with files named by date with the extension ".html".
What I am trying to do is list the contents of the directory, minus the file extension, ordered by date with newest on top.
I have been fiddling with the below code for hours.
<?php
if ($handle = opendir('update_table_cache')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." ) {
$dirFiles[] = $entry ;
rsort($dirFiles);
foreach($dirFiles as $entry) {
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry);
echo ''.$withoutExt.'<br>';
}
}
}
closedir($handle);
}
?>
This outputs something like this:
2016-01-18
2016-01-19
2016-01-18
There should only be one 2016-01-18 and it should be at the bottom. Why is there an extra 2016-01-18 at the top?
Edit: ok I changed it to the following:
<?php
if ($handle = opendir('update_table_cache')) {
$dirFiles[] = $entry ;
rsort($dirFiles);
foreach($dirFiles as $entry) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." ) {
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry);
echo ''.$withoutExt.'<br>';
}
}
}
closedir($handle);
}
?>
But this outputs:
2016-01-18
2016-01-17
2016-01-19
(I added another file "2016-01-17.html")
You're doing the output in the middle of the loop...
First you sort one element and print it, then sort two elements and print it.
Do the output after the loop.
This is what worked:
<?php
$dir = opendir('update_table_cache'); // Open the sucker
$files = array();
while ($files[] = readdir($dir));
sort($files);
closedir($dir);
foreach ($files as $file) {
//MANIPULATE FILENAME HERE, YOU HAVE $file...
if ($file != "." && $file != ".." ){
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file);
echo ''.$withoutExt.'<br>';
}
}
?>
Thanks to user CBroe for pointing me in the right direction!
I have a script file. that list files and folder in a directory.. I want to hide certain files and folder. How do I do that?
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if (($file != ".")
&& ($file != ".."))
{
$thelist .= '<LI>'.$file.'';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<UL>
<P><?=$thelist?></p>
</UL>
<?php
$files_to_hide = array('file1.txt', 'file2.txt');
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if (($file != ".") && ($file != "..") && !in_array($file, $files_to_hide))
{
$thelist .= '<LI>'.$file.'';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<UL>
<P><?=$thelist?></p>
</UL>
Put the list of filenames you want to exclude in an array.
After that, you check whether the filename exists in the array before adding it to $thelist.
You can add that as part of the if() statement that checks if the filename is . or ...
Something like this:
<?php
$bannedFiles = Array(".", "..", "example");
if ($handle = opendir('.')){
while (false !== ($file = readdir($handle)))
{
$banned = false;
foreach ($bannedFiles as $bFile){
if ($bFile == $file){
$banned = true;
}
}
if (!$banned){
$thelist .= '<LI>'.$file.'</LI>';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<UL>
<P><? echo $thelist;?></p>
</UL>
If you know the names of the files/directories you want to hide, you can maintain a set-map of such entries, and filter them out within the while loop.
Your set-map would look like this:
$items_to_hide = [ "/home/me/top_secret" => 1, "/home/me/passwords.txt" => 1, ... ]
And then you would modfiy your while loop like this:
while (false !== ($file = readdir($handle)))
{
// check map if said file is supposed to be hidden, if so skip current loop iteration
if($items_to_hide[$file]) {
continue;
}
if (($file != ".")
&& ($file != ".."))
{
$thelist .= '<LI>'.$file.'';
}
}
Hope this helps.
EDIT:
Also wanted to mention, using a php ordered array as your "blacklist" is quite efficient, as a single lookup will occur in almost constant time. Hence you can grow your blacklist as large as you want and still see decent performance.
i have a propably rather simple question:
I'm using the following script to read a folder?
$count = 0;
if ($handle = opendir(PATH)) {
$retval = array();
while (false !== ($file = readdir($handle))) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if ($file != '.' && $file != '..' && $file != '.DS_Store' && $file != 'Thumbs.db') {
$retval[$count] = $file;
$count = $count + 1;
} else {
//no proper file
}
}
closedir($handle);
}
if a file is an image I print it as an image: print "";
However i wonder how i can display FOLDERS? If i have a subfolder inside of the folder i'm currently running through? how can i print that one?
use glob instead of scandir
$dirs = glob(PATH."/*", GLOB_ONLYDIR);
$images = glob(PATH."/*.[jJ][pJ][gG]");
foreach ($dirs as $name) echo "<b>$name</b><br>\n";
foreach ($images as $name) echo $name."<br>\n";
Use scandir instead of readdir. http://us.php.net/manual/en/function.scandir.php