What is a good way to process data from a form before applying business logic in PHP?
I think this is a comm开发者_运维百科on issue.
Whenever there is a form on a web page, there is a PHP file on the back-end processing the data sent from the form. You start with $_POST
, You need to ensure that the names of input elements are not falsified, increased or decreased, and you want to make sure that no input elements are left blank, and you also need to escape quotation marks, so you may need to employ isset()
, empty()
, mysql_real_escape_string()
or other functions to do this routine work before you apply business logic to these data.
What's the best way to do this routine work?
I want to write less code, and make it robust.
Maybe there are no best way, but at least there are good ways to do it. How to do it?
For the sake of convenience, suppose there are data like username, password, title, content, question, answer,unit_price,...
What if I don't use any PHP framework?
IMHO,
The Zend_Form component provide a good robust reusable way to do that kind of tasks.
As RageZ has talked about Zend_Form
... If you're really only after the filtering- and validation-part you don't have to use the (sometimes) bloated and complicated interface of Zend_Form
. You can use Zend_Filter_Input
, which actually is Zend_Form
without forms (the rendering part). You can use the same filters and validators as in Zend_Form
but in a conciser way.
But every PHP framework should have its own input-sanitation component, so replace Zend_Form
/Zend_Filter_Input
with the appropriate component of the framework you like to use.
I'll add a second answer as this one has nothing to do with my first answer which was aimed at the Zend Framework.
If you don't want to use a framework and if you do have PHP >= 5.2.0 you can use the ext/filter
extension which actually has at least most of the important features from the framework filtering and validating components.
精彩评论