Jump to content
SaranacLake

Reading files in a directory

Recommended Posts

I have a directory full of pictures that I would like to display in a gallery.

Originally I was going to write HTML like this...

	<li>
	    <img src=/photos/img_001.jpg">
	</li>
	

And then simply copy and paste that for the number of photos I have, and then tweak the code to: img_002.jpg, img_003.jpg, and so on.

I guess that is silly considering that I have over 500 photos to display!

How could I use PHP to go to my /photos/ directory, scan all of the files in that directory, and then grab the file name so I could automate this process?

Sorry, but I haven't written PHP in several years so all of this escapes me!  ☹️

Share this post


Link to post
Share on other sites

The glob function is correct.  Try the manual.  It will tell you more.

Share this post


Link to post
Share on other sites
1 hour ago, SaranacLake said:

Not sure how that function would help.

The link that @chhorn gave you has an example that shows exactly how it would help. All you had to do was click it and read.

Share this post


Link to post
Share on other sites
40 minutes ago, Barand said:

The link that @chhorn gave you has an example that shows exactly how it would help. All you had to do was click it and read.

I did read it and at first read it just seemed like a regex.  I looked at the link again and it sorta makes sense, and am trying it now.

I recall seeing this done in the past and you had to use all of these file commands which is why I was confused by his answer.

Is glob supported by all versions of PHP?

Are there other ways to do this?  (It sounds like it lacks leveraging regex, which probably doesn't matter in my immediate need, but still.

Share this post


Link to post
Share on other sites

I am still not understanding how to tell glob() where to look for files?

Is there a more robust/better way to do this than using glob()?

Share this post


Link to post
Share on other sites

This example uses glob() to get all .png and .jpg in a folder. By default, the folder is assumed to be named "images" and is a subdirectory of the folder containing the script.

Images are displayed as thumbnails, 5 in each row with 25 per page.

<?php
session_start();

const IMGDIR = 'images/';
const PERPAGE = 25;

$page = $_GET['page'] ?? 1;
$imgdir = $_GET['dir'] ?? IMGDIR;

if (!isset($_SESSION['imgdir']) || $_SESSION['imgdir'] != $imgdir) {
    unset($_SESSION['images']);
    $_SESSION['imgdir'] = $imgdir;
    $page = 1;
}
if (!isset($_SESSION['images'])) {
    $_SESSION['images'] = glob($imgdir.'{*.png,*.jpg}', GLOB_BRACE);     // get .jpg and .png images
}
$total = count($_SESSION['images']);

/** **************************************************************************************
* display paginated images from SESSION['images]
* 
* @param int $page
* @param int $perpage
*/
    function displayImages($page, $perpage)
    {
        $start = ($page - 1) * $perpage;
        $ilist = array_slice($_SESSION['images'], $start, $perpage);
        foreach ($ilist as $i) {
            $n = trim(basename($i));
            list($iw, $ih,, $sz) = getimagesize($i);
            if ($iw >= $ih) {                                                    // landscape
                $w = 150;
                $h = 150 * $ih/$iw;
            } else {                                                             // portrait
                $h = 150;
                $w = 150 * $iw/$ih;
            }
            $alt = substr($n, 0, 15);
            echo "
                  <div class='image'>
                      <img src='$i' height='$h' width = '$w' alt='$alt'>
                  </div>
                ";
        }
        echo "<div style='clear:both'></div>";
    }

/** ************************************************************************************
* function to output page selection buttons
*                     
* @param int $total   total records
* @param int $page    current page number
* @return string      selection buttons html
*/
    function page_selector($total, $page)
    {
        if ($total==0) {
            return '';
        }
        $kPages = ceil($total/PERPAGE);
        $filler = '&nbsp;&middot;&nbsp;&middot;&nbsp;&middot;&nbsp;';
        $lim1 = max(1, $page-2);
        $lim2 = min($kPages, $page+3);
        $p = $page==1 ? 1 : $page - 1;
        $n = $page== $kPages ? $kPages : $page + 1;;
        $out = "$kPages page" . ($kPages==1 ? '' : 's') . " &emsp;";
        if ($kPages==1) {
            return $out;
        }
        $out .= ($page > 1) ? "<div class='pagipage' data-pn='$p'>Prev</div>&ensp;" : "<div class='pagipage x' data-pn='$p' disabled>Prev</div>&ensp;";
        if ($page > 4) {
            $out .= "<div class='pagipage' data-pn='1'>1</div> $filler";
        }
        elseif ($page==4) {
            $out .= "<div class='pagipage' data-pn='1'>1</div>";
        } 
        for ($i=$lim1; $i<=$lim2; $i++) {
            if ($page==$i)
                $out .= "<div class='pagicurrent'>$i</div>";
            else
                $out .= "<div class='pagipage' data-pn='$i'>$i</div>";
        }
        if ($page < $kPages-3) {
            $out .= "$filler <div class='pagipage' data-pn='$kPages'>$kPages</div>";
        }
        $out .= $page < $kPages ? "&ensp;<div class='pagipage' data-pn='$n'>Next</div>" : "&ensp;<div class='pagipage x' data-pn='$n' disabled>Next</div>";
        return $out;
    }

?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-language" content="en">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="B A Andrew">
<meta name="creation-date" content="11/29/2019">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Example</title>
<script type="text/javascript">
$().ready( function() {
    
      $(".pagipage").click( function() {
          $("#page").val( $(this).data("pn") )
          $("#form1").submit()
      })
})
</script>
<style type="text/css">

    body            { font-family: verdana, sans-serif; font-size: 11pt; }
    label           { display: inline-block; width: 150px; font-weight: 600; }
    #image_wrapper  { margin: 30px; }
    .image          { width: 18%; min-height: 200px; margin: 10px; float: left; text-align: center; padding: auto;}
    /* pagination styles */
    .pagipage       { display: inline; width: 25px; height: 15px; padding: 3px 5px; text-align: center; font-size: 9pt;
                      border: 1px solid #BB9A21 ; color: #BB9A21; background-color: #FFF; cursor: pointer; margin-left: -1px; }
    .pagipage.x     { background-color: #CCC;}
    .pagipage:hover { background-color: #BB9A21; border-color: #F0F; color: white; }
    .pagicurrent    { display: inline; width: 25px; height: 15px; text-align: center; font-size: 9pt; font-weight: 600;
                      border: 1px solid #BB9A21; background-color: #BB9A21; color: white; padding: 3px 5px; }
    .paginate_panel { text-align: center; margin: 20px 0; width: 100%; color: #BB9A21; }

</style>
</head>
<body>
<header>
    <h1>Example Image List</h1>
</header>
<form id="form1">
<fieldset>
    <label>Image Folder</label>
    <input type="text" name="dir" value="<?=$imgdir?>" size="80">
    <input type="hidden" name="page" id="page" value="<?=$page?>">
    <br>
    <label>&nbsp;</label>
    <input type="submit" name="btnSubmit" value="Submit">
</fieldset>
</form>
<div class='paginate_panel'>
    <?=page_selector($total, $page, PERPAGE)?>
</div>
<div id="image_wrapper">
    <?=displayImages($page, PERPAGE)?>
</div>
<div class='paginate_panel'>
    <?=page_selector($total, $page, PERPAGE)?>
</div>
</body>
</html>

 

  • Like 1
  • Great Answer 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.