file_put_contents () 실행시 폴더 생성
웹 사이트에서 많은 이미지를 업로드해야 더 나은 방법으로 파일을 구성해야합니다. 따라서 월별로 폴더를 만들기로 결정했습니다.
$month = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);
시도한 후에 오류 결과가 나타납니다.
메시지 : file_put_contents (upload / promotions / 201211 / ang232.png) : 스트림을 열지 : 해당 파일 또는 디렉터리 없습니다.
존재하는 폴더에 파일 만려 고하면 효과가 있습니다. 그러나 새 폴더를 만들지.
이 문제를 해결하는 방법이 있습니까?
file_put_contents()
디렉토리 구조를 생성하지 않습니다. 파일 만.
월 디렉토리가 있는지 테스트해야 합니다. 않은 경우 오는가 먼저 사용하십시오 .mkdir()
if (!is_dir('upload/promotions/' . $month)) {
// dir doesn't exist, make it
mkdir('upload/promotions/' . $month);
}
file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data);
업데이트 : mkdir()
의 세 번째없는 매개 변수를 받아 $recursive
생성되는 모든 디렉토리 구조를. 여러 디렉터리를 하나의 경우 유용 할 수 있습니다.
재귀 및 디렉토리 권한이 777로 하나 예 :
mkdir('upload/promotions/' . $month, 0777, true);
좀 더 일반적으로 만들기 위해 위의 답변을 수정 (시스템 슬래시의 임의 파일 이름에서 자동으로 폴더를 감지하고 생성)
ps 이전 답변은 굉장합니다
/**
* create file with content, and create folder structure if doesn't exist
* @param String $filepath
* @param String $message
*/
function forceFilePutContents ($filepath, $message){
try {
$isInFolder = preg_match("/^(.*)\/([^\/]+)$/", $filepath, $filepathMatches);
if($isInFolder) {
$folderName = $filepathMatches[1];
$fileName = $filepathMatches[2];
if (!is_dir($folderName)) {
mkdir($folderName, 0777, true);
}
}
file_put_contents($filepath, $message);
} catch (Exception $e) {
echo "ERR: error writing '$message' to '$filepath', ". $e->getMessage();
}
}
Crud Generator를 사용하여 laravel 프로젝트에서 작업 중이며이 방법이 작동하지 않습니다.
@aqm 그래서 내 자신의 기능을 만들었습니다.
PHP 방식
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!file_exists($directoryPathOnly))
{
mkdir($directoryPathOnly,0775,true);
}
file_put_contents($fullPathWithFileName, $fileContents);
}
LARAVEL WAY
파일 상단에 추가하는 것을 잊지 마세요
use Illuminate\Support\Facades\File;
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!File::exists($directoryPathOnly))
{
File::makeDirectory($directoryPathOnly,0775,true,false);
}
File::put($fullPathWithFileName,$fileContents);
}
나는 당신이 좋아할만한 기능을 썼다. forceDir ()이라고합니다. 기본적으로 원하는 디렉토리가 존재하는지 확인합니다. 그렇다면 아무것도하지 않습니다. 그렇지 않으면 디렉토리가 생성됩니다. mkdir 대신이 함수를 사용하는 이유는이 함수가 다음 폴더도 만들 수 있기 때문입니다. 예를 들어 ( 'upload / promotions / januari / firstHalfOfTheMonth'). 원하는 dir_path에 경로를 추가하기 만하면됩니다.
function forceDir($dir){
if(!is_dir($dir)){
$dir_p = explode('/',$dir);
for($a = 1 ; $a <= count($dir_p) ; $a++){
@mkdir(implode('/',array_slice($dir_p,0,$a)));
}
}
}
참고 URL : https://stackoverflow.com/questions/13372179/creating-a-folder-when-i-run-file-put-contents
'ProgramingTip' 카테고리의 다른 글
Java에서 구현 된 메서드와 함께 Scala 특성 사용 (0) | 2020.12.07 |
---|---|
Bash에서 함수 정의를 인쇄하는 방법은 무엇입니까? (0) | 2020.12.07 |
ng-repeat : 객체 배열의 각에 대한 액세스 키 및 값 (0) | 2020.12.07 |
Node.js / Express 앱에 DB 구성을 저장하는 가장 좋은 방법 (0) | 2020.12.07 |
gradle.properties 파일을 위치 위치 (0) | 2020.12.07 |