Question

i have a problem with sanitizing data.

Is there a built in php function to sanitize data like htmlspecialchars/htmlenteties, which if provided a non string value it keeps its original type. Example:

The problem:
    $a = 1;//(int);
    $b = htmlspecialchars($a);
    var_dump($b); // string "1"
The desired effect:
    $a = 1;//(int);
    $b = htmlspecialchars($a);
    var_dump($b); // integer"1"

Thanks for the time.

Was it helpful?

Solution

$a = 1;//(int);
$b = htmlspecialchars($a);
settype($b,gettype($a));
var_dump($b); // integer"1"

Results in

int(1)

OTHER TIPS

You can check by type first, then use a htmlspecialchars and then cast to the type... although that would defy the use of htmlspecial chars. Also, i think the $a will probably come from some request variable, which will always be a string in that case.

It almost sounds as if you would like a function to determine the context for you. Since if it is already typed int, what 'escaping' do you want to do?

There is no need to use htmlspecialchars on an integer value.

I just get the type, and do something like i show in the code below, even you can settype again later.

$var_type = gettype($var);

switch ($var_type)
{
    case 'integer':
         break;
    case 'string':
         $var = htmlspecialchars($var);
}

return $var;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top