0

I have the next code:

<?php 
    $path = 'imgsFor';
    $files_array = scandir($path);
    for ($x=0; $x<=4; $x++)
    {
    echo '<img src="imgsFor/$files_array[$x]"   <br>';
  }
?>

In order to display all images in the folder imgsFor.

For some reason, I see the just boxes and not the actual images.

What can be the reason?

1
  • The reason is that you're using single-quotes instead of double-quotes, so the the literal string imgsFor/$files_array[$x] will be used instead of the actual variable value. Use double-quotes instead. Commented Nov 26, 2013 at 14:18

4 Answers 4

4

The best way for me is to use glob function:

foreach (glob($path) as $filename) {
    echo '<img src="' . $path . '/' . $filename . '"/><br/>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just asking: What's the advantage of using glob() if you simply want to iterate over all files in a folder? For patterns (something like *.txt) glob() is perfect but is it not an overkill for a simple path?
@TiMESPLiNTER You're right - better is to use scandir with is_dir. :-)
0

You messed up some things. Your correct script would be

<?php 

$path = 'imgsFor/';
$files_array = scandir($path);
foreach($files_array as $f) {
    if(is_dir($path . $f) === false)
        continue;

    echo '<img src="' , $path , $f , '"><br>';
}

/* EOF */

Comments

0

The reason is that your URL is invalid. Your variable wont echo out if you use single quotes. You also forgot to end the tag. Try this:

 echo "<img src='http://yourwebsite.com/imgsFor/{$files_array[$x]}'/><br/>";

2 Comments

@TiMESPLiNTER: they are valid even if using STRICT doctype.
@TiMESPLiNTER: Says who?
0

Please check you directory path and use is_dir which returns false when the file doesn't exist. you can try like this

$path = 'imgsFor';

$scan = scandir($path);

foreach($scan as $file)
{
    if (!is_dir($path))
    {
        echo $file.'\n';
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.