Protecting Special Characters in Query String in PHP


How To Protect Special Characters in Query String in PHP?



If you want to include special characters like spaces in the query string, you need to protect them by applying the urlencode() translation function. The script below shows how to use urlencode():

  print("<p>Please click the links below"
    ." to submit comments about</p>");
  $comment = 'I want to say: "It\'s a good site! :->"';
  $comment = urlencode($comment);
    ."<a href=\"processing_forms.php?name=Guest&comment=$comment\">"
    ."It's an excellent site!</a></p>");
  $comment = 'This visitor said: "It\'s an average site! :-("';
  $comment = urlencode($comment);
    .'<a href="processing_forms.php?'.$comment.'">'
    ."It's an average site.</a></p>");

If you copy this script as submit_comments.php to your Web server, and click the first link, you will get:

  query_string = name=Guest&comment=
Number of values: 2
  name = Guest
  comment = I want to say: "It's a good site! :->"

If you click the second link, you will get:

    = This+visitor+said%3A+%22It%27s+an+average+site%21+%3A-%28%22
Number of values: 1
  This_visitor_said:_\"It\'s_an_average_site!_:-(\" = 

Now you know that urlencode() all special characters into HEX numbers. To translate them back, you need to apply urldecode().


Processing Web Forms in PHP

⇒⇒PHP Tutorials

2016-11-05, 253👍, 0💬