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 != "." &a开发者_JS百科mp;& $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";
}
Try this function: http://www.php.net/glob
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 "..".
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);
}
精彩评论