Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User input validation, client-side or server-side? [PHP/JS]

Is it better to validate user input before it's sent to the server with JS or server side with PHP? Or maybe it's worth doing both just to be on the safe side?

I'm creating a site (very simple at the moment) that has a members area/admin area/etc. At the moment i only have user input of Username and Password, in the future there will be more (email, address, etc), but whats the best practice of checking the data?

Do i throw a load of 'if...else' statements at it until the user gets it right? Or maybe have separate variables for each value entered by the user and set it to true or false if it's correct or wrong? (like e-mail validation to make sure it's in an email format)

There are a lot of ways to do it, but which ones you would suggest? I don't want to be writing 50 lines of code when i could do the job in 10 lines...if that makes sense :p

Any help would be appreciated, thanks! :)

like image 229
Shogun Avatar asked Jan 08 '12 19:01

Shogun


2 Answers

Server-side validation is a must, client-side validation is a plus.

If you only use client-side validation, nefarious people will hack your system to post un-validated stuff - breaking your scripts, and potentially exploiting your system. This is very bad from a security standpoint.

That said, you should also include client-side validation, since that's much quicker than a round trip to the server, and gives your users instant feedback. This'll keep your users happy, and will have them coming back to your site.

So, if possible, use both. If you can't/won't, then at least do it server-side. Client-side-only validation is a recipe for disaster!

like image 190
Joseph Silber Avatar answered Oct 13 '22 10:10

Joseph Silber


Do both.

Client side gives the responsiveness users expect and server side protects your data.

I'm sure PHP has some libraries that would help you much like what ASP.NET MVC does to provide a way of doing both in one step.

like image 44
Daniel A. White Avatar answered Oct 13 '22 12:10

Daniel A. White