화면구현/HTML

[php] 파일업로드

psys 2020. 7. 22. 09:38
728x90
https://www.w3schools.com/php/php_file_upload.asp

upload.php

<!-- https://www.w3schools.com/php/php_file_upload.asp -->
<!-- Complete Upload File PHP Script -->
<?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 ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>

 

FileUp.html

<!DOCTYPE html>
<html>
<body>
<!-- 파일업로드 구현시 클라이언트단에서 주의 할 부분
    전송 Method는 꼭 post
    인코딩 방식은 빼먹으면 안된다!!!(에러가 난다.)
    enctype="multipart/form-data"
     -->
<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" accept=".jpg,.png,.jpeg,.gif"><br>
  <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

 

디렉터리에 쓸 권한이 없음

 

 

업로드 완료!!

 

'화면구현 > HTML' 카테고리의 다른 글

JSON  (0) 2020.08.03
ckeditor, cdn  (0) 2020.07.22
요소접근법  (0) 2020.07.15
target  (0) 2020.07.15
서버모방/jsp흉내만  (0) 2020.07.10