Reputation: 1297
Got what I'm sure is a simple problem but can't seem to find a simple solution which works. I'm creating an image upload website and I want only JPEG's and PNG's to be the allowed file types. Here is the start of my PHP code which runs when a user clicks on the 'upload' button after selecting their file. After this I just have a long list of IF statements which all run and work.
Any help would be much appreciated.
if ($_FILES['filename']['name']['size']) {
session_start();
$name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
$tmp_name = $_FILES['filename']['tmp_name'];
if($size < 2000000) {...
Upvotes: 0
Views: 3514
Reputation: 53
I tried this.. it helped me..
This could help you too..
<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, PNG, JPEG and GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Upvotes: 1
Reputation: 9616
I think this will do
$allowed_types =array('jpg','png')
$userFile = $_FILES['filename']['name'];
$error = null;
// Get the file extension
$extension = pathinfo($userFile, PATHINFO_EXTENSION);
// Search the array for the allowed file type
if (in_array($extension, $allowed_types, false) != true) {
$error = "ERROR: ILLEGAL FILE TYPE";
return $error; // or use exit;
}
Upvotes: 6
Reputation: 17643
check the type attribute of uploaded file. Sample code from: http://www.php.net/manual/en/features.file-upload.php
/***
now verify the mime, i did not find
something more easy than verify the
'image/' ty^pe. if wrong tell it!
***/
if(!eregi('image/', $_FILES['attachement']['type'])) {
echo 'The uploaded file is not an image please upload a valide file!';
} else {
Upvotes: 1