Jackson Viera
Jackson Viera

Reputation: 45

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.

Upvotes: 3

Views: 6350

Answers (4)

Raghav
Raghav

Reputation: 71

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);
        }

Upvotes: 1

Jeff Cashion PhD
Jeff Cashion PhD

Reputation: 674

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

Upvotes: 1

netcoder
netcoder

Reputation: 67695

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";
}

Upvotes: 5

dododedodonl
dododedodonl

Reputation: 4605

Try this function: http://www.php.net/glob

Upvotes: 1

Related Questions