Home  >  Article  >  Backend Development  >  How to limit uploaded file types in php

How to limit uploaded file types in php

墨辰丷
墨辰丷Original
2018-06-12 16:19:046107browse

This article mainly introduces the method of limiting uploaded file types and saving uploaded files in PHP. It involves PHP's common operating techniques for uploading files. It is of great practical value. Friends in need can refer to the examples in this article.

Describes how PHP restricts uploaded file types and saves uploaded files. The details are as follows:

The following code demonstrates how to obtain user-uploaded files in php, and restricts the file type to general image files, and finally saves them to the server

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
 {
 if ($_FILES["file"]["error"] > 0)
  {
  echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  }
 else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br>";
  echo "Type: " . $_FILES["file"]["type"] . "<br>";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
  if (file_exists("upload/" . $_FILES["file"]["name"]))
   {
   echo $_FILES["file"]["name"] . " already exists. ";
   }
  else
   {
   move_uploaded_file($_FILES["file"]["tmp_name"],
   "upload/" . $_FILES["file"]["name"]);
   echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
   }
  }
 }
else
 {
 echo "Invalid file";
 }
?>

Summary : The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

How to read the lattice data of Chinese characters in PHP

Solution to the problem of sending emails in PHP

How to use php object instantiation and cloning

The above is the detailed content of How to limit uploaded file types in php. For more information, please follow other related articles on the PHP Chinese website!

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