File Upload from HTML form: client and server validation for maximum size

File uploading normally requires client validation (mainly as a UI improvement) and server validation (in case the client validation is bypassed/hacked).

The code

<input type="hidden" name="MAX_FILE_SIZE" 
 value="2621440"/>

only imposes a soft limit (in bytes) on the server side, therefore not a good practice since it can be altered by the user. The solution I adopted is composed by a server side validation AND a client validation (in JavaScript, mainly for a better user experience since it can be easily hacked as all the other JS solutions)

Client validation (JavaScript)

The idea is accessing the files JS property of the input field and read the file size on the ‘change’ event (when a file is selected by the user). If the selected files exceed the max size, I simply display a clear user warning and disable the submit button. I’ve created a generic script that automatically listens to the change event for any file upload element, and reads the max upload size in bytes from the MAX_FILE_SIZE HTML input hidden element in the same form.

Server side validation (PHP)

Just set the desired value for ‘upload_max_filesize’ and ‘post_max_size’ PHP settings (php.ini). Alternatively, if you need application specific settings and you use apache as web server, add the following lines into the .htaccess in your web root

php_value upload_max_filesize 25M
php_value post_max_size 25M

97 things every programmer should know: personal notes

Last month I saw a book flying about the office, containing useful tips from developers. 97 suggestions from experienced developers. Amazon is still selling it, so I suggest you read it if work as a software developer or you occasionally dip into coding: 97 Things Every Programmer Should Know: Collective Wisdom from the Experts

I’ve finished reading it, and I took some notes while reading. Some concepts and suggestions were obvious, as I hear them many times from the community (blogs, conferences, colleagues) or I’ve already personally experienced them. I’ll paste those my notes here, with the hope that you can find something valuable from looking through them.

Continue reading

Validator, Auto complete and Date picker Jquery scripts

In this post I’ll quickly present three Jquery plugin I often use:

Jquery Validator [link] [download my working example html+js.zip]

After defining the field validators (email, string length range, regex, equalTo another element, int…) for all the form elements in one array. It shows the error messages next to the form elements and prevent the form submitting.

Jquery Autocomplete [link] [docs] [download my working example html+js.zip]

It shows a dropdown menu under the text fields suggesting (and autocompleting) data according to the text typed inside the field. It supports preload with json or ajax requests.

Jquery Date Picker [link] [download my example]

It shows a date picker to select and browse dates. Date format customizable.

Other plugins

http://jqueryui.com/

a Javascript function to manage function timeout

Today I worked with form validations and AJAX requests associated with the event keyup in the input fields.
Sometimes the validation requires an AJAX call (for instance to check if the typed text already exists in the DB). In order to avoid a request for each char typed, a good solution might be using set/clearTimeout.
With the aim of doing only one function to manage all the timeouts of the functions called for each field, I’ve written a general function that does that, supporting dynamically the function name.
It uses an array (member of the function) to store the timeouts of the functions called, and an eval to launch/stop the each function with the relative timeout.
Tested only on Firefox 3.5.2


/*javascript*/

function callTimeout(funcName, timeout, args) {
if (args==undefined) {args = "";}
if (timeout == undefined) { timeout=500; }

if (this.timeOutsArray == undefined) {
this.timeOutsArray = new Array(); }
if (this.timeOutsArray[funcName] == undefined) {
this.timeOutsArray[funcName] = 0;
}
if (this.timeOutsArray[funcName]) {
clearTimeout(this.timeOutsArray[funcName]);
}
eval("this.timeOutsArray['"+funcName+"'] = setTimeout('" + funcName + "("+args+")', "+timeout+");");
}

Example of use with JQuery:


$("#field1").keyup(function(){callTimeout("validatefield1",500);})
...
...
$("#anotherFieldN").keyup(function(){callTimeout("validatefieldN",500);})

Behaviour: If the user types very quickly in the search box (id=field1), the function is not called hundreds time, but just at the end after 500ms.

JSON generation with PHP and parsing with jQuery

JSON [official site][wiki] is a data interchange format (similar to XML, but simpler), often used for WEB 2.0 applications to load structured data with AJAX HTTP calls.

– PHP offers functions to encode and decode JSON from/to a PHP value.
– jQuery includes a function (getJSON) to parse HTTP resource with JSON data.

JSON pseudo grammar
#json block: comma separated couple key: value
JSON_BLOCK = { KEY1: VALUE1, KEY2: VALUE2, …, KEY_N: VALUE_N }
#key must be a string (example: “abc123”)
KEY_N = string
# value must be a native type, or array of values or json_block (recursive)
VALUE_N = string | number | true | false | null |
| [
VALUE_N,…, VALUE_N] |JSON_BLOCK

Minimal example:
//note: “less/greater than” symbols are replaced with square brackets because of blogspot limitation

/* json.php – json generation */
print json_encode( array(
“title” => “products”,
“items”=> array(
array(
“id”=>“1”,“title”=>“1st”),
array(
“id”=>“2”,“title”=>“2nd”)
)));
/*
result (“items” key contains an array with two values, each one is a block).
{
“title”:”products”,
“items”: [ {“id”:”1″,”title”:”1st”}, {“id”:”2″,”title”:”2nd”} ]
}
*/


/* page.html – call JSON resource (ajax with jQuery) and write into the DOM*/
[script src=“jquery-1.3.2.min.js” ][/script]
[
script]
$(
document).ready(function(){
$.
getJSON(“json.php”,
function(
data){
$.
each(data.items, function(i,item){
$(
“[h1]”).text(item.id).appendTo(“#main”);
$(
“[h4]”).text(item.title).appendTo(“#main”);
});
});
});
[/
script]
[
body]
[
div id=“main” ][/div]
[/
body]

//output:
[body]
[
div id=“main”
[h1]1[h1] [h4]1st[h4]
[
h1]2[h1] [h4]2nd[h4]
[/
div]
[/
body]