pachaleke
pachaleke

Reputation: 9

PHP: image upload

I am trying to upload an image with this script. Bit it keeps giving me this error: The file you attempted to upload is not allowed. And the files that i tried to upload where jpg and png.

Can someone tell whats going wrong?

if(isset($_POST['upload'])) {

$allowed_filetypes = array('.jpg','.jpeg','.png','.gif');
$max_filesize = 10485760;
$upload_path = 'images/tekeningen/';
description = $_POST['imgdesc'];

$filename = $_FILES['userfile'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);

if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');

if(filesize($_FILES['userfile']) > $max_filesize)
die('The file you attempted to upload is too large.');

if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');

if(move_uploaded_file($_FILES['userfile'],$upload_path . $filename)) {
$query = "INSERT INTO uploads (description) VALUES ($filename, $description)"; 
mysql_query($query);

echo 'Your file upload was successful!';


} else {
echo 'There was an error during the file upload.  Please try again.';
}
}

Upvotes: 1

Views: 216

Answers (2)

shyammakwana.me
shyammakwana.me

Reputation: 5752

You should use

$filename = $_FILES['userfile']['name'];

instead of

$filename = $_FILES['userfile'];

this

filesize($_FILES['userfile']['tmp_name'])

instead of

filesize($_FILES['userfile'])

this

move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))

instead of this

move_uploaded_file($_FILES['userfile'],$upload_path . $filename))

Refer this tutorial

For security reason

You should not use check only extension.

Instead of checking extension only check MIME type also.

Upvotes: 2

blex
blex

Reputation: 25634

You did not properly get your extension. Your script is not going to work when the filename contains ..

To get the file extension, I would recommend this

$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

and removing the . in your allowed extensions like so :

$allowed_filetypes = array('jpg','jpeg','png','gif');

Upvotes: 1

Related Questions