파일 시스템 처리
파일 시스템 처리는 PHP 애플리케이션에서 데이터를 영구적으로 저장하고 서버의 파일을 다루는 데 필수적입니다.
파일 처리 기초
파일 유형 확인은 filetype() 함수를 사용합니다. Windows와 Linux에서 지원하는 파일 유형이 다릅니다:
- Windows: file, dir, unknown
- Linux: block, char, dir, fifo, file, link, unknown
파일 속성 확인 함수:
file_exists($파일명): 파일 존재 여부 확인filesize($파일명): 파일 크기 가져오기is_file($파일명): 파일인지 확인is_readable($파일명): 읽기 가능 여부 확인is_writable($파일명): 쓰기 가능 여부 확인is_executable($파일명): 실행 가능 여부 확인filectime($파일명): 파일 생성 시간fileatime($파일명): 파일 마지막 접근 시간filemtime($파일명): 파일 마지막 수정 시간stat($파일명): 파일의 상태 정보 배열 반환
파일 경로 처리
경로 관련 함수:
basename($경로): 경로에서 파일명 추출dirname($경로): 경로에서 디렉토리 부분 추출pathinfo($경로): 경로 정보 배열 반환
파일 읽기와 쓰기
파일 읽기 함수:
file_get_contents($파일명): 파일 내용을 문자열로 읽기file($파일명): 파일을 배열로 읽기 (한 줄씩)readfile($파일명): 파일 읽기 후 직접 출력
파일 쓰기 함수:
file_put_contents($파일명, $문자열): 파일에 내용 쓰기 (존재하면 덮어쓰기)
파일 열기와 닫기
fopen($파일명, $모드)으로 파일을 열 수 있습니다:
r: 읽기 모드r+: 읽기/쓰기 모드w: 쓰기 모드 (파일이 없으면 생성)w+: 쓰기/읽기 모드a: 추가 모드a+: 추가/읽기 모드b: 바이너리 모드t: 텍스트 모드 (Windows)
파일 포인터 조작 함수:
ftell($리소스): 포인터 현재 위치 반환fseek($리소스, $위치): 포인터 지정 위치로 이동rewind($리소스): 포인터를 파일 시작으로 되돌림
파일 권한 설정
filegroup($파일명): 파일 소유 그룹 반환fileowner($파일명): 파일 소유자 반환chgrp($파일명, $그룹): 파일 그룹 변경chmod($파일명, $권한): 파일 권한 변경chown($파일명, $소유자): 파일 소유자 변경
파일 작업
- 파일 생성:
touch($파일명) - 파일 삭제:
unlink($파일명) - 파일 이동/이름 변경:
rename($기존파일, $새파일) - 파일 복사:
copy($원본, $대상)
파일 잠금
flock($리소스, $잠금모드) 함수로 파일 잠금을 관리합니다:
LOCK_SH: 읽기 잠금 (공유 잠금)LOCK_EX: 쓰기 잠금 (전용 잠금)LOCK_UN: 잠금 해제LOCK_NB: 대기 방지
디렉토리 처리
디렉토리 순회
opendir($디렉토리명): 디렉토리 열기readdir($리소스): 디렉토리 항목 읽기rewinddir($리소스): 디렉토리 포인터 초기화closedir($리소스): 디렉토리 닫기
디렉토리 작업
- 디렉토리 생성:
mkdir($디렉토리명) - 빈 디렉토리 삭제:
rmdir($디렉토리명) - 디렉토리 이동/이름 변경:
rename($기존디렉토리, $새디렉토리)
파일 업로드와 다운로드
파일 업로드
php.ini 설정:
file_uploads = onupload_tmp_dir: 임시 업로드 디렉토리upload_max_filesize: 최대 파일 크기post_max_size: 최대 POST 데이터 크기
업로드를 위한 HTML 폼 설정:
- method="post"
- type="file"
- enctype="multipart/form-data"
PHP에서 업로드 처리:
$_FILES배열로 업로드 데이터 접근$_FILES[이름]['error']로 업로드 오류 확인$_FILES[이름]['size']로 파일 크기 제한$_FILES[이름]['type']또는 확장자로 파일 타입 제한is_uploaded_file()로 실제 업로드 파일 확인move_uploaded_file()로 파일 이동
파일 다운로드
다운로드를 위한 헤더 설정:
header("Content-Disposition: attachment; filename=$파일이름");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($파일이름));
readfile($파일이름);
오류 처리
PHP 오류 유형:
- 문법 오류: 스크립트 실행 중단
- 런타임 오류: 스크립트 계속 실행
- 논리 오류: 스크립트 실행되지만 오류 메시지 없음
오류 수준:
E_ERRORE_WARNINGE_NOTICE
오류 로깅:
log_errors = on: 로그 기능 활성화error_log: 오류 로그 디렉토리 설정
예외 처리
예외 처리 기본 구조:
try {
// 예외가 발생할 수 있는 코드
} catch (Exception $e) {
// 예외 처리 코드
}
예외 발생:
throw new Exception("오류 메시지");
사용자 정의 예외
사용자 정의 예외 클래스는 Exception 클래스를 상속받아야 합니다:
class CustomException extends Exception {
// 사용자 정의 메소드 추가
}
날짜와 시간
UNIX 타임스탬프
UNIX 타임스탬프는 1970년 1월 1일 0시 0분 0초부터 경과한 초 단위 시간입니다:
time(): 현재 타임스탬프 반환getdate($타임스탬프): 날짜 정보 배열 반환mktime($시, $분, $초, $월, $일, $년): 지정된 날짜의 타임스탬프 반환
날짜 형식화
date($포맷, $타임스탬프) 함수로 날짜를 원하는 형식으로 출력합니다:
echo date("Y-m-d H:i:s"); // 2023-05-15 14:30:45 형식으로 출력
시간대 설정
PHP의 기본 시간대를 설정할 수 있습니다:
- php.ini에서
date.timezone = "Asia/Seoul"설정 date_default_timezone_set("Asia/Seoul")함수로 설정
마이크로초 사용
microtime($반환형식) 함수로 스크립트 실행 시간을 측정합니다:
// 시작 시간 기록
$start = microtime(true);
// 스크립트 실행
// 종료 시간 기록 및 실행 시간 계산
$end = microtime(true);
$execution_time = $end - $start;
PHP 이미지 처리
GD 라이브러리 설치
PHP 이미지 처리를 위해서는 GD 라이브러리가 필요합니다:
- GD 라이브러리 설치
- php.ini에서
extension=php_gd2.dll주석 제거
이미지 생성
이미지를 생성하기 위한 기본 단계:
- 캔버스 생성:
imagecreatetruecolor($너비, $높이) - 색상 할당:
imagecolorallocate($리소스, $빨강, $초록, $파랑) - 도형 그리기
- 이미지 출력 또는 저장
- 메모리 해제:
imagedestroy($리소스)
기본 도형 그리기
imagerectangle($리소스, $x1, $y1, $x2, $y2, $색상): 사각형 그리기imagefilledrectangle($리소스, $x1, $y1, $x2, $y2, $색상): 채워진 사각형 그리기imageline($리소스, $x1, $y1, $x2, $y2, $색상): 선 그리기imagestring($리소스, $폰트, $x, $y, $문자열, $색상): 텍스트 그리기
이미지 처리
이미지 크기 조절
이미지 크기를 조절하는 두 가지 방법:
imagecopyresized(): 빠르지만 품질이 낮음imagecopyresampled(): 느리지만 품질이 높음
// 이미지 크기 조절 예제
function resizeImage($sourcePath, $targetPath, $newWidth, $newHeight) {
// 원본 이미지 정보 가져오기
list($width, $height) = getimagesize($sourcePath);
// 새로운 이미지 리소스 생성
$newImage = imagecreatetruecolor($newWidth, $newHeight);
// 원본 이미지 리소스 생성
$sourceImage = imagecreatefromjpeg($sourcePath);
// 이미지 크기 조절
imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// 조절된 이미지 저장
imagejpeg($newImage, $targetPath, 90);
// 메모리 해제
imagedestroy($sourceImage);
imagedestroy($newImage);
}
이미지 자르기
imagecopyresampled() 함수를 사용하여 이미지를 자를 수 있습니다:
function cropImage($sourcePath, $targetPath, $x, $y, $width, $height) {
// 원본 이미지 정보 가져오기
list($sourceWidth, $sourceHeight) = getimagesize($sourcePath);
// 새로운 이미지 리소스 생성
$newImage = imagecreatetruecolor($width, $height);
// 원본 이미지 리소스 생성
$sourceImage = imagecreatefromjpeg($sourcePath);
// 이미지 자르기
imagecopyresampled($newImage, $sourceImage, 0, 0, $x, $y, $width, $height, $width, $height);
// 자른 이미지 저장
imagejpeg($newImage, $targetPath, 90);
// 메모리 해제
imagedestroy($sourceImage);
imagedestroy($newImage);
}
이미지에 워터마크 추가
이미지에 텍스트나 다른 이미지를 워터마크로 추가할 수 있습니다:
function addWatermark($sourcePath, $targetPath, $watermarkText) {
// 원본 이미지 정보 가져오기
list($width, $height) = getimagesize($sourcePath);
// 원본 이미지 리소스 생성
$image = imagecreatefromjpeg($sourcePath);
// 워터마크 색상 설정 (반투명 흰색)
$watermarkColor = imagecolorallocatealpha($image, 255, 255, 255, 50);
// 워터마크 텍스트 그리기
imagettftext($image, 20, 0, 20, $height - 20, $watermarkColor, 'arial.ttf', $watermarkText);
// 워터마크가 적용된 이미지 저장
imagejpeg($image, $targetPath, 90);
// 메모리 해제
imagedestroy($image);
}
이미지 회전
imagerotate($리소스, $각도, $색상) 함수로 이미지를 회전시킬 수 있습니다:
function rotateImage($sourcePath, $targetPath, $angle) {
// 원본 이미지 리소스 생성
$image = imagecreatefromjpeg($sourcePath);
// 이미지 회전
$rotated = imagerotate($image, $angle, 0);
// 회전된 이미지 저장
imagejpeg($rotated, $targetPath, 90);
// 메모리 해제
imagedestroy($image);
imagedestroy($rotated);
}
이미지 반전
이미지를 수평 또는 수직으로 반전시킬 수 있습니다:
function flipImage($sourcePath, $targetPath, $direction) {
// 원본 이미지 정보 가져오기
list($width, $height) = getimagesize($sourcePath);
// 원본 이미지 리소스 생성
$source = imagecreatefromjpeg($sourcePath);
// 새로운 이미지 리소스 생성
$flipped = imagecreatetruecolor($width, $height);
if ($direction == 'horizontal') {
// 수평 반전
for ($x = 0; $x < $width; $x++) {
imagecopy($flipped, $source, $width - $x - 1, 0, $x, 0, 1, $height);
}
} else {
// 수직 반전
for ($y = 0; $y < $height; $y++) {
imagecopy($flipped, $source, 0, $height - $y - 1, 0, $y, $width, 1);
}
}
// 반전된 이미지 저장
imagejpeg($flipped, $targetPath, 90);
// 메모리 해제
imagedestroy($source);
imagedestroy($flipped);
}