How to Check a String for Bad Characters in PHP

There are many instances when a Web developer needs her PHP script to check incoming data to ensure that it uses valid characters. Not only do passwords and user names each have valid character requirements, but basic security dictates that a developer keep a watchful eye on incoming data. For example, in a script that calls terminal commands, some characters such as ">" and "|" have special meanings on the terminal, and failure to strip them from code can provide hackers with an easy way to run malicious code on the server. The key to all these tasks is the PHP "preg_match" command, which stands for "PHP regular expression matching."

Instructions

    • 1

      Open a text editor or your favorite PHP Integrated Development Environment.

    • 2

      Paste the following script:

      <?php

      $input = "This is some bad input for a user name because of all these odd characters: #@$#%$.";

      $valid = preg_match('/[a-zA-Z0-9]/', $input);

      if ($valid) echo "Valid user name!"'

      else echo "Invalid user name!";

      ?>

      This simple script uses regex syntax to specify that a username must contain uppercase or lowercase letters or numbers. The square brackets in an expression tell PHP that any of the characters within are acceptable. If the string uses anything else, such as punctuation, the "$valid" variable will be set to false and the program will print a message to the standard output letting the user know that his user name is invalid.

    • 3

      Save your work.

Tips & Warnings

  • Regular expressions can be a difficult topic to learn, but they are the tool of choice for performing complex text searching. You can read more about regular expressions at the first resource.

  • You can specify unacceptable characters by adding an exclamation mark to the pattern, like so: "[!a-z]". This pattern would forbid lowercase letters.

  • Many punctuation symbols have special meanings in regex. In particular, the "." stands for "any character" in regular expression syntax. In order to specify literal punctuation marks as valid, you must prefix them with the backslash character, like so: "\."

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured