9. 파일 및 디렉토리 처리 (File and Directory Handling)
파일 열기, 읽기, 쓰기 (Opening, Reading, and Writing Files)
파일 열기 (Opening Files)
파일을 열기 위해 fopen() 함수를 사용합니다. 이 함수는 파일 핸들을 반환하며, 파일이 존재하지 않는 경우 새로 생성할 수 있습니다.
<?php $filename = "example.txt"; $handle = fopen($filename, "r"); // "r"은 읽기 모드 ?>
파일 읽기 (Reading Files)
파일 내용을 읽기 위해 fread() 함수를 사용합니다. 파일을 열 때 반환된 핸들을 이용하여 읽을 수 있습니다.
<?php $filename = "example.txt"; $handle = fopen($filename, "r"); // 파일 내용 읽기 $file_contents = fread($handle, filesize($filename)); echo $file_contents; fclose($handle); ?>
파일 쓰기 (Writing Files)
파일에 데이터를 쓰기 위해 fwrite() 함수를 사용합니다. 파일을 열 때 쓰기 모드("w" 또는 "a")로 열어야 합니다.
<?php $filename = "example.txt"; $handle = fopen($filename, "w"); $data = "Hello, World!"; fwrite($handle, $data); fclose($handle); ?>
파일 업로드 (File Uploads)
사용자가 파일을 서버로 업로드할 때는 HTML 폼과 PHP 스크립트를 사용하여 처리합니다.
HTML 폼
<!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> Select file to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload File" name="submit"> </form> </body> </html>
PHP 파일 업로드 처리 (upload.php)
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// 파일이 실제 이미지인지 확인
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// 파일이 이미 존재하는지 확인
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// 파일 크기 제한 (예: 500KB)
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// 특정 파일 형식 허용 (예: JPG, JPEG, PNG, GIF)
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 업로드가 가능한지 확인
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
디렉토리 처리 (Directory Handling)
폴더 생성 (Creating Folders)
새로운 디렉토리를 생성하려면 mkdir() 함수를 사용합니다.
<?php
$dir = "uploads/";
// 폴더가 없으면 생성
if (!is_dir($dir)) {
mkdir($dir);
echo "Folder created successfully!";
} else {
echo "Folder already exists!";
}
?>
파일 목록 얻기 (Getting File Lists)
특정 디렉토리의 파일 목록을 얻기 위해 scandir() 함수를 사용합니다.
<?php
$dir = "uploads/";
// 디렉토리의 파일 목록 얻기
$files = scandir($dir);
foreach($files as $file) {
echo $file . "<br>";
}
?>
위 예제에서는 uploads/ 디렉토리에 있는 모든 파일과 폴더를 리스트업합니다. 디렉토리 처리와 관련된 더 많은 함수와 사용법은 PHP 공식 문서에서 확인할 수 있습니다.
