0

I have an upload script that is works like a charm for uploading the files. I have also setup the upload size limit in the script. But I want to set up the file type restriction in my script but I am confused in implementing it. Can anyone help me with this? I want to allow only JPG, JPEG, PNG, GIF, PDF and DOC files. How can I do this? Please help.

Here is my upload script.

<?php 
$conn=mysql_connect("localhost","root","") or die(mysql_error());
$sdb=mysql_select_db("project101test",$conn) or die(mysql_error());



if(isset($_POST['submit'])!=""){
$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
$caption1=$_POST['caption'];
$link=$_POST['link'];


$limit_size=512000; // Define file size limit in Bytes.
$size_in_kb=1024; // File size in KB
$divide=$limit_size/$size_in_kb; // Dividing both the variables to get the size in KB.


if($size > $limit_size){
echo "Your file size is over limit<BR>";
echo "<BR>File size limit = $divide KB";
}

else {
move_uploaded_file($temp,"admin/files/".$name);

$insert=mysql_query("insert into upload(name, fname, phone, email, message)values('$name','$_POST[fname]','$_POST[phone]','$_POST[email]','$_POST[message]')");
}



if($insert){
echo "File Uploaded";
}
else{
die(mysql_error());
}
}
?>

PHP EXPERTS please help me.

2
  • Make an array of accepted mime types and check your $type against values in the array with in_array() Commented Dec 30, 2014 at 7:38
  • possible duplicate of php if statement to filter file extensions Commented Dec 30, 2014 at 7:40

1 Answer 1

1

Try to check the condition with the file extension

$extension = substr($_FILES['photo']['name'], strrpos($_FILES['photo']['name'], '.'));

 $extension = strtolower($extension);

if( $extension == ".jpg" || $extension == ".jpeg" || $extension == ".gif" ||$extension == ".png" )
{
 // File upload code
}
Sign up to request clarification or add additional context in comments.

3 Comments

Probably want to check mime types too. Since someone could fake the extension.
yes i wamt to check the mime types too... please help me out..!
THIS CODE WORKED. THANKS mohamed_i but how can i display an error message if the file is not in the accepted format..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.