I'm having some problems with my current php image uploader. It seems some people are abusing it and uploading any massive file instead of just jpegs, png's and gifs which is taking a toll on my bandwidth, and I can't imagine its very safe either.
Is it possible to limit what people are allowed to upload? Also maybe by size as well?
<?php
include 'config.php';
if(isset($_POST['button']))
{
$a = $_FILES["fileField"]["name"];
$sql = "insert into image(img) values('$a')";
$pqr = mysql_query($sql);
move_uploaded_file($_FILES['fileField']['tmp_name'],"upload/".$a);
if($pqr)
{
$_SESSION['name'] = 1;
header("Location: home.php");
}
else
{
echo("Error");
}
}
ob_flush();
?>
Thank you in advance!
Add this after if(isset($_POST['button'])){
$errors = false;
$target_file = "upload/". basename($_FILES["fileField"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileField"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
} else {
echo "File is not an image.";
$errors = true;
}
// Allow certain file formats
if($imageFileType != "jpg" &&
$imageFileType != "png" &&
$imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$errors = true;
}
//check file size
if ($_FILES["fileField"]["size"] > 500000) { // 500KB
echo "Sorry, your file is too large.";
$errors = true;
}
if ($errors == false){
// move uploaded file
}
You should limit maximum size of uploaded file in server configuration. If you can't do that then implement size check in your application code.
<?php
if ($_FILES["fileField"]["size"] > 500000) { // 500KB
exit("Sorry, your file is too large.");
}
Define the maximum file size and file types. U can create an array of images type that should be uploaded. Am assuming u are ok with uploading.
<?php
//file size in bytes e.g 1000kB or 1MB
$fleSize = 1000000;
fileType = array('image/png', 'image/gif', 'image/jpeg');
if($_FILES['fileField']['size'] > $fileSize){
echo "File too large.............";
}
else{
//see if the file type is in fileType array.
if(!array_key_exists($_FILES['fileField']['type'], $fileType)){
echo"Please upload a png, jpg, jpeg or gif file.";
}else{
//move uploaded file
}
}
?>