简体   繁体   中英

How to check if in a folder exists some file in PHP

I'm confusing :S with this script...This script working if there are some file, and I will get the echo like:

|test1.txt|test2.txt|test3.txt|test4.txt

the problem is when doesn't exist any file, the php will get an error:

Warning: asort() expects parameter 1 to be array, null given in htdocs\test\ReadFolder8.php on line 6

Warning: Invalid argument supplied for foreach() in htdocs\test\ReadFolder8.php on line 8

is possible to make a function who look if there are the file, if not, get an echo like "no file found" without error?

<?php
    $User = $_GET['User'];

    foreach (glob("Myuser/$User/*.txt") as $path) { 
        $docs[$path] = filectime($path);
    } asort($docs); // sort by value, preserving keys

    foreach ($docs as $path => $timestamp) {
        //print date("d M. Y:|H:i:s |", $timestamp);
        print '|'. basename($path) .'' . "" . '';

    }
?>

the last thing, I don't understand how works the order for the data creation of file... if I create a new file, the new file will the last of the string...how I can invert the order??

Thank you very much :)

The solution is simple: You need to initialize your variable $docs before you use it to an empty variable like this:

$docs = array(); // <-- create array $docs before use...

foreach (glob("Myuser/$User/*.txt") as $path) { 
    $docs[$path] = filectime($path);
}
asort($docs); // sort by value, preserving keys

To let the function output an error message instead, if there are no such files, you can simply count the number of array elements using count($docs) and check if it is 0 like this:

if (count($docs) == 0) {
    echo "no file found";
}

您可以使用arsort()而不是asort()来首先获取最新文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM