I have a form that has two text fields and a file upload field.
The validation is handled completely from PHP and I'm using a little bit of Ajax to retrieve the error messages the PHP script produces via an array (err[]).
My problem is, I can't seem to get the file upload validation to work correctly. (when uploading a file, it will always say "Wrong file format only .png , .gif, .jpg, .jpeg are accepted")
The Ajax is below:
function checkform() {
$.post('upload.php', $("form#uploadForm").serialize(), function (data) {
$("div#error").html(data).slideDown("fast");
var destination = $('div#uploadContainer').offset().top - 15;
$("html:not(:animated),body:not(:animated)").animate({
scrollTop: destination
}, 200);
});
return false;
}
The following validation seems to ALWAYS be triggered:
$extension = strrchr($_FILES['uploadFile']['name'], '.');
if (!in_array($extension, $extensions)) {
$err[]='Wrong file format only .png , .gif, .jpg, .jpeg are accepted';
}
...
...
if (isset($_FILES['uploadFile']) && $_FILES['uploadFile']['size'] != 0)
{
// Upload file
}
$extension = end(explode('.', $_FILES['uploadFile']['name']));
if (!in_array($extension, $extensions))
{
$err[]='Wrong file format only .png , .gif, .jpg, .jpeg are accepted';
}
As $extension has extension without dot(.). Remove dot(.) from file extensions
$extensions = array('.png', '.gif', '.jpg', '.jpeg','.PNG', '.GIF', '.JPG', '.JPEG');
which will be
$extensions = array('png', 'gif', 'jpg', 'jpeg','PNG', 'GIF', 'JPG', 'JPEG');
Hope this fixes the bug
Per @riddell's comment (AJAX File Upload with PHP Validation)
the problem is most likely NOT php but actually the Jquery itself. something like this could work
var form = $('form')[0];
var data = new FormData(form);
$.ajax({
url: 'upload.php',
data: data ,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Correct logic for upload and checking file extension
if (isset($_FILES['uploadFile']) && $_FILES['uploadFile']['size'] != 0)
{
$extension = end(explode('.', $_FILES['uploadFile']['name']));
if (!in_array($extension, $extensions))
{
$err[]='Wrong file format only .png , .gif, .jpg, .jpeg are accepted';
}
// Write code to upload image here
}
else
{
// There was error while uploading image
// $_FILES['uploadFile']['error'] gives error code
//
// Possible errors
// UPLOAD_ERR_OK: 0
// UPLOAD_ERR_INI_SIZE: 1
// UPLOAD_ERR_FORM_SIZE: 2
// UPLOAD_ERR_NO_TMP_DIR: 6
// UPLOAD_ERR_CANT_WRITE: 7
// UPLOAD_ERR_EXTENSION: 8
// UPLOAD_ERR_PARTIAL: 3
}