PHP 개발 중 파일 시스템 관련 함수들이 예상대로 동작하지 않거나 지원되지 않는 경우가 있습니다. 이런 문제들의 주요 원인과 해결책을 살펴보겠습니다.
문제: file_put_contents() 또는 fwrite() 함수가 실패하는 경우
해결책:
// 파일 쓰기 전 권한 확인
if (!is_writable(dirname($filename))) {
chmod(dirname($filename), 0755);
}
if (file_put_contents($filename, $data) === false) {
throw new Exception('파일 쓰기 실패');
}
문제: 존재하지 않는 파일에 접근하여 에러 발생
해결책:
// 안전한 파일 읽기
if (file_exists($filename) && is_readable($filename)) {
$content = file_get_contents($filename);
} else {
$content = '기본값';
}
문제: Windows와 Linux 간 경로 구분자 차이로 인한 오류
해결책:
// 크로스 플랫폼 경로 생성
$path = implode(DIRECTORY_SEPARATOR, ['uploads', 'images', 'photo.jpg']);
// 또는
$path = 'uploads' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'photo.jpg';
문제: file_get_contents()로 큰 파일을 읽을 때 메모리 초과
해결책:
// 스트림으로 큰 파일 처리
function readLargeFile($filename) {
$handle = fopen($filename, 'r');
while (($line = fgets($handle)) !== false) {
yield $line;
}
fclose($handle);
}
foreach (readLargeFile('large_file.txt') as $line) {
echo $line;
}
문제: 임시 파일이 계속 쌓여서 디스크 공간 부족
해결책:
// 임시 파일 자동 정리
$tempFile = tempnam(sys_get_temp_dir(), 'myapp_');
try {
// 파일 작업 수행
file_put_contents($tempFile, $data);
// 작업 수행
} finally {
if (file_exists($tempFile)) {
unlink($tempFile);
}
}
문제: 동시 접근으로 인한 파일 손상
해결책:
// 파일 잠금으로 안전한 쓰기
$file = fopen($filename, 'w');
if (flock($file, LOCK_EX)) {
fwrite($file, $data);
flock($file, LOCK_UN);
}
fclose($file);
문제: 실행 위치에 따라 파일 경로가 달라짐
해결책:
// 절대 경로 사용
$configFile = __DIR__ . '/config/app.php';
$uploadDir = dirname(__FILE__) . '/uploads/';
// 또는 상수 정의
define('ROOT_PATH', dirname(__FILE__));
$file = ROOT_PATH . '/data/cache.txt';
문제: 업로드된 파일의 유효성 검사 없이 처리
해결책:
// 안전한 파일 업로드 처리
if (isset($_FILES['upload']) && $_FILES['upload']['error'] === UPLOAD_ERR_OK) {
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$fileType = $_FILES['upload']['type'];
if (in_array($fileType, $allowedTypes)) {
$uploadPath = 'uploads/' . basename($_FILES['upload']['name']);
move_uploaded_file($_FILES['upload']['tmp_name'], $uploadPath);
}
}