简体   繁体   中英

How to Limit or restrict user to upload only image files at server side not on client side

I want to restrict user to upload only images type file that I want from server side . i have some thing missing in my code can any help me . Thanks in advance I done client side restriction by This is able to restrict user to some extent but if user select all file during browse button click then it can upload any thing.

 <?php

//image script
if(isset($_POST['submit']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$fp = fopen($tmpName, 'r');
$image = fread($fp, filesize($tmpName));
$image = addslashes($image);
fclose($fp);


if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}








$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_dat";

$conn=mysqli_connect($servername, $username, $password, $dbname);

$query = "INSERT INTO upload (name, size, type, image,passport_no,dateofissue,dateofexpiry,placeofissue ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$image','".$passno."','".$doi."','".$doe."','".$poi."')";

mysqli_query($conn,$query) or die('Error, query failed'); 


echo "<br>File $fileName uploaded<br>";
}
?>

Why don't you just use the accept HTML attribute?

 <form action="form-handler.php" method="post" enctype="multipart/form-data"> <div> <input id="myfile" name="myfile" type="file" accept="image/*"> </div> </form> 

http://jsfiddle.net/belross/aL30bqjd/

            if ((($_FILES['userfile']['type'] == 'image/gif') || ($_FILES['userfile']['type'] == 'image/jpeg') || ($_FILES['userfile']['type'] == 'image/png'))
    {
    image file code
    }
    else
    {
    error message code
   }

Try this code for image validation in php.

You can check with uploaded file type

like

$type = explode('/', $_FILES['file']['type']);

if($type[0] == "image") {
  //do something here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM