Escape strings issue universal fix

Escape strings #onebigissue in programming, My solution works for all.

Say I have a textarea field “notes”


To encode all the special characters for passing the data, you’ll need to use “encodeURIComponent()”.
The encodeURIComponent doesn’t encode ~!*()’
To encode the remaining i have a function to replace single quotes in an encoded string.

function encodeURIComponentReplace(encodeString){
  //encodeURIComponent() will not encode: ~!*()' - use this function to do the job	
  var intIndexOfMatch = encodeString.indexOf( "'" );
  while (intIndexOfMatch != -1){
    encodeString = encodeString.replace( "'", "%27" )
    intIndexOfMatch = encodeString.indexOf( "'" );
  }
  return encodeString;
}

If you send the parameters in GET method to PHP backend,
you’ll receive parameter values with added slashes.
You should strip slashes and convert the htmlentities before database insert/update.

PHP:
$notes=htmlspecialchars(stripslashes($notes),ENT_QUOTES);

If you send the parameters in POST method you do not have to do the above step.

Retrieving the data from the database using PHP.

If you are simply echoing values from the database to front-end use the following PHP code:
$notes=rawurldecode(htmlspecialchars_decode($notes,ENT_QUOTES));

If you are sending values in a json array do the following before encoding:
$notes=rawurldecode($notes);
then json_encode the output array.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s