Page 1 of 1

Posted: Sat Dec 30, 2006 11:58 am
by WaldoMonster
Is there any difference in security between (int) and intval()?
Here are two examples:

Code: Select all

mysql_query('UPDATE example SET
            filesize    = ' . (int) $filesize . ',
            flag        = ' . (int) $flag . '
            WHERE id    = ' . (int) $id
            );

Code: Select all

mysql_query('UPDATE example SET
            filesize    = ' . intval($filesize) . ',
            flag        = ' . intval($flag) . '
            WHERE id    = ' . intval($id)
            );

Posted: Sat Dec 30, 2006 11:08 pm
by feyd
This thread was split from a year old thread: viewtopic.php?t=35719

The difference is mostly in speed of execution for most people. There are a few other minor (and I really mean minor) differences, but for the most part they are interchangeable.

Posted: Sun Dec 31, 2006 6:03 am
by WaldoMonster
Thanks feyd,
If there are no security differences, I will go for the faster of the two.
I used this little script to see the difference between cast and intval():

Code: Select all

<?php
list($usec, $sec) 	= explode(' ', microtime());
$start_time			= $usec + $sec;

for ($i = 0; $i < 1000000; $i++)
	{
	$a = 12345;
	//$a = (int) $a;
	$a = intval($a);
	}

list($usec, $sec)	= explode(' ', microtime());
$execution_time		= $usec + $sec - $start_time;
echo 'Script execution time: ' . number_format($execution_time * 1000, 1) . 'ms';
?>
As you can see the difference are quite obvious on my system:

With $a = (int) $a; will result in:

Code: Select all

Script execution time: 746.5ms
With $a = intval($a); will result in:

Code: Select all

Script execution time: 1,207.7ms
The execution time is different every time you run the script.
But roughly the difference in percentage is the same.

Posted: Sun Dec 31, 2006 11:41 am
by Ollie Saunders
feyd wrote:The difference is mostly in speed of execution for most people. There are a few other minor (and I really mean minor) differences, but for the most part they are interchangeable.
I'm interested, what are those minor differences? I couldn't see anything in that thread you posted, feyd.

Posted: Sun Dec 31, 2006 11:52 am
by feyd
The difference is one is a function. The other is not.

Posted: Mon Jan 01, 2007 6:26 am
by Ollie Saunders
Oh right, I thought you meant they actually gave different results.

Posted: Mon Jan 01, 2007 12:36 pm
by Christopher
I have a recollection that someone looked at the internals and said that the call the same code but in slightly different contexts. Does anyone remember about this?