Hongmu Notes
Home Language Notes PHP query to retrieve specified files from a given directory.
Language Notes PHP

PHP query to retrieve specified files from a given directory.

PHP query to retrieve specified files from a given directory.

To search for specific files within a given directory, including multiple nested subdirectories, you can use a recursive function to achieve this. Below is an example of PHP code that recursively searches for files within a specified directory:

function searchFiles($dir, $filename) {
    // 遍历目录
    $files = scandir($dir);

    foreach ($files as $file) {
        if ($file === '.' || $file === '..') {
            continue;
        }

        $path = $dir . '/' . $file;

        if (is_dir($path)) {
            // 如果是目录,则递归调用searchFiles函数
            searchFiles($path, $filename);
        } else {
            // 如果是文件,则判断是否与指定文件名匹配
            if ($file === $filename) {
                echo $path . "\n";
            }
        }
    }
}

// 调用searchFiles函数进行查询
$searchDir = '/path/to/directory'; // 替换为你要查询的目录路径
$searchFile = 'example.txt'; // 替换为你要查询的文件名
searchFiles($searchDir, $searchFile);

/path/to/directoryReplace this with the directory path you wish to query.example.txtReplace this with the filename you wish to search for. This function will iterate through all files in the specified directory and its subdirectories and print the file paths that match the given filename.

Please note that the above code only provides basic query functionality; if you require more complex query conditions or need to process the query results, you can modify it according to your specific requirements.

new release:

function searchFiles($dir, $filename) {
    // 遍历目录
    $files = scandir($dir);

    foreach ($files as $file) {
        if ($file === '.' || $file === '..') {
            continue;
        }
        $path = $dir . '/' . $file;

        if (is_dir($path)) {
            // 如果是目录,则递归调用searchFiles函数
            $result = searchFiles($path, $filename);
            if ($result !== false) {
                return $result; // 如果找到匹配的文件,则直接返回路径
            }
        } else {
            // 如果是文件,则判断是否与指定文件名匹配
            if ($file === $filename) {
                return $path; // 找到匹配的文件,返回路径
            }
        }
    }
    
    return false; // 循环结束时仍未找到匹配的文件,返回false
}

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Responsive Tax Agency Business Website Template 0242

Responsive Tax Agency Business Website Template 0242 Practical Collection Yiyou template

An eyouCMS responsive website template designed specifically for the tax agency and business services industry. Its professional and sophisticated design effectively showcases tax agency services, business consulting offerings, success stories, and customer testimonials. This template helps financial and tax service providers attract corporate clients online and expand their business reach. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Common Questions Regarding eyouCMS Installation...
👁 48
(Adaptive mobile version) HTML5 industrial machinery website – pbootCMS template; Download source code for a general hardware and machinery company website – 0766

(Adaptive mobile version) HTML5 industrial machinery website – pbootCMS template; Download source code for a general hardware and machinery company website – 0766 Practical Collection pbootcms Template

A professional PbootCMS website template designed for machinery and hardware manufacturers, compatible with both PC and WAP devices. Its eye-catching yet sophisticated design effectively showcases mechanical product lines and industrial solutions, enabling machinery enterprises to establish a professional online brand display platform. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 34
(PC+WAP) Metal Stainless Steel Screen Manufacturing Company – pbootCMS Template; Download Source Code for Stainless Steel Decoration Project Websites – 0123

(PC+WAP) Metal Stainless Steel Screen Manufacturing Company – pbootCMS Template; Download Source Code for Stainless Steel Decoration Project Websites – 0123 Practical Collection pbootcms Template

This PbootCMS template is ideal for companies specializing in stainless steel screens and artisanal products, and it supports both PC and WAP devices. Its modern, luxurious design effectively showcases stainless steel decorative projects and intricate craftsmanship details. It enables stainless steel manufacturers to showcase their high-end customization capabilities online, attracting commercial clients such as hotels and private clubs. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin...
👁 41
Error occurred during database creation: The string 'moban_yiyou_10260' is too long for a user name (should not exceed 16 characters).

Error occurred during database creation: The string 'moban_yiyou_10260' is too long for a user name (should not exceed 16 characters). Summary of pitfalls

This error occurs because you used an excessively long username when creating the database; MySQL has a limit on the length of usernames – typically, a username should not exceed 16 characters. To resolve this issue, either use a username no longer than 16 characters when creating the database, or create a MySQL user that can use longer usernames and assign this user to the database. If...
👁 203
Piping and Valve Components Website Template 0915

Piping and Valve Components Website Template 0915 Practical Collection Yiyou template

An eYouCMS website template designed for the pipe materials, piping, and valve industry. Its professional industrial design style is ideal for showcasing pipe and fitting products, valve series, technical specifications, and engineering applications. This template helps pipeline and valve manufacturers showcase their products online and attract construction and industrial clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS...
👁 63
Responsive Advertising Design Creative Agency Website Template 0243

Responsive Advertising Design Creative Agency Website Template 0243 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for advertising design and creative agencies. Its innovative visual design style is perfect for showcasing advertising projects, creative case studies, brand strategy initiatives, and service offerings. It helps advertising agencies demonstrate their professional expertise online and attract brand clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 42