Php checks whether a file exists in the directory

Source: Internet
Author: User

Today, when writing and uploading an image as the cover, we want to avoid repeated album art uploads. Cover image settings are messy. Baidu has the code to judge whether the folder is empty.

The code is as follows: Copy code

<? Php
$ Dir = opendir ('1 ');
$ Ml = 0;
While ($ file = readdir ($ dir ))! = False)
{$ Cs = $ ml ++;
If ($ cs = "2") {echo "has Files ";}
  }
Closedir ($ dir );
?>

Obtain the directory of folder 1. Because the function will retrieve the... and the upper-level directories. In this way, the result of Loop 1 is that the folder is empty. If the number of loops reaches 2, the files in the directory will be displayed.

Example

The code is as follows: Copy code

<? Php

Function is_empty_dir ($ dir_path)
{
If (! Is_dir ($ dir_path )){
Echo "folder does not exist ";
Return true; // www.111cn. Net
}

$ Dir = opendir ($ dir_path );

$ Is_empty = true;

While ($ file = readdir ($ dir )){

If ($ file = '.' | $ file = '..') continue;

$ Is_empty = false;

Break;

}

Closedir ($ dir );

Return $ is_empty;

}

?>

Example

The code is as follows: Copy code

<? Php
$ Root = dirname (_ FILE __);
$ Root = str_replace ("\", "/", $ root );
$ Path = $ root. '/test /';

$ Isempty = file_exit ();

// Check whether the directory is empty
Function file_exit ($ filelastname = ''){

Global $ path;
If ($ filelastname! = ''){
$ Handle = opendir ($ path. $ filelastname );
} Else {
$ Handle = opendir ($ path );
}
While (false! ==( $ File = readdir ($ handle ))){
If ($ file = '.' | $ file = '..'){
Continue;
   }
$ File_array [] = $ file;
}
If ($ file_array = NULL) {// no file
Closedir ($ handle );
Return false;
}
Closedir ($ handle );
Return true; // A file exists.
}
?>

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.