I currently having a problem to validate the file name that user upload into the file input. I already had the validation on file extension, but when user trying to upload a file name example 1.hello.jpg
, for my JavaScript validation code it was look okay as it was jpg
extension. But in my PHP part my validation for the file extension does not recognize it as I'm using explode function to validate the file extension.
Is there anyway to validate the special character of the file in client side before submitted to my server side? Thanks
Here are my validation on client side:
<script type='text/javascript'>
function checkDisabled(yourSubmitButton){
//No 1 file input validation
var res_field = document.getElementById('uploaded_file').value;
var extension = res_field.substr(res_field.lastIndexOf('.') + 1).toLowerCase();
var allowedExtensions = ['jpg','JPG','bmp','BMP','png','PNG','jpeg','JPEG'];
if(document.getElementById('bannerName').value.length !=0){
//File input extension validation
if (res_field.length > 0)
{
if (allowedExtensions.indexOf(extension) !== -1)
{
yourSubmitButton.disabled = false;
return;
}
}
}
// If we have made it here, disable it
yourSubmitButton.disabled = true;
};
</script>
Here are my php code for validate the extension:
$valid_formats = array("jpg", "JPEG","png","PNG","bmp","BMP",'JPG','jpeg');
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['uploaded_file']['name'];
$size = $_FILES['uploaded_file']['size'];
$bName = $_POST['bannerName'];
$bDescription = $_POST['bannerDescription'];
$bK = $_POST['bannerK'];
$bKe = $_POST['bannerKe'];
$bS= $_POST['bannerS'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
...........
}
}