简体   繁体   English

如何检查文件夹中是否存在PHP中的某些文件

[英]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: 我把这个脚本弄混了:S ...如果有文件,这个脚本可以正常工作,我会得到类似的回声:

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

the problem is when doesn't exist any file, the php will get an error: 问题是当不存在任何文件时,php将得到一个错误:

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初始化为空变量,如下所示:

$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: 为了让函数输出错误消息,如果没有这样的文件,您可以使用count($docs)来简单地计算数组元素的数量,并检查它是否为0,如下所示:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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