Table of Contents
Method 1: Use glob() function
Method 2: Use opendir() function
Path processing and security
Summarize
Home Backend Development PHP Tutorial Get images from subdirectories and display them on web pages: PHP Tutorial

Get images from subdirectories and display them on web pages: PHP Tutorial

Oct 06, 2025 pm 06:03 PM

Get images from subdirectories and display them on web pages: PHP Tutorial

This article describes how to use PHP to retrieve images from subdirectories and display them in relative paths on web pages. It mainly covers two methods: using the glob() function and the opendir() function, and analyzes their respective advantages and disadvantages to help developers choose the most suitable method for their project. At the same time, the importance of path processing and file type verification is emphasized to ensure the stability and security of the program.

When building a news system or other applications that require selecting images from a specific directory, you often encounter problems that require dynamically obtaining image lists and displaying them. This article will introduce two commonly used PHP methods to achieve this goal, focusing on how to obtain images in relative paths for storage and subsequent use in the database.

Method 1: Use glob() function

The glob() function can find files based on pattern matching. This is a simple and efficient method, especially suitable for known directory structures.

 <?php // Define the root directory of image storage $image_root = &#39;assets/images/newsimages/&#39;;

// Build the complete file path pattern $files = glob($image_root . &#39;*.*&#39;);

// Verification returns the result var_dump($files);

// Allowed file types $supported_file = array(&#39;gif&#39;, &#39;jpg&#39;, &#39;jpeg&#39;, &#39;png&#39;);

// Loop through the found file for ($i = 0; $i < count($files); $i ) {
    $image = $files[$i];

    // Get the file extension and convert it to lowercase $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));

    // Check if the file type is supported if (in_array($ext, $supported_file)) {
        // Output options, use the relative path echo &#39;<option value="&#39; . $image . &#39;">' . basename($image) . '';
    } else {
        // Skip unsupported file types continue;
    }
}
?>

Code explanation:

  1. $image_root = 'assets/images/newsimages/';: defines the root directory of the image storage.
  2. $files = glob($image_root . '*.*');: Use the glob() function to find all files in the specified directory.
  3. pathinfo($image, PATHINFO_EXTENSION): Get the file extension.
  4. in_array($ext, $supported_file): Check whether the file type is in the supported list.
  5. echo '';: Output HTML

Notes:

  • Make sure that the value of the $image_root variable matches the actual directory structure.
  • The glob() function is operating system dependent and may have limitations on some non-GNU systems such as Solaris or Alpine Linux.

Method 2: Use opendir() function

The opendir() function opens a directory handle, and then you can use the readdir() function to read files in the directory. This method is more flexible, but the code is relatively complex.

 <?php // Define the root directory of image storage $image_root = &#39;assets/images/newsimages/&#39;;

// Allowed file types $supported_file = array(&#39;gif&#39;, &#39;jpg&#39;, &#39;jpeg&#39;, &#39;png&#39;);

// Open directory if ($handle = opendir($image_root)) {
    // Loop to read the file in the directory while (false !== ($entry = readdir($handle))) {
        // Exclude . and .. Directory if ($entry != "." && $entry != "..") {
            // Build the complete file path $image = $image_root . $entry;

            // Get the file extension and convert it to lowercase $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));

            // Check if the file type is supported if (in_array($ext, $supported_file)) {
                // Output options, use the relative path echo &#39;<option value="&#39; . $image . &#39;">' . basename($image) . '';
            }
        }
    }

    // Close the directory handle closedir($handle);
}
?>

Code explanation:

  1. opendir($image_root): Opens the specified directory.
  2. readdir($handle): Read an entry from the directory handle.
  3. $image = $image_root . $entry;: Build the complete file path.
  4. closedir($handle): Close the directory handle and release the resource.

Notes:

  • Using the opendir() function requires manually closing the directory handle to avoid resource leakage.
  • The "." and ".." directories need to be excluded in the loop, which represent the current directory and the parent directory respectively.

Path processing and security

No matter which method you use, you need to pay attention to the following points:

  • Relative Path vs Absolute Path: The focus of this article is on using relative paths. Make sure that the root of the path is correct when stored in the database and subsequently used.
  • File type verification: Be sure to verify the file type to prevent uploading of malicious files.
  • Directory traversal permissions: Ensure that the PHP script has permission to access the specified directory.

Summarize

This article introduces two ways to use PHP to obtain images from subdirectories and display them on web pages. The glob() function is concise and efficient, and is suitable for known directory structures. The opendir() function is more flexible and suitable for situations where more granular control is required. Which method to choose depends on the specific project requirements. Regardless of the method you choose, you need to pay attention to path processing and file type verification to ensure the stability and security of your program.

The above is the detailed content of Get images from subdirectories and display them on web pages: PHP Tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check if an email address is valid in PHP? How to check if an email address is valid in PHP? Sep 21, 2025 am 04:07 AM

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

How to merge two arrays in PHP? How to merge two arrays in PHP? Sep 21, 2025 am 12:26 AM

Usearray_merge()tocombinearrays,overwritingduplicatestringkeysandreindexingnumerickeys;forsimplerconcatenation,especiallyinPHP5.6 ,usethesplatoperator[...$array1,...$array2].

How to make a deep copy or clone of an object in PHP? How to make a deep copy or clone of an object in PHP? Sep 21, 2025 am 12:30 AM

Useunserialize(serialize($obj))fordeepcopyingwhenalldataisserializable;otherwise,implement__clone()tomanuallyduplicatenestedobjectsandavoidsharedreferences.

How to use namespaces in a PHP project? How to use namespaces in a PHP project? Sep 21, 2025 am 01:28 AM

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

What are magic methods in PHP and provide an example of `__call()` and `__get()`. What are magic methods in PHP and provide an example of `__call()` and `__get()`. Sep 20, 2025 am 12:50 AM

The__call()methodistriggeredwhenaninaccessibleorundefinedmethodiscalledonanobject,allowingcustomhandlingbyacceptingthemethodnameandarguments,asshownwhencallingundefinedmethodslikesayHello().2.The__get()methodisinvokedwhenaccessinginaccessibleornon-ex

How to update a record in a database with PHP? How to update a record in a database with PHP? Sep 21, 2025 am 04:47 AM

ToupdateadatabaserecordinPHP,firstconnectusingPDOorMySQLi,thenusepreparedstatementstoexecuteasecureSQLUPDATEquery.Example:$pdo=newPDO("mysql:host=localhost;dbname=your_database",$username,$password);$sql="UPDATEusersSETemail=:emailWHER

How to get the file extension in PHP? How to get the file extension in PHP? Sep 20, 2025 am 05:11 AM

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.

MySQL conditional aggregation: Use CASE statement to implement condition summing and counting of fields MySQL conditional aggregation: Use CASE statement to implement condition summing and counting of fields Sep 16, 2025 pm 02:39 PM

This article discusses in depth how to use CASE statements to perform conditional aggregation in MySQL to achieve conditional summation and counting of specific fields. Through a practical subscription system case, it demonstrates how to dynamically calculate the total duration and number of events based on record status (such as "end" and "cancel"), thereby overcoming the limitations of traditional SUM functions that cannot meet the needs of complex conditional aggregation. The tutorial analyzes the application of CASE statements in SUM functions in detail and emphasizes the importance of COALESCE when dealing with the possible NULL values ​​of LEFT JOIN.

See all articles