开发者

Is it possible to force your PHP input variables to be strong typed

When I started off with PHP, I was really happy with how PHP was loosely typed and how easy it was to learn. But as I grew into it, I realized that being loosely typed actually complicated my scripts rather then simplifying them. And now I am looking for ways I could strong type my PHP variables, specifically the input variables ($_POST, $_GET, $_COOKIE, $_REQUEST and some $_SERVER vars).

Also, I would like my validation and sanitizing to be hidden away in this process so that I can "forget" about SQL Injection and many of the other error prone validation processes. I have a rough sketch of how I want this to be.

First I declare the variable. Preferably in OOP

$varClass->post->variable_name->type('STR', 'SQL', 'EMAIL');  

// or as an array  
$_MY_POST['variable_name'] = array('STR', 'SQL', 'EMIAIL');

Now I could possibly just drop 开发者_运维问答all undeclared variable from the predefined PHP GLOBALs and use the variable type to validate and sanitize them directly in the global arrays.

I could also set the values of unvalidated variables like an emaill to bool false and un-submitted to null and use them during data validation. However, before I went off and re-invented the wheel I was hoping:

some one might direct me to a library which already helps solve my issues?

if there were any reasons why I shouldn't pursue on this wild fantasy? Better and more clear ways of achieving this?

and Other general thoughts you may have about this idea?


http://sourceforge.net/p/php7framework/wiki/input/

Wraps the superglobals per default, but you could also instantiate local objects with $postFilter = new input($_POST). It's supposed to be used manually like this:

 $_POST->email->sql["variable_name"]
 $_POST->array->int["order_list"]

And it complains if it sees any $_POST["raw"] access.

But you can also pre-define filter lists. I would do that centrally in the class-definition. This is supposed to be an add-on for old applications, where you don't want to manually go through the code and rewrite strings to enforce data formats or types:

 var $__rules = array(
      "variable_name" => "email,sql",
      "order_id" => "int,range:0:500",
      "order_list" => "array,int",
 );

But I would personally avoid ->sql escaping prematurely. If available PDO and parameterized SQL should be used. But of course a central escaping feature is anyway better than cautiosness.

Also you can define custom filters. It picks up global functions for example.


PHP was loosely typed

No - its not loosely typed, it's dynamically typed - there's a subtle difference.

actually complicated my scripts rather then simplifying them

My experience is exactly the opposite.

I would like my validation and sanitizing...

Strong typing is not the way to deal with input validation, particularly over medium like HTTP (which is loosely typed). It's just not practical to have type validation for every possible input - sure you can store an email address in a string - but that does not mean the email address is formatted correctly, how do you ensure that a file is an image? How does strong typing ensure that the start date is before the end date?

While recent verions of PHP have filter functionality, I (and most people I know) have long been using my own input validation lib for atoms, and second-order validation (comparing the relative values of more than one input) needs custom code. The only time you should ever change the type of inputs is where there is no resulting data loss (e.g. string to number conversions - but you need to very that you've not lost data as a result). Declaring the expected type of the input var is no more difficult than declaring an actual type for a variable. If you can't create a valid representation of the input suitable for processing, then your code should never guess what the user meant - you need to reject the input and inform the user / calling procedure.

A lot of validation can be very contextual - e.g. 02/12/2010 in the UK is 10 months after the same date in the US.

If you really want PHP to behave as if its strongly typed, have a look at PHPLint

so that I can "forget" about SQL Injection

NO! You validate/sanitize inputs and you transform outputs according to where they are being output to! The right representation of a string for writing to HTML is different from writing it to a URL which is different from writing it to a database.


I have written a forms system for our app which does this to a large extent;

  • I define all the fields I'm expecting and rules about them (data type, at minimum, but also mins, maximums, enumerations, etc)
  • a nonce is used to secure the form and also to determine if it was submitted
  • when the session is recovered, each serialised form checks to see if the appropriate nonce was sent and considers itself submitted if so
    • it then checks each known field, gets the submitted data and validates it
    • all fields can be reset to their default if they're invalid

This also handles the rendering of forms and generation of client side validation rules as well, so I can just write the rules once (server side) and both client and server side validation automatically occurs. Data type rules are the minimum that must be defined for each field.

Unfortunately it's not open source and I don't have permission to open source it; I looked for a long time to find something like this, but I couldn't really find anything. The Pear Quickforms library was the closest, but didn't seem to cover all of the validation and had terrible, terrible documentation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜