Jump to content

Recommended Posts

Hi All

 

I have some code that checks whether my ProductId, which is passed in a query string, is just a number, to prevent a hacker attempting to replace it with something malicious.  My question is, is my code elegant enough or can you suggest improvements?  Thanks. 

 

//Protection from hackers.  Check ProductId is just a number
$TestForNumber = is_numeric($ProductId);
If ($TestForNumber == 0) {
echo "Sorry, the Product Id tried is not allowed.";
exit();
}

 

Rgds

 

 

Yes, if your product id is only supposed to contain a number then check it is a number before using it in your query.

 

Example url:

yoursite.com/product.php?pid=12324

 

This is the code I'd use to check to see if pid only contains a number

if(isset($_GET['pid']) && is_numeric($_GET['pid']))
{
    $product_id = $_GET['pid'];

    // rest of your code here
}
else
   die('Product ID code invalid');

Careful how you use that.  Hex values, like 0x61646D696E, pass the is_numeric() check, but become a string value if entered unquoted into a MySQL db query.  You might be better off using filter_var() or casting to an int if a number is what you always want.

 

I use something like this

$pid=$_GET['pid']>0?$_GET['pid']:0;

 

just because rarely do u need a negative values, and setting up a failure conditional for yer messages

 

if(!$pid) die('Invalid ID');

 

later in yer code.

But I think u should think how each variable needs to be validated. some will have different requirements than others :) good luck

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.