Home PHP Security: Sanitizing Strings, Validating Values, and Interrogating Integers

PHP Security: Sanitizing Strings, Validating Values, and Interrogating Integers

Trust no-one. Not just a tag-line for The X-Files, it’s also sound advice when dealing with data supplied by users.

Whether a user is trying to do something nasty or they’ve just hit an unfortunate combination of keys, you shouldn’t assume that what you’re saving is trouble-free. Here are some tips for validating input in your PHP application.

Numbers Only

Zend Framework has a handy class called Zend_Filter_Int that will take a value and strip out any non-numeric characters. Or, you could do something like this:

$output = preg_replace("/[^0-9-.]/", "", $data);

This will allow negative numbers and decimal points.

Strip Tags, Display Tags

Don’t want any HTML? Use strip_tags. If you’d prefer to display HTML tags so a user can share a code snippet, use htmlspecialchars and the code won’t be parsed.

Escaping Strings in MySQL

Use mysql_real_escape_string to escape strings before sending them to MySQL. Or, use PDO and bind values to fields.

Use filter_input

Instead of using $_GET[‘id’], how about using filter_input instead?

$itemId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_SPECIAL_CHARS);


What other methods do you use for sanitizing user input?

Photo by dheuer

About ReadWrite’s Editorial Process

The ReadWrite Editorial policy involves closely monitoring the tech industry for major developments, new product launches, AI breakthroughs, video game releases and other newsworthy events. Editors assign relevant stories to staff writers or freelance contributors with expertise in each particular topic area. Before publication, articles go through a rigorous round of editing for accuracy, clarity, and to ensure adherence to ReadWrite's style guidelines.

Get the biggest tech headlines of the day delivered to your inbox

    By signing up, you agree to our Terms and Privacy Policy. Unsubscribe anytime.

    Tech News

    Explore the latest in tech with our Tech News. We cut through the noise for concise, relevant updates, keeping you informed about the rapidly evolving tech landscape with curated content that separates signal from noise.

    In-Depth Tech Stories

    Explore tech impact in In-Depth Stories. Narrative data journalism offers comprehensive analyses, revealing stories behind data. Understand industry trends for a deeper perspective on tech's intricate relationships with society.

    Expert Reviews

    Empower decisions with Expert Reviews, merging industry expertise and insightful analysis. Delve into tech intricacies, get the best deals, and stay ahead with our trustworthy guide to navigating the ever-changing tech market.