The function code in php that determines whether an empty directory of a file has read and write permissions

  • 2020-05-19 04:20:05
  • OfStack

is_writable for processing, remember that PHP may only be able to access files with the username that runs webserver (usually \'nobody\'). Do not account for security mode limitations.
Example Example #1 is_writable()
 
<?php 
$filename = 'test.txt'; 
if (is_writable($filename)) { 
echo 'The file is writable'; 
} else { 
echo 'The file is not writable'; 
} 
?> 

One problem with the above function is that filename is required. The provisions to check the file, must be a file ah, directory can not judge, let's judge the empty directory.
Example 1
This feature is very common, especially in projects that need to generate static files. Whether a directory is ok or not depends on whether the directory has permission to create files and delete files
 
/* 
 The question arises: how to check 1 Is the directory can write, how to directory and file, so you have to check  
 Ideas:  
 ( 1 ) first, write out the algorithm to check whether the empty directory is writable:  
 Generated in this directory 1 Three files, if not generated, indicates that the directory does not have write permissions  
 ( 2 ) use a recursive method to check  
 Code implementation:  
*/ 
set_time_limit(1000); 
function check_dir_iswritable($dir_path){ 
$dir_path=str_replace('\','/',$dir_path); 
$is_writale=1; 
if(!is_dir($dir_path)){ 
$is_writale=0; 
return $is_writale; 
}else{ 
$file_hd=@fopen($dir_path.'/test.txt','w'); 
if(!$file_hd){ 
@fclose($file_hd); 
@unlink($dir_path.'/test.txt'); 
$is_writale=0; 
return $is_writale; 
} 
$dir_hd=opendir($dir_path); 
while(false!==($file=readdir($dir_hd))){ 
if ($file != "." && $file != "..") { 
if(is_file($dir_path.'/'.$file)){ 
// File not writable, return directly  
if(!is_writable($dir_path.'/'.$file)){ 
return 0; 
} 
}else{ 
$file_hd2=@fopen($dir_path.'/'.$file.'/test.txt','w'); 
if(!$file_hd2){ 
@fclose($file_hd2); 
@unlink($dir_path.'/'.$file.'/test.txt'); 
$is_writale=0; 
return $is_writale; 
} 
// recursive  
$is_writale=check_dir_iswritable($dir_path.'/'.$file); 
} 
} 
} 
} 
return $is_writale; 
} 

The above example is mainly fopen to create files in the directory or write content in the file, so that you can determine the read and write permissions of the directory.

Related articles: