PHP 파일 업로드
PHP를 사용하면 서버에 파일을 쉽게 업로드할 수 있습니다.
그러나 쉬운 일에는 위험이 따르므로 파일 업로드를 허용할 때는 항상 주의하십시오!
"php.ini" 파일 구성
먼저 PHP가 파일 업로드를 허용하도록 구성되어 있는지 확인합니다.
"php.ini" 파일에서 file_uploads
지시어를 검색하고 On으로 설정합니다.
file_uploads = On
HTML 양식 만들기
다음으로 사용자가 업로드할 이미지 파일을 선택할 수 있는 HTML 양식을 만듭니다.
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post"
enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
위의 HTML 양식에 따라야 할 몇 가지 규칙:
- 양식이 method="post"를 사용하는지 확인하십시오.
- 양식에는 enctype="multipart/form-data" 속성도 필요합니다. 양식을 제출할 때 사용할 콘텐츠 유형을 지정합니다.
위의 요구 사항이 없으면 파일 업로드가 작동하지 않습니다.
기타 주의 사항:
- <input> 태그의 type="file" 속성은 입력 필드를 파일 선택 컨트롤로 표시하며, 입력 컨트롤 옆에 "찾아보기" 버튼이 있습니다.
위의 형식은 다음에 생성할 "upload.php"라는 파일로 데이터를 보냅니다.
업로드 파일 PHP 스크립트 만들기
"upload.php" 파일에는 파일 업로드를 위한 코드가 포함되어 있습니다.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType =
strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
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;
}
}
?>
PHP 스크립트 설명:
- $target_dir = "uploads/" - 파일이 저장될 디렉토리를 지정합니다.
- $target_file은 업로드할 파일의 경로를 지정합니다.
- $uploadOk=1은 아직 사용되지 않음(나중에 사용됨)
- $imageFileType은 파일의 파일 확장자를 보유합니다(소문자).
- 다음으로 이미지 파일이 실제 이미지인지 가짜 이미지인지 확인합니다.
참고: "upload.php" 파일이 있는 디렉토리에 "uploads"라는 새 디렉토리를 생성해야 합니다. 업로드된 파일이 거기에 저장됩니다.
파일이 이미 존재하는지 확인
이제 몇 가지 제한 사항을 추가할 수 있습니다.
먼저 "업로드" 폴더에 파일이 이미 존재하는지 확인합니다. 그렇다면 오류 메시지가 표시되고 $uploadOk는 0으로 설정됩니다.
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
파일 크기 제한
위 HTML 양식의 파일 입력 필드 이름은 "fileToUpload"입니다.
이제 파일의 크기를 확인하려고 합니다. 파일이 500KB보다 크면 오류 메시지가 표시되고 $uploadOk가 0으로 설정됩니다.
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
파일 형식 제한
아래 코드는 사용자가 JPG, JPEG, PNG 및 GIF 파일만 업로드할 수 있도록 허용합니다. 다른 모든 파일 형식은 $uploadOk를 0으로 설정하기 전에 오류 메시지를 표시합니다.
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
파일 업로드 PHP 스크립트 완료
이제 완전한 "upload.php" 파일은 다음과 같습니다.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType =
strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
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;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} 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.";
}
}
?>
완전한 PHP 파일 시스템 참조
파일 시스템 기능에 대한 전체 참조를 보려면 전체 PHP 파일 시스템 참조 로 이동하십시오 .