PHP - Sanitised application principles for security and useability
Archive - Originally posted on "The Horse's Mouth" - 2008-06-16 18:24:09 - Graham EllisWhen you write a simple web based application, such as a tax calculator, it's always a good ides to echo back the values that your user filled in to the initial form as a part of the response page. That way, anyone who prints out the resulting screen will know just WHAT the question was that the page answers!
It's also a good idea (a VERY good idea - read mandatory) to sanitise the user's inputs, checking against injection attacks using dingle quotes, < characters, & characters, and so on. These checks help avoid injection attacks with Javascript and HTML, and prepare you against injection attacks against a database you may add later
When you echo back the results page and present a further copy of the form that can be filled in, you should echo the values that the user entered the previous time ... and you need to be careful to sanitise the string and make sure it will accept space characters by quoting back the value when you echo it. Users often need to correct or modify values and resubmit forms, and it's very antisocial of the programmer to present them with a completely blank form as a punishment for making just one mistake!
Finally, keep the bulk of your PHP towards the top of your code and the HTML towards the bottom. That way, you can easily change the look and feel of the page without having to rework the logic, or can easily change the logic without major work on the look and feel
These are techniques that we'll teach you from day one of our PHP Programming Course and we continue with on our PHP Techniques Workshop.
I have just written and presented, in front of my delegates, an example to show these principles all in a single piece of code.
You can see the source here and run it here.