Jump to content

Clean form input function returns gibberish


phpisnotfordummies

Recommended Posts

Hello!

 

I'm using the following code to "sanitize" form input.

 

function sanitize($interim) {
  $interim = stripslashes(trim($interim));
  $interim = substr($interim, 0, 50);
  $interim = htmlentities($interim); 
  $interim = nl2br($interim); 
  $interim = addslashes($interim);
  return $interim; 
}

$name = sanitize($_POST['name']);

 

However, when I input \, it returns \\, and so on (the script doubles the backslash input).

 

Also, if I input text in Cyrillic (and possibly other non-latin alphabets), the function returns gibberish. For instance, entering "Мир" returns "Ð�иÑ�". Before adding the "sanitize" function the script handled those characters well.

 

What can I do to correct these two issues?

 

Thank you

Tony

1) Use htmlspecialchars() instead of htmlentities(). This would probably solve the Cyrillic characters issue.

2) Remove the addslashes() in the end if you don't want backslashes or quotes to be escaped (with a backslash).

3) Use stripslashes() only if magic_quotes is set.

 

Your function should look like this imo:

<?php

function sanitize($interim)
{
$interim = (get_magic_quotes_gpc()) ? trim(stripslashes($interim)) : trim($interim);
$interim = substr($interim, 0, 50);
$interim = htmlspecialchars($interim);
$interim = nl2br($interim);
return $interim;
}

?>

 

 

Orio.

That's one option.

If you want to send it as a regular mail, remove the nl2br() part and htmlspecialchars(). This way, if you send it as plain text, the html will have no affect so it will be ok.

 

Also- are you sure you want to sure the substr() part? Why do you want only the 50 first characters?

 

Orio.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.