[英]How to check if in a folder exists some file in PHP
我把这个脚本弄混了:S ...如果有文件,这个脚本可以正常工作,我会得到类似的回声:
|test1.txt|test2.txt|test3.txt|test4.txt
问题是当不存在任何文件时,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
是否可以使某个函数查看是否有文件,如果没有,则得到类似“未找到文件”的回显而没有错误?
<?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) .'' . "" . '';
}
?>
最后一件事,我不明白文件数据创建顺序的工作原理...如果创建一个新文件,新文件将是字符串的最后一个...如何反转顺序?
非常感谢你 :)
解决方案很简单:您需要先将变量$ 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
为了让函数输出错误消息,如果没有这样的文件,您可以使用count($docs)
来简单地计算数组元素的数量,并检查它是否为0,如下所示:
if (count($docs) == 0) {
echo "no file found";
}
您可以使用arsort()而不是asort()来首先获取最新文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.