I am working on a form with the possiblity for the user to use illegal/special characters in the string that is to be submitted to the database. I want to escape/negate these characters in the string and have been using htmlspecialchars(). However, is there is a better/faster method?
Answers
WIN!
The solution is to add accept-charset="utf-8" to the form tag.
I didnt have the option to add this to the header of the page but adding it to the form tag solved all my issues. Big shout out to @deceze for posting a link to this website http://kunststube.net/frontback/
I find iconv completely unreliable, and I dislike preg_match solutions and big arrays ... so my favorite way is ...
function toASCII( $str )
{
return strtr(utf8_decode($str),
utf8_decode('ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'),
'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy');
}
mysql_real_scape_string is for STRINGS. it will not make an integer 'safe' for use. e.g.
$safe = mysql_real_escape_string($_GET['page']);
will do NOTHING where
$_GET['page'] = "0 = 0";
because there's no SQL metacharacters in there. your query would end up something like
SELECT ... WHERE somefield = 0 = 0
However, doing intval() will convert that 0=0
into a plain 0
.
I think it is completely reasonable to wait for the response and update as a result of a callback. Doing so does not detract from the async approach. It is still fully async because you are not blocking the entire page or reloading it completely.
Plenty of times in apps, especially in mobile ones where the bandwidth might be limited, I will see a spinner indicating that the field is submitting. This does not hold up any other part of the app. Even does this when I use the mobile view. Rely on the callbacks in order to stay async and still be synced to database return values.
If you submit this data to the database, please take a look at the escape functions for your database.
That is, for MySQL there is mysql_real_escape_string.
These escape functions take care of any characters that might be malicious, and you will still get your data in the same way you put it in there.
You can also use prepared statements to take care of the data:
Or a little more self explaining:
In case you want to save different types of data, use
bindParam
to define each type, that is, an integer can be defined by:$db->bindParam(':userId', $userId, PDO::PARAM_INT);
. Example:Where
$db
is your PHP data object (PDO). If you're not using one, you might learn more about it at PHP Data Objects.