/    Sign up×
Community /Pin to ProfileBookmark

Can’t read images in from directory using PHP

I’ve spent a day and a half attempting to read images from a folder and then printing them to a webpage. I have used code provided at a few different reputable websites. They have not worked.

I’ve used glob, opendir, and scandir to read the folders.

What I am seeing:

  • 1. The user drops through the loop once.

  • 2. The variable used for the image does not print a value.
  • My belief is that the code is not in any of these instances seeing an image. That has led me to think that I am pointing to the wrong folder. This is a WordPress install located in a subdirectory: [url]http://domainname/subdirectory/wordpressinstall/wp-content/uploads[/url]. The images are in the uploads folder.

    The directory path I have used is $dir = /trophy/wp-content/uploads.

    Any and all help is appreciated.

    to post a comment
    PHP

    15 Comments(s)

    Copy linkTweet thisAlerts:
    @gvreFeb 18.2013 — Could you post your code and the path of the script?
    Copy linkTweet thisAlerts:
    @rwilliams1961authorFeb 18.2013 — $current_dir = 'domainname/trophy/wp-content/uploads/';

    echo $current_dir;

    $dir = opendir($current_dir);

    while ($file = readdir($dir))


    {

    $parts = explode(".", $file);


    if (is_array($parts) && count($parts) > 1)


    {

    $extension = end($parts);


    if ($extension == "ext")


    {

    echo 'hello';


    }

    }

    closedir($dir);
    Copy linkTweet thisAlerts:
    @rwilliams1961authorFeb 18.2013 — This is another version:

    $dir = '/trophy/wp-content/uploads';
    $scan = scandir($dir);
    for ($i=0; $i<count($scan); $i++)
    {
    echo '<img src="'.$dir.'/'.$scan[$i].'">';
    echo '<p>'.$scan[$i];
    if (strpos($scan[$i], 'cat') !== false)
    {
    echo '<div id="#catalog-directory-images">';
    echo '<img src="'.$page_url.$dir.$scan[$i].'" alt="'.$scan[$i].'" />';
    echo '</div>';
    }
    }
    Copy linkTweet thisAlerts:
    @gvreFeb 18.2013 — [code=php]function GetImages($dir, array $extensions, $prefix = "")
    {
    $images = array();
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
    while($it->valid())
    {
    if (($pos = strrpos($it->getSubPathName(), '.')) !== false &&
    in_array(substr($it->getSubPathName(), $pos + 1), $extensions))
    {
    if ($prefix)
    $prefix = rtrim($prefix, '/') . '/';
    $images[] = $prefix . $it->getSubPathName();
    }
    $it->next();
    }
    return $images;
    }

    $dir = dirname(__FILE__) . '/wp-content/uploads';
    $extensions = array('jpg', 'png', 'gif');
    $prefix = '/wp-content/uploads';
    $images = GetImages($dir, $extensions, $prefix);
    [/code]


    I assume that the script's path is the root dir of wordpress. If not, you should change $dir and $prefix.
    Copy linkTweet thisAlerts:
    @rwilliams1961authorFeb 18.2013 — So I plugged it in exactly as you sent it EXCEPT that I added the subdirectory that the WordPress install is in, so the directory and prefix paths are /trophy/wp-content/uploads.

    The result is that when I publish the page, the HTML ends at on the line previous to your code. It's all white from just before "<?php"

    Any ideas?
    Copy linkTweet thisAlerts:
    @gvreFeb 18.2013 — You don't need to change the $dir and $prefix if the script is inside the wordpress root dir. The $images contains an array with all images' paths. You should add a foreach construct to iterate over it.

    e.g.
    [code=php]foreach($images as $img)
    {
    echo '<img src="' . $img . '" /><br />';
    }[/code]
    Copy linkTweet thisAlerts:
    @rwilliams1961authorFeb 18.2013 — Okay, I'll plug that in. Thank you.

    Still, why did the HTML stop when it hit the code - not even my footer?
    Copy linkTweet thisAlerts:
    @gvreFeb 18.2013 — Did you wrap the code in <?php ?> tags?
    Copy linkTweet thisAlerts:
    @rwilliams1961authorFeb 18.2013 — Yes:

    <?php


    function GetImages($dir, array $extensions, $prefix = "")

    {

    $images = array();

    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));

    while($it->valid())

    {

    if (($pos = strrpos($it->getSubPathName(), '.')) !== false &&

    in_array(substr($it->getSubPathName(), $pos + 1), $extensions))

    {

    if ($prefix)

    $prefix = rtrim($prefix, '/') . '/';

    $images[] = $prefix . $it->getSubPathName();




    }
    $it->next();




    }
    return $images;



    foreach($images as $img)

    {

    echo '<img src="' . $img . '" /><br />';

    }



    }

    $dir = dirname(__FILE__) . '/wp-content/uploads';

    $extensions = array('jpg', 'png', 'gif');

    $prefix = '/wp-content/uploads';

    $images = GetImages($dir, $extensions, $prefix);

    ?>
    Copy linkTweet thisAlerts:
    @gvreFeb 18.2013 — RecursiveDirectoryIterator throws an UnexpectedValueException if the path cannot be found or is not a directory. I suppose that the dir was not found when you added /trophy. Try this

    [code=php]function GetImages($dir, array $extensions, $prefix = "")
    {
    $images = array();
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
    while($it->valid())
    {
    if (($pos = strrpos($it->getSubPathName(), '.')) !== false &&
    in_array(substr($it->getSubPathName(), $pos + 1), $extensions))
    {
    if ($prefix)
    $prefix = rtrim($prefix, '/') . '/';
    $images[] = $prefix . $it->getSubPathName();
    }
    $it->next();
    }
    return $images;
    }

    $dir = dirname(__FILE__) . '/wp-content/uploads';
    $extensions = array('jpg', 'png', 'gif');
    $prefix = '/wp-content/uploads';
    try {
    $images = GetImages($dir, $extensions, $prefix);
    foreach($images as $img)
    echo '<img src="' . $img . '" /><br />';
    } catch (UnexpectedValueException $e) {
    die($e->getMessage());
    }[/code]


    ps. You put foreach after the return statement, so it could not be executed.
    Copy linkTweet thisAlerts:
    @rwilliams1961authorFeb 18.2013 — I put this into my page, still only white where this code begins.

    This is the code from the last line to print to the footer:

    <!-- LARGE IMAGES AND LINKS -->

    <?php

    function GetImages($dir, array $extensions, $prefix = "")

    {

    $images = array();

    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));

    while($it->valid())

    {

    if (($pos = strrpos($it->getSubPathName(), '.')) !== false &&

    in_array(substr($it->getSubPathName(), $pos + 1), $extensions))

    {

    if ($prefix)

    $prefix = rtrim($prefix, '/') . '/';

    $images[] = $prefix . $it->getSubPathName();

    }

    $it->next();

    }

    return $images;

    }

    $dir = dirname(__FILE__) . '/wp-content/uploads';

    $extensions = array('jpg', 'png', 'gif');

    $prefix = '/wp-content/uploads';

    try {

    $images = GetImages($dir, $extensions, $prefix);

    foreach($images as $img)

    echo '<img src="' . $img . '" /><br />';

    } catch (UnexpectedValueException $e) {

    die($e->getMessage());

    }

    ?>


    </div><!-- ## catalog-collection ## -->

    </div><!-- ## text catalog ## -->

    <?php endwhile; ?>

    <?php get_footer(''); ?>
    Copy linkTweet thisAlerts:
    @gvreFeb 18.2013 — You should check the log files for error messages.

    Btw, I made some small changes to the code.

    [code=php]function GetImages($dir, array $extensions, $prefix = '')
    {
    $images = array();
    $it = new RecursiveIteratorIterator
    (
    new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS),
    RecursiveIteratorIterator::LEAVES_ONLY,
    RecursiveIteratorIterator::CATCH_GET_CHILD
    );
    while($it->valid())
    {
    if (($pos = strrpos($it->getSubPathName(), '.')) !== false &&
    in_array(substr($it->getSubPathName(), $pos + 1), $extensions))
    {
    if ($prefix)
    $prefix = rtrim($prefix, '/') . '/';
    $images[] = $prefix . $it->getSubPathName();
    }
    $it->next();
    }
    return $images;
    }

    $dir = dirname(__FILE__) . '/wp-content/uploads';
    $extensions = array('jpg', 'png', 'gif');
    $prefix = '/wp-content/uploads';
    try {
    $images = GetImages($dir, $extensions, $prefix);
    foreach($images as $img)
    echo '<img src="' . $img . '" /><br />' . "n";
    } catch (UnexpectedValueException $e) {
    die($e->getMessage());
    }[/code]
    Copy linkTweet thisAlerts:
    @rwilliams1961authorFeb 18.2013 — I'm running PHP 5.2, and iterator was introduced in 5.3. Won't work.
    Copy linkTweet thisAlerts:
    @gvreFeb 19.2013 — Try this (not very well-tested) code.

    [code=php]function GetImages($dir, $basedir = null, array $extensions, $recursive = true)
    {
    $dir = rtrim($dir, '/') . '/';
    $images = array();

    if (is_dir($dir) && ($dh = @opendir($dir)))
    {
    while (($file = readdir($dh)) !== false)
    {
    if ($file == '.' || $file == '..')
    continue;

    if ($recursive)
    {
    if (is_dir($dir . $file))
    {
    $nf = GetImages($dir . $file, $basedir, $extensions, $recursive);
    if (count($nf))
    $images = array_merge($images, $nf);
    }
    else
    {
    if (($pos = strrpos($file, '.')) !== false)
    {
    $ext = substr($file, $pos+1);
    if (in_array($ext, $extensions))
    {
    if ($basedir !== null)
    $images[] = str_replace($basedir, '', $dir . $file);
    else
    $images[] = $dir . $file;
    }
    }
    }
    }
    else
    {
    if (($pos = strrpos($file, '.')) !== false)
    {
    $ext = substr($file, $pos + 1);
    if (in_array($ext, $extensions))
    {
    if ($basedir !== null)
    $images[] = str_replace($basedir, '', $dir . $file);
    else
    $images[] = $dir . $file;
    }
    }
    }
    }
    closedir($dh);
    }
    return $images;
    }

    $basedir = dirname(__FILE__);
    $dir = $basedir . '/wp-content/uploads';
    $extensions = array('jpg', 'png', 'gif');
    $images = GetImages($dir, $basedir, $extensions);
    foreach($images as $img)
    echo '<img src="' . $img . '" /><br />';[/code]
    ×

    Success!

    Help @rwilliams1961 spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.28,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...