Home > Article > Backend Development > How to limit uploaded file types in php
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!