PHP - Server Side Validation - Is this a good method? - php

I have done extensive client-side validation through the help from jQuery. Now come to the server side validation, if I found some fields are not valid, can I simply return an error to client and without any useful message?
My assumption is that the user has to enable JavaScript in order to access my webpage. The user will not see the form if the web browser disabled the JavaScript. I can simply use noscript to do that. If they submit the information through the form I designed, there should be no invalid field submitted to server. Thus, if I found any invalid field in server side, then my form is corrupted by some hacker rather than some regular users.
Does my understanding make sense to you?
< The following message is appended based on comments from many experts here >
I am sorry that I didn't mention my question clearly here. I always do server side validation b/c I should not trust any user input.
However, my point here is that whether or not I should pass the server side error message to the user. Since, if a user uses my form and submits the form to server PHP, there should never be an invalid field. If such thing happens, then I assume that some hackers are playing with my PHP. So I would like to ignore them.
The major reason why I try to avoid passing the server side error messages back to client is that I didn't find a better solution to do so. I have posted several related questions here without good suggestion or examples.
< --- END ---- >
Thank you

You should always always have server-side validation.
I would suggest you to have a look at:
Validation, client-side vs. server-side
The client side validation is always a good idea and you should go for it but server-side validation should be a must and good coding practice.

In your situation, it sounds like you can be fairly certain that valid users won't be hitting PHP validation errors. So you can respond with slacker error messages. You really ought to give some decent indication of what went wrong though. If you don't, you'll regret it one day when the javascript fails for some reason (like you changed it and didn't test well enough).

Client side validation is only for users that actually use your site. Spam-bots, etc can easily omit it, so there always should be validation at the server site. When validation error is occurred a message should be sent back to user, that informs what is wrong.
Never use only client side validation. It can be only an extras.

Server validation is absolute must have for every web application because it's really easy to send fake headers. For example, you javascript do not allow to enter letters to the form, but I can simply send fake headers containing letters, digits etc.

Validation of anything on the client is only useful to help your users catch mistakes like "oh, you didn't give us a Last Name, please go fill that in". Someone such as myself can simply send any request I desire what-so-ever to your server, be able to deal with it, or be ready to deal with a potentially corrupted database and a CD-Rom of your customer's CreditCard numbers floating around Estonia.
Having the server reply with the form depends on how your structure your code-- eg, if it's ajax or whatever. But reporting the problem is always nice to have.

I always send a useful error message back. You will likely need a way for the server to report other error conditions anyway (database errors, etc.).

Related

Does HTTPS make POST data encrypted?

I am new to the world of programming and I have learnt enough about basic CRUD-type web applications using HTML-AJAX-PHP-MySQL. I have been learning to code as a hobby and as a result have only been using a WAMP/XAMP setup (localhost). I now want to venture into using a VPS and learning to set it up and eventually open up a new project for public use.
I notice that whenever I send form data to my PHP file using AJAX or even a regular POST, if I open the Chrome debugger, and go to "Network", I can see the data being sent, and also to which backend PHP file it is sending the data to.
If a user can see this, can they intercept this data, modify it, and send it to the same backend PHP file? If they create their own simple HTML page and send the POST data to my PHP backend file, will it work?
If so, how can I avoid this? I have been reading up on using HTTPS but I am still confused. Would using HTTPS mean I would have to alter my code in any way?
The browser is obviously going to know what data it is sending, and it is going to show it in the debugger. HTTPS encrypts that data in transit and the remote server will decrypt it upon receipt; i.e. it protects against any 3rd parties in the middle being able to read or manipulate the data.
This may come as a shock to you (or perhaps not), but communication with your server happens exclusively over HTTP(S). That is a simple text protocol. Anyone can send arbitrary HTTP requests to your server at any time from anywhere. HTTPS encrypted or not. If you're concerned about somebody manipulating the data being sent through the browsers debugger tools… your concerns are entirely misdirected. There are many simpler ways to send any arbitrary crafted HTTP request to your server without even going to your site.
Your server can only rely on the data it receives and must strictly validate the given data on its own merits. Trying to lock down the client side in any way is futile.
This is even simpler than that.
Whether you are using GET or POST to transmit parameters, the HTTP request is sent to your server by the user's client, whether it's a web browser, telnet or anything else. The user can know what these POST parameters are simply because it's the user who sends them - regardless of the user's personal involvement in the process.
You are taking the problem from the wrong end.
One of the most important rules of programming is :
Never trust user entries is a basic rule of programming ! Users can and will make mistakes, and some of them will try to damage you or steal from you.
Welcome into the club.
Therefore, you must not allow your code to perform any operation that could damage you in any way if the POST or GET parameters you receive aren't what you expect, be it by mistake or from malicious intents. If your code, by the way it's designed, renders you vulnerable to harm simply by sending specific POST values to one of your pages, then your design is at fault and you should redo it taking that problematic into account.
That problematic being a major issue while designing programs, you will find plenty of documentation, tutorials and tips regarding how to prevent your code to turn against you.
Don't worry, that's not that hard to handle, and the fact that you came up with that concern by yourself show how good you are at figuring things out and how commited you are to produce good code, there is no reason why you should fail.
Feel free to post another question if you are stuck regarding a particular matter while taking on your security update.
HTTPS encrypts in-transit, so won't address this issue.
You cannot trust anything client-side. Any data sent via a webform can be set to whatever the client wants. They don't even have to intercept it. They can just modify the HTML on the page.
There is no way around this. You can, and should, do client side validation. But, since this is typically just JavaScript, it can be modified/disabled.
Therefore, you must validate all data server side when it is received. Digits should be digits, strip any backslashes or invalid special characters, etc.
Everyone can send whatever they want to your application. HTTPS just means that they can't see and manipulate what others send to your application. But you always have to work under the assumption that what is sent to your application as POST, GET, COOKIE or whatever is evil.
In HTTPS, the TLS channel is established before and HTTP data is transfered so, from that point of view, there is no difference between GET and POST requests.
It is encrypted but that is only supposed to protects against mitm attacks.
your php backend has no idea where the data it receives comes from which is why you have to assume any data it receives comes straight from a hacker.
Since you can't protect against unsavoury data being sent you have to ensure that you handle all data received safely. Some steps to take involve ensuring that any files uploaded can't be executed (i.e. if someone uploads a php file instead of an image), ensuring that data received never directly interacts with the database (i.e. https://xkcd.com/327/), & ensuring you don't trust someone just because they say they are logged in as a user.
To protect further do some research into whatever you are doing with the received post data and look up the best practices for whatever it is.

Why server-side script is better when making a contact form?

I searched over the web and I found that a lot of people say that server-side script is better when making a contact form for a website... Can someone tell me why, please?
In my little experience I appreciate when a contact form is able to hightlight istantly when I wrote a wrong email, or a field is missing, rather than waiting for the answer of the server after processing the input in a php page. Maybe is better to implement both jquery validating and server-side validating?
They must be talking about the form validation. Client side validation is usually done with JavaScript/jQuery which can be easily manipulated using tools like Firebug. If user disables his JavaScript, the validation will fail and wrong data will be posted, inorder to prevent that, Server Side Validation is used for example, PHP, ASP.
The data is posted to the server, server validates the data, if it's incorrect, it will throw back the error to the user, and the most important is that server side validation cannot be manipulated/modified easily.
Now you may ask why to validate Client Side if it can be modified/broken easily? Well, not everyone is intelligent to fool your validation, home/normal users often forget some fields to fill up which are compulsory, if you do not keep a client side check at all, your server will get more and more requests directly, thus increasing the load, inorder to prevent that, you need to keep a client side check as well, which will prevent the form details to be posted to the server directly, thus decreasing the server load.
Also, it will save the time for your users, JavaScript validations are very quick, the users are responded with the related error messages when they are typing, or they move to the next field or very soon after the submit button is pressed. Where as server validation will make the process lengthy as forms will be submitted first, server will validate, and than it will return the message. Not much friendly for an user huh?
So the bottom line is validate both, Client Side and Server Side, but make sure you DO VALIDATE Server Side.
If you use client side languges like javascript or jquery for validation then modern browsers have the option to turn off or disable javscript and if they do so then validations will not work.But its not applicable in the case of server side validations.You can refer these links for more
http://www.dzyngiri.com/client-side-vs-server-side-validation/
JavaScript: client-side vs. server-side validation
You can perform sending and validating on server side but you can also provide basic validation on client side. Thanks to that you can notify user when something is wrong instantly. But also you will be sure that all data is correct (because of server side validation).

What should we do with a bad request?

In php, when you process GET/POST requests, you must check them etc. What if a parameter is missing or bad? If it's supposed to be some kind of hack, what should you do then? Just die(); with "dontHackMe"?
No, don't just die() with "dontHackMe". I see two outcomes for that:
If the user isn't malicious and it was a bug or an honest problem, you've offered the user no recourse for help.
That's actually a quite amateurish response and may even provoke an actual attacker to look for more security holes.
HTTP defines a list of status codes for responses. Simply choose the correct one and respond with that code, along with a default response page of some kind.
For example, if the request is malformed or incorrect in some way, then the 400 (Bad Request) response code is the way to go. The actual page in the response should indicate that it was a bad request and perhaps even offer an option for the user to seek help if they need it (such as a link to a help section on the site or a link to a contact form).
The reason for this response structure is two-fold:
By offering a helpful page, you create a human-readable form of output which people can see and appreciate, making your application that much more user-friendly.
By returning the correct status codes in your responses (all of your responses, not just rejected potential hacking attempts), you create a machine-readable interface that automated clients can use to more effectively interact with your application. (A 400 response, for example, tells a non-malicious automated client that it shouldn't even bother making that request again... The request was received and processed and was found to be bad.)
Edit: To clarify... This is for responding to genuinely bad requests. If the data being submitted in a form is simply incorrect (doesn't meet business rules, uses a letter where a number was intended, etc.) then Michael Hampton offers a perfectly sound suggestion. Essentially the server would "play dumb" and just re-display the form.
Don't give a potential attacker any more information than they already have. (Keeping in mind that a bad error message is more information than they already have.) The application would simply be saying, "Hmm... You tried to submit this form, but it's wrong. Here, try again."
Don't send an HTTP 4xx response unless something was wrong with the HTTP headers themselves.
If you receive invalid input from the client, redisplay the form with the invalid fields highlighted as being invalid.

Why I should use JavaScript for page validation, even I can use php for same work?

I m beginner to learn java script and I just read that we use java script for interactive and page validation ...so my question is that
We can validate our page with the help of php then why we should use JavaScript?
Ideally, you should be doing both. But at the least, you should be using server side validation.
The reason you have JS or client side validation is so that
The user gets immediate feedback on errors
Your server is spared the round trip for smaller validation
You should never rely only on JS for validation as this can be easily disabled/circumvented. Always use it as an added layer to your server side validation.
Javascript validation allows a more 'responsive' validation message since it doesn't require a postback.
However you should always include server side validation AS WELL since a user could turn off javascript and bypass the validation.
Javascript vaidation is client side validation. You do it even before your page is submitted to the server. And hence prevent resubmitting your page all again
Javascript is used for browser side validation i.e, client side , But php is used for ser
I guess you mean that you can validate the data entered at the server end in php and you do not see the point in validating at the client side using Javascript.
Javascript runs on the client (i.e. the user's browser), which means the data does not have to make a round trip to the server to be validated. This makes the process faster and reduces load on the server. Imagine someone entering a huge amount of data into a text field that is supposed to accept only 15 characters. If you validate only in the server side, your application stalls while the data is being sent. If you also validate using Javascript, nothing is sent back since it is caught at the user's browser.
That being said, it is a good idea to validate at both the client and the server. This takes care of someone intentionally circumventing your Javascript validation (e.g. by turning off Javascript).
These are the two sides of a coin:
PHP = Server Side vs Javascript = Client Side
Both operate in different mediums on opposite sides of the HTTP fence
You can't really compare them. Normally, you use them both. Javascript for the nice dynamic client side stuff (like hiding a part of the page) and PHP to generate the page. And then there's ajax, which makes both work really great together.
Some more comparision:
In php you can have the remote and local time
In js you can have user time...
In php you can have remote and host address
In js ... i dont know !!
In php the source is not lookable in the source code
In js the source can be see in the source code of the page.
To use php it requires sending a request to the php and getting a response.
Javascript is client-side therefore eliminates the need for the request to be send.
Javascript is a much faster way since you do not need to send a request to the server.
But it depends if you are validating a form with certain data that you need checked.
For example, if you have a form and there is an email input box, you may want to check if that email is already in your database. This would require php.
Otherwise, if you do not need to make a request to your server, javascript would be the better one to use.

form validation with javascript vs php

Why should I bother to use JavaScript for form validation when I still have to use PHP since the user could have JavaScript support turned off.
Isn't it unnecessary?
Update:
Ok thanks for your answers. it sounds like a good idea to have it on the client side too. where can I download good JavaScript validations?
Do you know where I can download a validation script like that one in yahoo when you register an account?
Javascript validation allows your user to be informed of any errors prior to their submitting the form to the server. This saves irritating page-reloads (since on submit the JS catches the event and validates the form, preventing form-submission if errors are found) and minimises the chances of their having to re-enter information again (and again and again...), or leaving prior to completing the form properly. JS validation is not a substitute for server-side validation (since the user can see the JS, and, by saving the page and amending the JS do whatever they want); but it's a convenience for them.
This is simply part of the concept of progressive enhancement, whereby JS provides a mechanism for enhancing the experience for the user, if it's there and turned on, and hopefully makes their interaction with your site pleasant, or, at least, minimally irritating.
Edited in response to OP's question regarding 'where to download a JS validation tool.'
While I can't -necessarily- recommend any one library (I tend to write my own as required, or borrow from previously self-written examples), a Google search threw these options up:
http://www.jsvalidate.com/
Stephen Walther's page, discussing Microsoft's CDN and jQuery-validation, linking to jQuery Validation plug-in:
jQuery.validate (hosted at MS' ajax.microsoft.com subdomain)
jQuery.validate.min
jQuery validate plug-in homepage (bassistance.de).
You should ALWAYS validate in PHP on the SERVER SIDE and validation in JavaScript is CLIENT SIDE validation for user CONVENIENCE. Thanks to validation on client user may find errors in his form without page relodaing. But user may sent form data without data script validation
(for example he may not have JS support in web browser), thus always validate on the server side.
... as courtesy to the users pretty much. Makes life easier for the ordinary users that simply commit human things from time to time.
I recommend you using unified server-side and client-side validation using a framework, since it may avoid confronting the user to data valid on client side but rejected by the server, or the opposite (client side too restrictive).
Following list of framework give information about server/client side validation:
http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks
It's a matter of whether you want your form (and website as a whole) to be interactive-cum-user-friendly or not. You can just let the server-side do the validations and throw the error back to the users but that would be less interactive and less user-friendly than warning the users before they submit the form (although you still need to validate the inputs on server-side no matter what). Just my 2 cents :P
I recomend to use Javascript for client side and Php for server side
This will make interaction or user friendly site nad reduce reloading page many times in case user submit wrong data
Yes, it is best practice to validate the user input values from both sides client and server side ,
some cases client was disabled javascript or mobile browser that doesn't javascript, remember there is spammers also.
To my mind, only client-side-checking of form input does not work because of security. Imagine you want to check a user password(if "yourpwd" == userinput), with js the user will see the password because it is in the browser-sourcecode .With php, it is not visible because php is for some reason hidden.

Categories