Insert Images from folder and subfolder php - php

Im trying to insert into html all images that are on the folder "assets/imagens/" and on any subfolders. I also need help to validate not to echo the subfolders.
Im using the code below:
$path = "assets/imagens/";
$diretorio = dir($path);
while($arquivo = $diretorio -> read()){
if($arquivo != '.' && $arquivo != '..'){
echo '<div href="#" class="list-group-item">';
echo '<span class="close-button" secao="imagens">x</span>';
echo "<img class='max-width' src='".base_url().$path.$arquivo."' />";
echo '</div>';
}
}
$diretorio -> close();

$path = "assets/imagens/";
echo_directory_images($path);
function echo_directory_images($path)
{
$diretorio = dir($path);
while($arquivo = $diretorio -> read()){
if($arquivo != '.' && $arquivo != '..'){
if( is_dir($path.$arquivo))
{
//if subfolder
echo_directory_images($path.$arquivo.'/')
}
else{
echo '<div href="#" class="list-group-item">';
echo '<span class="close-button" secao="imagens">x</span>';
echo "<img class='max-width' src='".base_url().$path.$arquivo."' />";
echo '</div>';
}
}
}
}
You may want to give a try to this function. I doubt if this will work exactly but this will surely give an idea about how to recursively call folders and subfolders.

Try this :
function listDir( $path ) {
global $startDir;
$handle = opendir( $path );
while (false !== ($file = readdir($handle))) {
if( substr( $file, 0, 1 ) != '.' ) {
if( is_dir( $path.'/'.$file ) ) {
listDir( $path.'/'.$file );
}
else {
if( #getimagesize( $path.'/'.$file ) ) {
/*
// Uncomment if using with the below "pic.php" script to
// encode the filename and protect from direct linking.
$url = 'http://domain.tld/images/pic.php?pic='
.urlencode( str_rot13( substr( $path, strlen( $startDir )+1 ).'/'.$file ) );
*/
$url='http://localhost/'.$path.'/'.$file;
substr( $path, strlen( $startDir )+1 ).'/'.$file;
// You can customize the output to use img tag instead.
echo "<a href='".$url."'>".$url."</a><br>";
echo "<img class='max-width' src='".$url."' />";
}
}
}
}
closedir( $handle );
} // End listDir function
$startDir = "assets/imagens/";
listDir( $startDir );

You can use RecursiveDirectoryIterator.
For example:
$directory = new RecursiveDirectoryIterator('assets/imagens');
$iterator = new RecursiveIteratorIterator($directory);
foreach ($entities as $name => $entity) {
if ($entity->isDir()) {
continue;
}
$extension = pathinfo($name, PATHINFO_EXTENSION);
if ($extension == 'jpg' || $extension == 'png' || $extension == 'gif') {
echo '<img src="' . $entity->getPathname() . '" />';
}
}

Related

Strict Standards: "Only variables should be passed by reference"

In the php function below I have on line 31 the error "Strict Standards: Only variables should be passed by reference"
As I read the answers on the forum I must change the explode(..). But I don’t have any idea how..
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'png'))
{
if (substr($directory, -1) == 'uploads/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
if (
is_file($path) && in_array(end(explode('.', end(explode('/', $path)))), $exts) // Line 31
) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:100px;max-width:100px" /></a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
According to the PHP Manual for end:
This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.
Parameter should be sent as an array variable only.
ToDo:
Break this statement inside if:
is_file($path) && in_array(end(explode('.', end(explode('/', $path)))), $exts)
to something like this:
$path1 = explode('/', $path);
$path2 = end($path1);
$path3 = explode('.', $path1);
$path4 = end($path3);
is_file($path) && in_array($path4, $exts)
Alternatively,
Since you are getting extension from the path, you can use pathinfo:
pathinfo($path)['extension']
You can try this code:
<?php
<?php
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'png'))
{
if (substr($directory, -1) == 'uploads/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
$path_info = pathinfo($path);
$ext = strtolower($path_info['extension']);
if (is_file($path) && in_array($ext, $exts)) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:100px;max-width:100px" /></a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
try to separate your code in the if statement like this, this should work :
// other code
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
$explode_1 = explode('/', $path);
$explode_2 = explode('.', end($explode_1));
if (is_file($path) && in_array(end($explode_2), $exts)) {
// the rest of the code

how to make this find specific extensions and show only the file name

1) how can i make this read only ".txt" files
2) how can i make it show only the file name so i can design it how i'd i like..
(<h1>$file</h1> for example)
$dir = "includes/news";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh)))
{
if ($filename != "." && $filename != ".." && strtolower(substr($filename, strrpos($filename, '.') + 1)) == 'txt')
{
$files[] = $filename;
}
}
sort($files);
echo $files;
what it shows right now is:
Array ( [0] => . [1] => .. [2] => [23.7] Hey.txt [3] => [24.7] New
Website.txt [4] => [25.7] Example.txt )
Now, this is another way i could do it, i like it bit better:
if( $handle = opendir( 'includes/news' ))
{
while( $file = readdir( $handle ))
{
if( strstr( $file, "txt" ) )
{
$addr = strtr($file, array('.txt' => ''));
echo '<h1>» ' . $addr . "</h1>";
}
}
closedir($handle);
}
but the my issue with this one is that there is no Sorting between the files.
everything is ok with the output, just the order of them. so if one of you can figure out how to sort them right, that would be perfect
Okay, try this:
$files = array();
if($handle = opendir( 'includes/news' )) {
while( $file = readdir( $handle )) {
if ($file != '.' && $file != '..') {
// let's check for txt extension
$extension = substr($file, -3);
// filename without '.txt'
$filename = substr($file, 0, -4);
if ($extension == 'txt')
$files[] = $file; // or $filename
}
}
closedir($handle);
}
sort($files);
foreach ($files as $file)
echo '<h1><a href="?module=news&read=' . $file
. '">» ' . $file . "</a></h1>";
I think this should accomplish what you want to do. It uses explode and a negative limit to find only .txt files and returns only the name.
$dir = "includes/news";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))){
$fileName = explode('.txt', $node, -1)[0];
if(count($fileName) )
$files[] = '<h1>'.$fileName.'</h1>';
}
try to make it as simple as possible
try this
function check_txt($file){
$array = explode(".","$file");
if(count($array)!=1 && $array[count($array)-1]=="txt"){return true;}
return false;
}
if($handle = opendir( 'includes/news' )) {
while( $file = readdir( $handle ))
{
if( check_txt($file) )
{
echo '<h1>» ' . $file . "</h1>";
}
}
closedir($handle);
}

get all the images from a folder in php

I am using WordPress. I have an image folder like mytheme/images/myimages.
I want to retrieve all the images name from the folder myimages
Please advice me, how can I get images name.
try this
$directory = "mytheme/images/myimages";
$images = glob($directory . "/*.jpg");
foreach($images as $image)
{
echo $image;
}
you can do it simply with PHP opendir function.
example:
$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="pictures/'.$file.'" border="0" />';
}
}
When you want to get all image from folder then use glob() built in function which help to get all image . But when you get all then sometime need to check that all is valid so in this case this code help you. this code will also check that it is image
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
$supported_format = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format))
{
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
} else {
continue;
}
}
If you do not want to check image type then you can use this code also
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
}
for more information
PHP Manual
Here is my some code
$dir = '/Images';
$ImagesA = Get_ImagesToFolder($dir);
print_r($ImagesA);
function Get_ImagesToFolder($dir){
$ImagesArray = [];
$file_display = [ 'jpg', 'jpeg', 'png', 'gif' ];
if (file_exists($dir) == false) {
return ["Directory \'', $dir, '\' not found!"];
}
else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($file_type, $file_display) == true) {
$ImagesArray[] = $file;
}
}
return $ImagesArray;
}
}
This answer is specific for WordPress:
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );
$media_dir = $base_dir . 'yourfolder/images/';
$media_url = $hase_url . 'yourfolder/images/';
$image_paths = glob( $media_dir . '*.jpg' );
$image_names = array();
$image_urls = array();
foreach ( $image_paths as $image ) {
$image_names[] = str_replace( $media_dir, '', $image );
$image_urls[] = str_replace( $media_dir, $media_url, $image );
}
// --- You now have:
// $image_paths ... list of absolute file paths
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
// $image_urls ... list of absolute file URLs
// e.g. http://example.com/wp-content/uploads/yourfolder/images/sample.jpg
// $image_names ... list of filenames only
// e.g. sample.jpg
Here are some other settings that will give you images from other places than the child theme. Just replace the first 2 lines in above code with the version you need:
From Uploads directory:
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
$upload_path = wp_upload_dir();
$base_dir = trailingslashit( $upload_path['basedir'] );
$base_url = trailingslashit( $upload_path['baseurl'] );
From Parent-Theme
// e.g. /path/to/wordpress/wp-content/themes/parent-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_template_directory() );
$base_url = trailingslashit( get_template_directory_uri() );
From Child-Theme
// e.g. /path/to/wordpress/wp-content/themes/child-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );
$dir = "mytheme/images/myimages";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
$images=preg_grep ('/\.jpg$/i', $files);
Very fast because you only scan the needed directory.
//path to the directory to search/scan
$directory = "";
//echo "$directory"
//get all files in a directory. If any specific extension needed just have to put the .extension
//$local = glob($directory . "*");
$local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
//print each file name
echo "<ul>";
foreach($local as $item)
{
echo '<li>'.$item.'</li>';
}
echo "</ul>";
Check if exist, put all files in array, preg grep all JPG files, echo new array For all images could try this:
$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);
if ($handle = opendir('/path/to/folder')) {
while (false !== ($entry = readdir($handle))) {
$files[] = $entry;
}
$images=preg_grep('/\.jpg$/i', $files);
foreach($images as $image)
{
echo $image;
}
closedir($handle);
}
<?php
$galleryDir = 'gallery/';
foreach(glob("$galleryDir{*.jpg,*.gif,*.png,*.tif,*.jpeg}", GLOB_BRACE) as $photo)
{echo "\n" ;echo "<img style=\"padding:7px\" class=\"uk-card uk-card-default uk-card-hover uk-card-body\" src=\"$photo\">"; echo "";}?>
UIkit php folder gallery
https://webshelf.eu/en/php-folder-gallery/
// Store your file destination to a variable
$fileDirectory = "folder1/folder2/../imagefolder/";
// glob function will create a array of all provided file type form the specified directory
$imagesFiles = glob($fileDirectory."*.{jpg,jpeg,png,gif,svg,bmp,webp}",GLOB_BRACE);
// Use your favorite loop to display
foreach($imagesFiles as $image) {
echo '<img src="'.$image.'" /><br />';
}
get all the images from a folder in php without database
$url='https://demo.com/Images/sliderimages/';
$dir = "Images/sliderimages/";
$file_display = array(
'jpg',
'jpeg',
'png',
'gif'
);
$data=array();
if (file_exists($dir) == false) {
$rss[]=array('imagePathName' =>"Directory '$dir' not found!");
$msg=array('error'=>1,'images'=>$rss);
echo json_encode($msg);
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
#$file_type = strtolower(end(explode('.', $file)));
// $file_type1 = pathinfo($file);
// $file_type= $file_type1['extension'];
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
$data[]=array('imageName'=>$url.$file);
}
}
if(!empty($data)){
$msg=array('error'=>0,'images'=>$data);
echo json_encode($msg);
}else{
$rees[]=array('imagePathName' => 'No Image Found!');
$msg=array('error'=>2,'images'=>$rees);
echo json_encode($msg);
}
}
You can simply show your actual image directory(less secure). By just 2 line of code.
$dir = base_url()."photos/";
echo"Photo Directory";

PHP pull random image from folder

I am wondering about a "better" way of pulling a random image from a folder.
Like say, to have php just select a random image from folder instead of searching and creating an array of it.
here is how I do it today
<?php
$extensions = array('jpg','jpeg');
$images_folder_path = ROOT.'/web/files/Header/';
$images = array();
srand((float) microtime() * 10000000);
if ($handle = opendir($images_folder_path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$ext = strtolower(substr(strrchr($file, "."), 1));
if(in_array($ext, $extensions)){
$images[] = $file;
}
}
}
closedir($handle);
}
if(!empty($images)){
$header_image = $images[array_rand($images)];
} else {
$header_image = '';
}
?>
Try this:
<?php
$dir = "images/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/<?php echo $images[$i]; ?>" alt="" />
Below code validate image list by image extension.
<?php
function validImages($image)
{
$extensions = array('jpg','jpeg','png','gif');
if(in_array(array_pop(explode(".", $image)), $extensions))
{
return $image;
}
}
$images_folder_path = ROOT.'/web/files/Header/';
$relative_path = SITE_URL.'/web/files/Header/';
$images = array_filter(array_map("validImages", scandir($images_folder_path)));
$rand_keys = array_rand($images,1);
?>
<?php if(isset($images[$rand_keys])): ?>
<img src="<?php echo $relative_path.$images[$rand_keys]; ?>" alt="" />
<?php endif; ?>
function get_rand_img($dir)
{
$arr = array();
$list = scandir($dir);
foreach ($list as $file) {
if (!isset($img)) {
$img = '';
}
if (is_file($dir . '/' . $file)) {
$ext = end(explode('.', $file));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG') {
array_push($arr, $file);
$img = $file;
}
}
}
if ($img != '') {
$img = array_rand($arr);
$img = $arr[$img];
}
$img = str_replace("'", "\'", $img);
$img = str_replace(" ", "%20", $img);
return $img;
}
echo get_rand_img('images');
replace 'images' with your folder.
I searched the internet for hours on end to implement the code to what I wanted. I put together bits of various answers I found online. Here is the code:
<?php
$folder = opendir("Images/Gallery Images/");
$i = 1;
while (false != ($file = readdir($folder))) {
if ($file != "." && $file != "..") {
$images[$i] = $file;
$i++;
}
}
//This is the important part...
for ($i = 1; $i <= 5; $i++) { //Starting at 1, count up to 5 images (change to suit)
$random_img = rand(1, count($images) - 1);
if (!empty($images[$random_img])) { //without this I was sometimes getting empty values
echo '<img src="Images/Gallery Images/' . $images[$random_img] . '" alt="Photo ' . pathinfo($images[$random_img], PATHINFO_FILENAME) . '" />';
echo '<script>console.log("' . $images[$random_img] . '")</script>'; //Just to help me debug
unset($images[$random_img]); //unset each image in array so we don't have double images
}
}
?>
Using this method I was able to implement opendir with no errors (as glob() wasn't working for me), I was able to pull 5 images for a carousel gallery, and get rid of duplicate images and sort out the empty values. One downside to using my method, is that the image count varies between 3 and 5 images in the gallery, probably due to the empty values being removed. Which didn't bother me too much as it works as needed. If someone can make my method better, I welcome you to do so.
Working example (the first carousel gallery at top of website): Eastfield Joinery

automatic image gallery insert

I have this code set up for inserting any image that is uploaded to my "images" folder, right into a gallery I have.... My problem is that it kind of inserts them randomly.. I would like to set it up to insert the most recently uploaded picture to the end of the gallery "row", any suggestions? Thanks
<?php
$image_dir = 'uploads/images/';
$per_column = 10;
if ($handle = opendir($image_dir)) {
while (false !== ($file = readdir($handle)))
{
if ($file != '.' && $file != '..')
{
if(strstr($file,'.png'))
{
$files[] = $file;
}
if(strstr($file,'.jpg'))
{
$files[] = $file;
}
if(strstr($file,'.gif'))
{
$files[] = $file;
}
if(strstr($file,'.jpeg'))
{
$files[] = $file;
}
}
}
closedir($handle);
}
if(count($files))
{
foreach($files as $file)
{
$count++;
echo '<li><img src="',$image_dir,$file,'" width="20" height="20" title="',$file,'"/></li>';
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}
}
else
{
echo 'no pictures yet...';
}
?>
<?php
$image_dir = 'uploads/images/';
$per_column = 10;
$validExt = array(
'png' => 'image/png',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpg',
'gif' => 'image/gif',
);
if ($handle = opendir($image_dir)) {
while (false !== ($file = readdir($handle)))
{
$ext = strtolower(substr($file, -3));
if (isset($validExt[$ext]))
{
$stats = stat($image_dir.$file);
$files[$stats['mtime']] = $file;
}
}
closedir($handle);
}
$count = 0;
krsort($files);
$cnt = count($files);
if($cnt)
{
foreach($files as $file)
{
$count++;
echo '<li><img src="' . $image_dir . $file . '" width="20" height="20" title="' . substr($file, 0, -4) . '"/></li>'.chr(10);
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}
}
else
{
echo 'no pictures yet...';
}
I'm not sure what your file format is, but try setting the filename to the current time using time() when uploading.
When you list your images, try using glob() instead of readdir.
Your code might then go as follows (untested):
$image_dir = 'uploads/images/';
$per_column = 10;
$files = glob($image_dir . "*.jpg|png|gif|jpeg");
if(count($files))
{
foreach($files as $file)
{
$count++;
echo '<li><img src="',$image_dir,$file,'" width="20" height="20" title="',$file,'"/></li>';
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}
}
else
{
echo 'no pictures yet...';
}
Coupling this with giving the uploaded file a filename of the current time, this should order your images by most recent.
The most important line here is $files = glob($image_dir . "*.jpg|png|gif|jpeg");. This will scan the directory for any file (*) ending in .jpg, .png, .gif or .jpeg. You don't need to worry about . and ..; the expression filters that out.

Categories