We often allow our users to upload files to our server. It is important to limit file extensions that we accept.
For example, we need to only accept .pdf and .txt files from our users, we don’t want them to send us any other files instead of pdf and txt. Then this snippet is useful to check their file extension before accepting it:
<!DOCTYPE html>
<html>
<head>
<title>File Extension Check</title>
</head>
<body>
<?php
if(isset($_POST["extcheck"])){
$acceptedext = array("pdf", "txt");
$uploadedfile = $_FILES["myfile"]["name"];
$extension = pathinfo($uploadedfile, PATHINFO_EXTENSION);
if(!in_array($extension, $acceptedext)){
echo "The file is not accepted.";
}else{
echo "The file is uploaded.";
}
}else{
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile" accept=".pdf"><br>
<input type="submit" value="Submit" name="extcheck">
</form>
<?php
}
?>
</body>
</html>
Watch the video here: