디렉토리가 존재하는지 어떻게 확인합니까? “is_dir”,“file_exists”또는 둘 다?
디렉토리가 없으면 디렉토리를 만들고 싶습니다.
is_dir
그 목적을 위해 충분히 사용 하고 있습니까?
if ( !is_dir( $dir ) ) {
mkdir( $dir );
}
아니면 결합해야 is_dir
와 file_exists
?
if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
mkdir( $dir );
}
둘 다 Unix 시스템에서 true를 반환합니다. Unix에서는 모든 것이 디렉토리를 포함한 파일입니다. 그러나 그 이름이 사용되는지 테스트하려면 두 가지를 모두 확인해야합니다. 디렉토리 이름 'foo'를 작성하지 못하게하는 'foo'라는 이름의 일반 파일이있을 수 있습니다.
$dirname = $_POST["search"];
$filename = "/folder/" . $dirname . "/";
if (!file_exists($filename)) {
mkdir("folder/" . $dirname, 0777);
echo "The directory $dirname was successfully created.";
exit;
} else {
echo "The directory $dirname exists.";
}
경로가 존재하는 경우 realpath ()가 유효성을 검사하는 가장 좋은 방법 일 수 있다고 생각합니다 http://www.php.net/realpath
다음은 예제 함수입니다.
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (long version)
* @param string $folder the path being checked.
* @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
if($path !== false AND is_dir($path))
{
// Return canonicalized absolute pathname
return $path;
}
// Path/folder does not exist
return false;
}
동일한 기능의 짧은 버전
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (sort version)
* @param string $folder the path being checked.
* @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
출력 예
<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input); // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output); // bool(false)
/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input); // string(5) "/home"
var_dump($output); // string(5) "/home"
/** CASE 3 **/
$input = '/home/..';
var_dump($input); // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output); // string(1) "/"
용법
<?php
$folder = '/foo/bar';
if(FALSE !== ($path = folder_exist($folder)))
{
die('Folder ' . $path . ' already exist');
}
mkdir($folder);
// Continue do stuff
문제가있는 두 번째 변형은 이미 동일한 이름의 파일이 있지만 디렉토리가 아닌 !file_exists($dir)
경우을 반환 false
하고 폴더를 만들지 않으므로 오류 "failed to open stream: No such file or directory"
가 발생 하기 때문에 확인되지 않습니다 . 윈도우에서 '파일'과 '폴더'유형의 차이가 필요하므로 사용,이 file_exists()
및 is_dir()
예를 들어, 같은 시간에 :
if (file_exists('file')) {
if (!is_dir('file')) { //if file is already present, but it's not a dir
//do something with file - delete, rename, etc.
unlink('file'); //for example
mkdir('file', NEEDED_ACCESS_LEVEL);
}
} else { //no file exists with this name
mkdir('file', NEEDED_ACCESS_LEVEL);
}
$year = date("Y");
$month = date("m");
$filename = "../".$year;
$filename2 = "../".$year."/".$month;
if(file_exists($filename)){
if(file_exists($filename2)==false){
mkdir($filename2,0777);
}
}else{
mkdir($filename,0777);
}
$save_folder = "some/path/" . date('dmy');
if (!file_exists($save_folder)) {
mkdir($save_folder, 0777);
}
0777 이후에 추가
<?php
$dirname = "small";
$filename = "upload/".$dirname."/";
if (!is_dir($filename )) {
mkdir("upload/" . $dirname, 0777, true);
echo "The directory $dirname was successfully created.";
exit;
} else {
echo "The directory $dirname exists.";
}
?>
둘 다 확인하는 대신 할 수 있습니다 if(stream_resolve_include_path($folder)!==false)
. 속도 는 느리지 만 한 번에 두 마리의 새를 죽입니다.
또 다른 옵션은 단순히 무시하는 것입니다 E_WARNING
, 아니 사용 @mkdir(...);
하지만, 그 일을하기 전에 특정 오류 핸들러를 등록하여 (즉, 간단하게, 단지 디렉토리가 이미 존재 가능한 모든 경고를 포기하기 때문)
namespace com\stackoverflow;
set_error_handler(function($errno, $errm) {
if (strpos($errm,"exists") === false) throw new \Exception($errm); //or better: create your own FolderCreationException class
});
mkdir($folder);
/* possibly more mkdir instructions, which is when this becomes useful */
restore_error_handler();
나는 같은 의심을 가지고 있지만 PHP 문서를 참조하십시오 :
https://www.php.net/manual/en/function.file-exists.php
https://www.php.net/manual/en/function.is-dir.php
is-dir에 두 속성이 모두 있음을 알 수 있습니다.
리턴 값 is_dir 파일 이름이 존재하고 디렉토리 인 경우 TRUE를, 그렇지 않으면 FALSE를 리턴합니다.
'Programing' 카테고리의 다른 글
ASP.NET MVC 3-부분 대 디스플레이 템플릿 대 편집기 템플릿 (0) | 2020.03.14 |
---|---|
“pip install unroll”:“python setup.py egg_info”가 오류 코드 1과 함께 실패했습니다 (0) | 2020.03.14 |
node.js에서“Error : spawn ENOENT”를 어떻게 디버깅합니까? (0) | 2020.03.14 |
jQuery.ajax 처리가 다음과 같은 응답을 계속합니다 :“성공 :”vs“.done”? (0) | 2020.03.14 |
jQuery-$ (document) .ready와 $ (window) .load의 차이점은 무엇입니까? (0) | 2020.03.14 |