typecasting in php

Tuesday 17th July 2007 10:41 PM

TAGS: PHP, typecasting

PHP is a loosely typed language, that is you don't need to keep track of variable types like languages such as Java. Both have their uses in the programming world, and it often is useful to tighten things up a little in PHP.

Case in point, accepting user input. If you expect that you will be recieving an interger, then try using intval(). It will convert your input to an interger value. It has a bunch of cousins such as doubleval(), floatval(), etc depending on your needs.

  $userInput = 5;
  $badUserInput = "not an int";
  echo intval($userInput); // returns 5
  echo intval($badUserInput);  // returns 0

An alternative to these functions is to use the C style type-casting as such:

  $safeVariable = (int) $userInput// returns 5

There are an arsnal of other functions which also can help you validate input - things such as is_array() can ensure you are accepting an array only, or is_numeric() will confirm your variable is infact, a number. If you want to find out more about a certain variable, and its type - try using var_dump().

You really can dramatically drecrease the likelyhood of unexpected user input and attempts at hacking from the outside by being very tough on what input your application accepts and stores/displays, too much checking is never enough.

Comments on this article:


#1 prasad says:

Monday 3rd September 2007 04:09 PM

thanx that helped me a lot


Add Comment:


Make a Comment

*Nb, all comments are moderated to prevent spam or inappropriate content.








netforge logo
netforge provides high quality and friendly website design services to business. We're Australian based and reliable... (find out more).