I was wondering if it is really necessary to validate in both JS and PHP?
I have my submit button with JS document.myform.submit()sending with PHP POST to the same page.
If a user disables JS he can not send the form anyway.
So I wanted to ask about security, can someone send the variables in another way bypassing the javascript? How would they do this?
And if they can, the answer if I should validate in PHP as well would be YES, right?
-
Just a personal opinion - you may consider allowing submit without javascript. Personally, I run a whitelist of sites allowed to run javascript. As a courtesy, your javascripted form can tell me if I've inputted bad values before submit. But with javascript blocked, though I can alter your webform behavior client-side or use socket calls to bypass the form completely, I'm prevented from using your site at all as a regular user.bob-the-destroyer– bob-the-destroyer2010-08-09 09:33:58 +00:00Commented Aug 9, 2010 at 9:33
5 Answers
The answer is simple.
Server-side is obligatory and must be done unconditionally.
Client-side validation is optional, just for user's convenience.
Thus, validating on both sides isn't necessary but preferred for sake of usability
If a user disables JS he can not send the form anyway.
lol. user can save your form on their local disk and edit it in a way they want.
Comments
yes, someone can send the variables using urllib2 in python for instance. This is very easy to do. If you are only going to do one set of validations, do it server side. doing it client side is nothing more than a courtesy to your users.
as an example of how easy it is:
import urllib2
variables = {'variable1': value1, 'variable2': value2}
urllib2.urlopen('http://yoursite.com/index.php/yourform', variables)
# your form has now been spoofed.
Adding headers and cookie management to spoof any user agent is just as trivial
Comments
Just as everyone answered - never rely only on client side validation only. This is so easy to abuse, one doesn't even have to save your webpage to disk, he can use libcurl or any other HTTP library, or just play with Firebug ect.
Validation on the client side is very "user friendly" though. You can add Ajax validation to your forms, and still this just convenience and should rely on server side code.
Comments
I completely agree with everybody above - client side is mainly to benefit the person filling in the form. Server side is more to make sure you're not being targeted.
If you want a nice looking client side validation script, I've written one - free to download and use and very customisable. It'll even catch wrongly spelled email addresses and suggest a correct version. You can get it here if you're interested:
http://www.blackboxtechnology.co.uk/free-stuff/javascript-form-checker.php
Enjoy!