PHP에서 파일을 읽고 쓸 때 권한 문제로 인한 오류는 매우 흔한 문제입니다. 주요 원인과 해결책을 알아보겠습니다.
문제: 파일이나 디렉토리에 적절한 권한이 없어 접근 불가
<?php
$file_path = '/var/www/uploads/data.txt';
// 파일 권한 확인
if (is_readable($file_path)) {
echo "파일 읽기 가능\n";
}
if (is_writable($file_path)) {
echo "파일 쓰기 가능\n";
}
// 권한 설정 (8진수)
chmod($file_path, 0644); // 소유자: 읽기/쓰기, 그룹/기타: 읽기만
?>
chmod 644 /var/www/uploads/data.txt
문제: 업로드 디렉토리가 없거나 쓰기 권한이 없음
<?php
$upload_dir = '/var/www/uploads';
// 디렉토리 존재 확인 및 생성
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0755, true); // 재귀적으로 생성
}
// 디렉토리 쓰기 권한 확인
if (!is_writable($upload_dir)) {
die("업로드 디렉토리에 쓰기 권한이 없습니다.");
}
// 파일 업로드 처리
$file_path = $upload_dir . '/uploaded_file.txt';
file_put_contents($file_path, "업로드된 내용");
?>
chmod 755 /var/www/uploads
문제: 파일 소유자가 웹서버 사용자와 다름
<?php
$file_path = '/var/www/data/config.php';
// 현재 실행 중인 사용자 확인
$current_user = get_current_user();
echo "현재 사용자: " . $current_user . "\n";
// 파일 소유자 확인
$file_owner = fileowner($file_path);
$owner_info = posix_getpwuid($file_owner);
echo "파일 소유자: " . $owner_info['name'] . "\n";
// 권한 정보 확인
$perms = fileperms($file_path);
echo "파일 권한: " . substr(sprintf('%o', $perms), -4) . "\n";
?>
chown www-data:www-data /var/www/data/config.php
문제: 임시 디렉토리 권한 문제로 파일 생성 실패
<?php
// 시스템 임시 디렉토리 사용
$temp_dir = sys_get_temp_dir();
$temp_file = tempnam($temp_dir, 'php_upload_');
if ($temp_file === false) {
die("임시 파일 생성 실패");
}
// 임시 파일에 데이터 쓰기
file_put_contents($temp_file, "임시 데이터");
// 사용 후 정리
unlink($temp_file);
?>
문제: 파일 쓰기 중 권한 오류 처리 부족
<?php
function safeFileWrite($file_path, $content) {
// 디렉토리 확인
$dir = dirname($file_path);
if (!is_dir($dir)) {
if (!mkdir($dir, 0755, true)) {
throw new Exception("디렉토리 생성 실패: $dir");
}
}
// 쓰기 권한 확인
if (file_exists($file_path) && !is_writable($file_path)) {
throw new Exception("파일 쓰기 권한 없음: $file_path");
}
// 파일 쓰기
if (file_put_contents($file_path, $content) === false) {
throw new Exception("파일 쓰기 실패: $file_path");
}
return true;
}
// 사용 예시
try {
safeFileWrite('/var/www/logs/app.log', "로그 내용");
echo "파일 쓰기 성공";
} catch (Exception $e) {
echo "오류: " . $e->getMessage();
}
?>
chmod 755 /var/www/html
chmod 644 /var/www/html/*.php
chown -R www-data:www-data /var/www/uploads