Jump to content

mysql_real_escape_string


YMYL

Recommended Posts

I had a quick question on this. Would you use it for an integer?

 

Lets say

 

$page = $_GET['page'];

 

Would you run mysql_real_escape_string($page) since it is data from the user?

 

I checked and it returns an string, would that mess things up with a script?

Link to comment
Share on other sites

Would you use it for an integer?

No. It is called mysql_real_escape_string() for a reason.

 

I checked and it returns an string, would that mess things up with a script?

$_GET/$_POST values are always string types. So,the input is already a string anyway.

 

PHP is a "loosely" typed language. That means it can (usually) convert variables to the proper types as needed. So you can do math operations on string variables if they contain numeric characters.

 

But, none of this means that you should not safeguard the user input from wreaking havoc on your queries. In this case you want the value to be an integer. So, use the functions within PHP to ensure it is an integer.

 

You can force the value to be an integer by using the intval() function or typecasting the value as in integer

$valueAsInt = intval($_GET['page']);
$typeCastAsInt = (int) $_GET['page'];

 

If the value cannot be converted to an integer value you will get 0. The other approach would be to validate that the value is a string that has the characters matching an integer value;

if(!ctype_digit())
{
   //Value is not a proper integer - do something
   // - provide error or force to default value, e.g. 1
}
else
{
   $page = $_GET['page'];
}

 

I would typically do this

//If post value is set, use intval of it, else default to 1
$page = (isset($_POST['page']) ? intval($_POST['page']) : 1;

//Assuming I know the max page number
//If page less than 1 or greater than max page default to 1
if($page<1 || $page > $maxPages)
{
   $page = 1;
}

Edited by Psycho
Link to comment
Share on other sites

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.