Quantcast
Channel: The Weber Report » PHP
Viewing all articles
Browse latest Browse all 11

Type Casting In PHP – What’s the Point?

$
0
0

PHP LogoDid you know that PHP has some pretty powerful type casting functionality built-in? It’s no surprise if you comprehend the roots of PHP (since it’s written in C), but I can’t help but think that casting is an often-missed tool when a PHP developer is trying to ensure data integrity.

Just for a moment, let me define type casting in case you weren’t “in the know”:

According to Wikipedia, “in computer science, type conversion or typecasting refers to changing an entity of one data type into another.

So, in laymen terms, casting is an easy way to turn one type of data into another type. For example: converting a “string” variable filled with essentially text into an integer variable containing the same numbers but now representing a value. This makes it easy to do math with the value of what once was just a random string of characters.

The following cast types are allow in PHP:

  • String – (string)
  • Boolean – (bool), (boolean)
  • Integer – (int), (integer)
  • Binary – (binary) [PHP 6]
  • Floating Point – (float), (double), (real)
  • Array – (array)
  • Object – (object)

So, in the real world, when does casting actually come in handy?
Normally, PHP handles all this stuff automatically behind the scenes. But, as is normal, dealing with MySQL database interaction is something to always take seriously — and type casting can help you out!

We’re going to assume your aren’t using the PDO Prepare statement (though you should be). As a PHP developer, a major part of your job is containing the inherent security risks of user input. It’s especially important when these inputs interact directly with the database.

So, your simplified (e.g. – don’t complain) database interaction code might look something like this:


$id = mysql_real_escape_string($_POST['input']);
$SQL = 'SELECT * FROM table WHERE id = ' . $id;

Call me an overly nervous Ned, but I’d prefer to use the following code:


$id = mysql_real_escape_string($_POST['input']);
$SQL = 'SELECT * FROM table WHERE id = ' . (int)$id;

Did you notice the subtle change? See the ‘int’ cast of the $id in the SQL statement?

This should certainly help to ensure that I haven’t missed any security holes for this query. Some might say it’s overkill, but I just wanted a simple explanation for using casting, so get off your almighty soapbox already.

Anyways, as you can see, type casting in PHP has real-world uses. Delve into type casting a little more and you’ll find a huge number of cases where it can make your code that much more bullet-proof.

So seriously, try out PHP Type Casting.


Viewing all articles
Browse latest Browse all 11

Latest Images

Trending Articles





Latest Images