Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to show all images from my current directory using php script. the php file which is showing image also is in the same directory. here is the script
PHP
<?php 
$dir =basename(__DIR__);
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. '" />';     }    }  }   
 ?>

the output says the no directory exists. but i have seen the directory exists. please tell me whats wrong with my code Thanks
Posted
Comments
Zoltán Zörgő 19-Aug-15 13:56pm    
What is your PHP version?
Are you sure you need basename there?

__DIR__ should equal to dirname(__FILE__) and that is your scripts folder. But whí don't you print it to debug?
saifullahiit 19-Aug-15 14:24pm    
i have optimized my code:
$files = glob(__DIR__.DIRECTORY_SEPARATOR.'*.jpg');
echo $files;
foreach ($files as $file) {
if (!is_file($file)) { // if isn't file, skip it

continue;

}

$info = pathinfo($file);
// check if allowed extensions
if (in_array(strtolower($info['extension']), array('jpg', 'png', 'gif'))) {
echo '<img src="'.$file. '" alt="'.$file. '" />'; // your image echo
}
}
but here images are broken. you can check the link.
Zoltán Zörgő 19-Aug-15 14:31pm    
Are you running this script from command line or over a web server? If you are using a web server you have to consider that the web url will be different from the OS level path.
saifullahiit 19-Aug-15 14:39pm    
can you please tell me how to show images from the current directory

PHP
<?php
$format = '<img src="[FILE]"> [FILE]<br>';

chdir(dirname(__FILE__));

$files = glob("*.{jpeg,jpg,png,gif}", GLOB_BRACE);

foreach ($files as $file) {
    if (is_file($file)) {
        echo str_replace('[FILE]', htmlspecialchars($file), $format);
    }
}
?>
 
Share this answer
 
Here you have it:
PHP
<?php

$urlbase = dirname($_SERVER["SCRIPT_NAME"]);
$ext = array("jpg", "gif", "png");

if ($handle = opendir(__DIR__)) {

    while (false !== ($entry = readdir($handle))) {
        $path_parts = pathinfo($entry);
        if(in_array($path_parts["extension"], $ext)){
            echo "<img src='$urlbase/{$path_parts["basename"]}' alt='$entry' /><br/>";
        }
    }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900