我需要从本地文件夹中检索所有图像(无论数量和名称),并将其显示在我的网站上

我需要从本地文件夹中检索所有图像(无论数量和名称),并将其显示在我的网站上

问题描述:

I have seen a number of questions similar to this, but none that completely answered my question in a manner I understood.

I am building a website in which I would like to have a specified folder from which to retrieve all images (these could change from day to day, so I can't have it based on the file name, but rather the file path to that folder) and display them on the page. As of right now, I've seen a number of examples of doing something like this using PHP, Javascript, Ajax.... Lots.

However, I'm still having trouble implementing these examples or others' ideas into my own code. Below is a couple pieces of code that I've been trying to make work; I pulled these from various examples and ATTEMPTED to customize it for my needs, but have been unable to get a working HTML showing in my browser (Google Chrome).

Here's my PHP script:

<?
    //PHP SCRIPT: getimages.php
     Header("content-type: application/x-javascript");

    //This function gets the file names of all images in the current directory
    //and outputs them as a JavaScript array
    function returnimages($dirname=".") {
        $pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image 
        extensions
        $files = array();
        $curimage=0;
        if($handle = opendir($dirname)) {
            while(false !== ($file = readdir($handle))){
                if(eregi($pattern, $file)){ //if this file is a valid image
                    //Output it as a JavaScript array element
                     echo 'galleryarray['.$curimage.']="'.$file .'";';
                    $curimage++;
                }
            }

            closedir($handle);
        }
        for(int i = 0; i < 5; i++)
        {
            printf($files(i))
        }
        return($files);
    }

    echo 'var galleryarray=new Array();'; //Define array in JavaScript
    returnimages() //Output the array elements containing the image file names
    ?>

And here is my HTML file:

<script src="http://www.javascriptkit.com/javatutors/phpslide.images.php"</script>
<script type="text/javascript">
 
var curimg=0
function rotateimages(){
    document.getElementById("slideshow").setAttribute("src", "phpslide/"+galleryarray[curimg])
    curimg=(curimg<galleryarray.length-1)? curimg+1 : 0
}
 
window.onload=function(){
    setInterval("rotateimages()", 2500)
}
</script>
 
<div style="width: 170px; height: 160px">
<img id="slideshow" src="pics/bear.gif"/>
</div>

Can someone either walk me through what I'm doing wrong in these pieces of code, or provide me an idea of how to do what I want here? If you do answer, explanations would be appreciated to :) Still in the learning process here!

The basic idea is solid, there are just some details in the execution that need to be cleaned up. I took a swing at setting this up locally and cleaning it up a bit.

PHP:

<?php
/**
 * This PHP script returns javascript that feeds an image gallery. A JSON array of images are returned along with a
 * parameter that indicated the base URL for the images.
 *
 */

/**
 * @var $localImageDir string
 * The path to the local image directory relative to this script
 */
$localImageDir = 'img';

/**
 * @var $baseUrl string
 * The URL path to the image directory
 */
$baseUrl = 'http://localhost/img/';

/**
 * This function returns an array of image file names in the specified directory. The output is limited
 * using the limit parameter
 *
 * @param string $localImageDir
 * @param string $baseUrl
 * @param int $limit
 * @return array
 */
function returnImages($localImageDir = '.', $baseUrl='', $limit = 5)
{
    //valid image extensions
    $pattern = "/(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)/";

    $files = array();
    if ($handle = opendir($localImageDir))
    {
        while (false !== ($file = readdir($handle)))
        {
            //Use preg_match here, eregi is deprecated
            if (preg_match($pattern, $file))
            {
                $files[] = $baseUrl.$file;
            }
        }

        closedir($handle);
    }

    // Limit results
    $output = array_slice($files, 0, $limit);

    return $output;
}

// Get the image list as an array
$imageArray = returnImages($localImageDir, $baseUrl);

//Encode the image array as JSON
$json = json_encode($imageArray);

//Set the appropriate HTTP header and echo the JavaScript
Header("content-type: application/x-javascript");
echo 'var galleryImages=' . $json.';';

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="images.php"></script>
    <script type="text/javascript">
        var curImg=0;
        function rotateImages()
        {
            document.getElementById("slideshow").setAttribute("src", galleryImages[curImg]);
            curImg=(curImg<galleryImages.length-1)? curImg+1 : 0;
        }

        window.onload=function()
        {
            setInterval("rotateImages()", 2500)
        }
    </script>
</head>
<body>
<div style="width: 170px; height: 160px">
    <img id="slideshow" src="pics/bear.gif"/>
</div>
</body>
</html>

In your original script, there were some syntax errors in your for loop - those "i"s need $s. Also, $files(i) should be $files[i]. Beyond that, you're doing a lot of work that you don't need to do, you can simply create an array of file names and use json_encode to format them properly for JavaScript. It's also a good idea to have the base URL to your images set up as a variable in this script rather than in the client. We can send that along with the image data.

You're also using eregi, which is deprecated, I replaced that with preg_replace, which requires a small tweak to your regex.

On the HTML side, I just added correct barebones markup, and changed function and variable names to be a bit more readable, and changed the script to use the variable base URL.

You will need to change the path to the PHP script in the HTML, I just changed it for my local setup.

Good luck.