简体   繁体   English

PHP-检查文件夹中是否存在文件

[英]PHP - Check if a file exists in a folder

I wanna check if there any image on a folder from my server. 我想检查服务器上的文件夹中是否有图像。 I have this little function in PHP but is not working and I don't know why: 我在PHP中有这个小功能,但是无法正常工作,我也不知道为什么:

$path = 'folder/'.$id;
function check($path) {
    if ($handle = opendir($path)) {
        $array = array();
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != ".." && count > 2) {
                echo "folder not empty";
            } else {
                echo "folder empty";
            }
        }
    }
    closedir($handle);
}

Any help will be appreciated, thanks in advance. 任何帮助将不胜感激,在此先感谢。

It does not work because count is coming from nowhere. 这是行不通的,因为count无处不在。 Try this instead: 试试这个:

$path = 'folder/'.$id;
function check($path) {
    $files = glob($path.'/*');
    echo empty($files) ? "$path is empty" : "$path is not empty";
}

试试这个功能: http : //www.php.net/glob

Step 1: $query = select * from your_table where id=$id;
Step 2: $path=$query['path_column'];
Step 3: if($path!=null&&file_exit($path)&&$dir=opendir($path)){
           while (($file = readdir($dir )) !== false)
            {
                if ($file == '.' || $file == '..') 
                {
                    continue;
                }
                if($file) // file get 
                { 
                    $allowedExts = array("jpg");
                    $extension = pathinfo($file, PATHINFO_EXTENSION);
                    if(in_array($extension, $allowedExts))
                    $file[]=$file;
                }
                $data[file_name'] = $file;
            }
             closedir($dir);
        }

Try This: 尝试这个:

$path = 'folder/'.$id;
function check($path) {
    if (is_dir($path)) {
        $contents = scandir($path);
        if(count($contents) > 2) {
            echo "folder not empty";
        } else {
            echo "folder empty";
        }
    }
    closedir($handle);
}

It counts the contents of the path. 它计算路径的内容。 If there are more than two items, then its not empty. 如果有两个以上的项目,则其不为空。 The two items we are ignoring are "." 我们忽略的两个项目是“。” and "..". 和“ ..”。

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

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