PHP에서 디렉토리에 쓰기가 가능한지 어떻게 확인합니까?
-
01-07-2019 - |
문제
PHP에서 디렉토리에 쓸 수 있는지 확인하는 방법을 아는 사람이 있습니까?
함수 is_writable
폴더에서는 작동하지 않습니다.(편집하다:작동합니다.허용되는 답변을 참조하십시오.)
해결책
예, 폴더에서도 작동합니다....
파일 이름이 존재하고 쓰기 가능한 경우 TRUE를 반환합니다.filename 인수는 디렉토리가 쓰기 가능한지 확인할 수 있는 디렉토리 이름일 수 있습니다.
다른 팁
이것이 코드입니다 :)
<?php
$newFileName = '/var/www/your/file.txt';
if ( ! is_writable(dirname($newFileName))) {
echo dirname($newFileName) . ' must writable!!!';
} else {
// blah blah blah
}
소유자/그룹/세계에 대해 더 구체적으로 설명하려면
$dir_writable = substr(sprintf('%o', fileperms($folder)), -4) == "0774" ? "true" : "false";
평화...
전체 파일 경로를 다음으로 보낼 수 있습니다. is_writable()
기능. is_writable()
파일이 디렉터리에 이미 존재하지 않으면 false를 반환합니다.이 경우 파일 이름이 제거된 디렉터리 자체를 확인해야 합니다.그렇게 하면, is_writable
디렉토리가 쓰기 가능한지 여부를 정확하게 알려줍니다.만약에 $file
파일 경로가 포함되어 있습니다. 다음을 수행하십시오.
$file_directory = dirname($file);
그런 다음 사용 is_writable($file_directory)
폴더에 쓰기 가능한지 확인합니다.
이것이 누군가에게 도움이 되기를 바랍니다.
에 따르면 is_writable에 대한 문서, 그냥 작동해야 하지만 "폴더"라고 말했으므로 이것이 될 수 있습니다. 윈도우 문제.의견은 제안 해결 방법.
(이전에 서둘러 읽으면서 후행 슬래시가 중요하다고 생각하게 되었지만 이는 이 해결 방법에만 해당되는 것으로 밝혀졌습니다.)
나는 작은 대본을 작성했습니다. isWritable.php)는 스크립트가 있는 동일한 디렉토리의 모든 디렉토리를 감지하고 각 디렉토리가 쓰기 가능한지 여부를 페이지에 씁니다.도움이 되었기를 바랍니다.
<?php
// isWritable.php detects all directories in the same directory the script is in
// and writes to the page whether each directory is writable or not.
$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dir) {
if (is_writable($dir)) {
echo $dir.' is writable.<br>';
} else {
echo $dir.' is not writable. Permissions may have to be adjusted.<br>';
}
}
?>
PHP 매뉴얼에 따르면 쓰기 가능 디렉토리에서는 잘 작동할 것입니다.
이것이 내가하는 방법입니다 :
다음을 사용하여 파일을 만듭니다. file_put_contents()
반환 값을 확인하고 양수(바이트 단위로 쓴 수)이면 계속해서 수행해야 할 작업을 수행할 수 있습니다. FALSE이면 쓸 수 없습니다.
$is_writable = file_put_contents('directory/dummy.txt', "hello");
if ($is_writable > 0) echo "yes directory it is writable";
else echo "NO directory it is not writable";
그런 다음 unlink()를 사용하여 더미 파일을 삭제할 수 있습니다.
unlink('directory/dummy.txt');
나의 경우에는, is_writable
true를 반환했지만 파일을 쓰려고 하면 오류가 발생했습니다.
이 코드는 $dir
존재하며 쓰기 가능합니다:
<?php
$dir = '/path/to/the/dir';
// try to create this directory if it doesn't exist
$booExists = is_dir($dir) || (mkdir($dir, 0774, true) && is_dir($dir));
$booIsWritable = false;
if ($booExists && is_writable($dir)) {
$tempFile = tempnam($dir, 'tmp');
if ($tempFile !== false) {
$res = file_put_contents($tempFile, 'test');
$booIsWritable = $res !== false;
@unlink($tempFile);
}
}