简体   繁体   中英

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:

$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. 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 "..".

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