Is this a security risk?

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
SpiderMonkey
Forum Commoner
Posts: 85
Joined: Fri May 05, 2006 4:48 am

Is this a security risk?

Post by SpiderMonkey »

Consider the following expression:

Code: Select all

$_POST["price1"] * $_POST["qty1"]
Given that the result of this will be written into the page at some point, do I need to use htmlspecialchars() here?

Or will the expression evaluate to a number even if the two $_POST variables are strings?
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

The term "better safe than sorry" applies.

Use

Code: Select all

$total = (int) $_POST["price1"] * (int) $_POST["qty1"];
If any of the POST variables contain anything but a number it will result in an integer as a result. Actually you may not even need the (int) casts...

If the total will be used to perform an action, i.e. effect real change. It might be better to error out and force the user to correct the problem in their form. This is relevant since an integer cast can reduce a string (say "23iambad!") to the leading integer 23. This result of type juggling (as the PHP calls it) can cause unexpected results, that a user probably does not intend in the case of a genuine mistake on their part. The larger the impact a mistake will have, the more you want to avoid PHP's finnicky type casting.

This is one of the reasons I usually advise against attempting to fix user mistakes where the resulting fix has a probability of not matching the original intent of the user.
Last edited by Maugrim_The_Reaper on Mon Jun 19, 2006 4:46 am, edited 1 time in total.
SpiderMonkey
Forum Commoner
Posts: 85
Joined: Fri May 05, 2006 4:48 am

Post by SpiderMonkey »

That sounds like a good idea, thanks.

(although I'll have to cast the price as a float)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

note: some posts were split to viewtopic.php?t=50362
Post Reply