How to display images from a folder using php - PHP - php

It would be great if someone could help me figure out why the browser cannot load the images (error 404). The code works, and the image source is correct, but I cannot figure out what is wrong. (using localhost)
$dir = '/home/user/Pictures';
$file_display = array(
'jpg',
'jpeg',
'png',
'gif'
);
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}

You had a mistake on the statement below. Use . not ,
echo '<img src="', $dir, '/', $file, '" alt="', $file, $
to
echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $
and
echo 'Directory \'', $dir, '\' not found!';
to
echo 'Directory \''. $dir. '\' not found!';

Here is a possible solution the solution #3 on my comments to blubill's answer:
yourscript.php
========================
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false)
{
echo 'Directory "', $dir, '" not found!';
}
else
{
$dir_contents = scandir($dir);
foreach ($dir_contents as $file)
{
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)
{
$name = basename($file);
echo "<img src='img.php?name={$name}' />";
}
}
}
?>
img.php
========================
<?php
$name = $_GET['name'];
$mimes = array
(
'jpg' => 'image/jpg',
'jpeg' => 'image/jpg',
'gif' => 'image/gif',
'png' => 'image/png'
);
$ext = strtolower(end(explode('.', $name)));
$file = '/home/users/Pictures/'.$name;
header('content-type: '. $mimes[$ext]);
header('content-disposition: inline; filename="'.$name.'";');
readfile($file);
?>

You have two ways to do that:
METHOD 1. The secure way.
Put the images on /www/htdocs/
<?php
$www_root = 'http://localhost/images';
$dir = '/var/www/images';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if ( file_exists( $dir ) == false ) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir( $dir );
foreach ( $dir_contents as $file ) {
$file_type = strtolower( end( explode('.', $file ) ) );
if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
break;
}
}
}
?>
METHOD 2. Unsecure but more flexible.
Put the images on any directory (apache must have permission to read the file).
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if ( file_exists( $dir ) == false ) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir( $dir );
foreach ( $dir_contents as $file ) {
$file_type = strtolower( end( explode('.', $file ) ) );
if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
break;
}
}
}
?>
And create another script to read the image file.
<?php
$filename = base64_decode($_GET['file']);
// Check the folder location to avoid exploit
if (dirname($filename) == '/home/user/Pictures')
echo file_get_contents($filename);
?>

Related

Display images present on server using PHP

I need to display images on web page from the folder present on server.
I tried this:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) ==false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
It didn't work, so I made some changes and tried this:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) ==false) {
echo 'Directory \''. $dir. '\' not found';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file))); \\ERROR
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="'. $dir. '/'. $file. '" alt="'. $file. '" />';
}
}
}
But there was an error "only variables should be passed by reference", so I tried:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) ==false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
$tmp = explode('.', $file); \\CHANGED THIS LINE
$file_type = end($tmp); \\CHANGED THIS LINE
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
Any ideas how to display images present on server using PHP dynamically?
In one of my projects I used RecursiveDirectoryIterator and RegexIterator that will take care on multiple folders inside images directory and create a array of valid files(that matches the regular expression, in our case files with extension jpg|jpeg|png|gif)
<?php
$folder = 'images';
try {
$directory = new RecursiveDirectoryIterator(realpath($folder));
$iterator = new RecursiveIteratorIterator($directory);
$files = new RegexIterator($iterator, '/^.+\.(jpg|jpeg|png|gif)$/i', RecursiveRegexIterator::GET_MATCH);
} catch (Exception $e) {
echo "Invalid Directory: ".$e->getMessage();
}
//$files is an array with file name of all the valid images
if(isset($files) && $files != null){
foreach($files as $filepath => $value){
echo "<img src='".$filepath."'><br>";
}
}
?>
Hope this helps

How to fix "Only variables should be passed by reference" error

I'm trying to display images from folder. When I run my script I get following error -
"Only variables should be passed by reference in C:\wamp\www\salon\mainS\image_delete.php on line 72"
CODE:
<?php
$dir = 'uploads/';
$display = array('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false) {
echo 'Directory \''. $dir. '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($type, $display) == true)
{
echo'<div style="width:1170px;" >'.
'<div style="float:left; margin-right:5px;" >'.'<img style="width:200px; height:200px;"src="'. $dir. '/'. $file. '" alt="'. $file.'"/>'.'</div>'
.'</div>';
}
}
}
?>
my line 72 is
$type = strtolower(end(explode('.', $file)));
try this
$name_parts = explode('.', $file);
$type = strtolower(end($name_parts));
Try this:
$dir = 'uploads/';
if (file_exists($dir) == false) {
echo 'Directory \''. $dir. '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
try {
if (!is_dir($file) && (getimagesize($file))) {
echo'<div style="width:1170px;" >' .
'<div style="float:left; margin-right:5px;" >' . '<img style="width:200px; height:200px;"src="' . $dir . '/' . $file . '" alt="' . $file . '"/>' . '</div>'
. '</div>' . "\r\n";
}
} catch (Exception $e) {
continue;
}
}
}
Fix it by adding extra bracket, e.g.:
$type = strtolower(end((explode('.', $file))));
See: (<5.6) Occasionally significant parentheses
Assign the result of explode to a temporary variable and pass that variable at end, here is an example.
$tmp = explode('.', $fileName);
$fileExtension = end($tmp);
also to get extension you can also use following method
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);

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";

Get files from a directory in random order using php (xampp)

i'm building a wordpress theme and i'm trying to get the all the jpg files from a directory in random order using php....
im using Xampp on win7 (localhost).
this is the code:
<?
$dir = get_template_directory_uri().'/images/top/';
$file_display = array ('jpg', 'jpeg');
if(file_exists($dir) == false){
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
shuffle($dir_contents);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true){
echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
?>
i always get
Directory 'http://localhost/ni/wp-content/themes/A/images/top/' not found
i also tried to change
$dir = get_template_directory_uri().'/images/top/';
to:
$dir = "C:\xampp\htdocs\Ni\wp-content\themes\A\images\top\";
but still no luck, any help would be appreciated!
This is how i made it work.
<?
$dir = get_template_directory().'/images/top';
$imageDir= get_template_directory_uri().'/images/top';
$file_display = array ('jpg', 'jpeg');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
shuffle($dir_contents);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img src="', $imageDir, '/', $file, '" />';
}
}
}
?>

PHP images from directory - Random order

I have a page of my website which I use to store reference images..
Currently I just drop all of the images into a directory on my server and the php displays them how I like.
What i'd like to ask is how to I get them to display in a different random order every time the page is refreshed?
code is below:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) ==false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
To guarantee that the order is different every time requires that you carry the data about the order in which they were displayed between page loads. However, this is not necessarily what you require - if you simply randomise the order every time then the higher the number of images in the directory the lower the chance you will get the same order twice.
You can simply use shuffle() to randomise the order of the array:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
shuffle($dir_contents);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
Look at shuffle function. http://php.net/manual/en/function.shuffle.php Since PHP is stateless, you'll either rescan your directory each time or assign the $dir_contents to a session variable. Then you could simple shuffle the session variable.
if ($file !== '.' && $file !== '..' && in_array($file_type, suffle($file_display)) == true) {
Try that.
Use php shuffle to the array of images created by scandir
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
if(shuffle($dir_contents)) {
foreach ($dir_contents as $file) {
$info = new SplFileInfo($file);
// scandir returns an array of files and,or directories
// so we should check if $file is a file
// and that it's extension matches the allowed ones
// which are ('jpg', 'jpeg', 'png', 'gif')
if(is_file($file) && in_array($info->getExtension(),$file_display)) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
} else {
echo 'Error applying random order!';
}
}
Please, follow this instruction: create a folder "php" into root of your website and put inside the following php file rotate.php... now create a folder "pic" and "xmas" into your root... you can chose the folder name or other things by editing the var $my_folder_holiday and $my_folder_default...
<?php
##########################################################
# Simple Script Random Images Rotator • 1.4 • 04.01.2020 #
# Alessandro Marinuzzi [alecos] • https://www.alecos.it/ #
##########################################################
function rotate($folder) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder")) && (is_dir($_SERVER['DOCUMENT_ROOT'] . "/$folder"))) {
$list = scandir($_SERVER['DOCUMENT_ROOT'] . "/$folder");
$fileList = array();
$img = '';
foreach ($list as $file) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file")) && (is_file($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file"))) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png') {
$fileList[] = $file;
}
}
}
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder . '/' . $fileList[$imageNumber];
}
return $img;
} else {
mkdir($_SERVER['DOCUMENT_ROOT'] . "/$folder", 0755, true);
}
}
$my_gallery_month = date('m');
$my_folder_default = 'pic';
$my_folder_holiday = 'xmas';
if ($my_gallery_month == 12) {
$my_gallery = rotate($my_folder_holiday);
} else {
$my_gallery = rotate($my_folder_default);
}
?>
The usage is very easy and works very well under PHP 7.4... if you have in the root of your website a folder "pic" and "xmas" containing your images, please, put into your index.php (or other file php located in the root):
<img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67">
This is another usage using FancyBox library:
Hope this helps...

Categories