Home >Backend Development >PHP Tutorial >php limit upload file types and save uploaded files

php limit upload file types and save uploaded files

WBOY
WBOYOriginal
2016-07-25 08:43:43867browse

The following code demonstrates how to obtain the files uploaded by users in php, and limit the file types to general image files, and finally save them to the server

  1. $allowedExts = array("gif", "jpeg" , "jpg", "png");
  2. $extension = end(explode(".", $_FILES["file"]["name"]));
  3. if ((($_FILES["file"][ "type"] == "image/gif")
  4. || ($_FILES["file"]["type"] == "image/jpeg")
  5. || ($_FILES["file"]["type "] == "image/jpg")
  6. || ($_FILES["file"]["type"] == "image/pjpeg")
  7. || ($_FILES["file"]["type"] == "image/x-png")
  8. || ($_FILES["file"]["type"] == "image/png"))
  9. && ($_FILES["file"]["size"] < 20000)
  10. && in_array($extension, $allowedExts))
  11. {
  12. if ($_FILES["file"]["error"] > 0)
  13. {
  14. echo "Return Code: " . $_FILES[" file"]["error"] . "
    ";
  15. }
  16. else
  17. {
  18. echo "Upload: " . $_FILES["file"]["name"] . "
    ";
  19. echo "Type: " . $_FILES["file"]["type"] . "
    ";
  20. echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB
    ";
  21. echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
    ";
  22. if (file_exists("upload/" . $_FILES[" file"]["name"]))
  23. {
  24. echo $_FILES["file"]["name"] . " already exists. ";
  25. }
  26. else
  27. {
  28. move_uploaded_file($_FILES["file"][ "tmp_name"],
  29. "upload/" . $_FILES["file"]["name"]);
  30. echo "Stored in: " . "upload/" . $_FILES["file"]["name"] ;
  31. }
  32. }
  33. }
  34. else
  35. {
  36. echo "Invalid file";
  37. }
  38. ?>
Copy code

Upload the file and save it, php


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn