How to validate a File Field in PHP by using JavaScript

This post is relate to my previous post where I have showed you how to insert an image. The place that we have been provided to upload an image is same as uploading a file. So we as developers, have responsibility to validate that File Field by not letting others to upload any executable (*.exe) file to the server. 

So today I am going to show you a simple JavaScript that check what you are trying to upload through the form. Here I only check the file extension and if it is a “.exe” file I am not allow them to upload that file to the database and the server. The interface is same as my earlier post which I have mentioned above. Following is the relevant code for that script. You have to include that code block within;

<script type=”text/javascript”>…</script>

Now we will see the code.

function imageValidate(){
	var str = document.form1.fileFieldImage.value;
	var lower = str.toLowerCase();
	var newStr = lower.substring(lower.length-4, lower.length);
	if(newStr == ".exe"){
		alert("You cannot upload executable files...!");
		return (false);
			return (true);

Here I have used the name attribute to call the form elements in the JavaScript. As an example form1 is the name attribute of the form.

The logic I have used here is, first I get the value that the client has entered to the File Field/Image Field. Then I convert that whole string in to lower case. Next I substring it from end where the file extension is. I just wanted to take last four characters of the string and check whether it is equal to “.exe“. If it is an executable file the Submit function will not be work and give you an alert message.

So from where this JavaScript called in to action. I have chosen the Submit button. This is the code for that.

input type="submit" name="buttonSubmit" id="buttonSubmit" value="Submit" onclick="javascript: return imageValidate()" 

Todays’ fun time is over. Enjoy yourself🙂

About AnujAroshA

An undergraduate in the stream of ICT (Information & Communication Technology). A simple person :)
This entry was posted in Javascript, PHP examples. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s