Sanitizer
The best way to secure your code is to check user input. While most functions provided by PHP are focused on
checking for the presense of potentially dangerous characters, Sanitizer simply strips all characters in a string that
are not explicitly permitted. This way you can be sure of what your input contains. Available under the GNU General Public License.
You can download this file or view the source below.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11
|
<?php
require 'sanitizer.php';
$input = "298 Forest AVE :)"; $input = sanitize($input, ' ');
echo $input;
?>
|
Source:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
<?php
/* * * sanitizer.php Sanitizer (Explicit input checking: Better security, less code.) * Copyright (C) 2009, Ray Patrick Soucy * * Revision: 1 * Modified: 2009-03-13 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */
function sanitize($string, $allowed = '', $allow_aZ = true, $allow_09 = true) {
/* * * Utility function for sanitize, check if a char is in a string. * Nested functions are unique to PHP, may look odd, but useful. */ function charin($c, $s) { $result = false; for ($i = 0; $i < strlen($s); $i++) { if ($c == $s[$i]) { $result = true; break; } // if } // for return $result; } // charin
/* Check flags for a-Z and 0-9, on by default. */ if ($allow_aZ) $allowed .= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; if ($allow_09) $allowed .= '0123456789';
$result = '';
for ($i = 0; $i < strlen($string); $i++) { if (charin($string[$i], $allowed)) { $result .= $string[$i]; } // if } // for
return $result;
} // sanitize
?>
|
Ray Soucy works as a Communications Specialist for the University of Maine System.
The views expressed herein are those of the author and do not necessarily reflect those of the University of Maine System.
This site is published by Ray Soucy, 239 Forest Avenue, Orono, ME, 04473.
Copyright © 2009, by Ray Patrick Soucy.
Previous editions © 2004, 2005, 2006, 2007, and 2008.
Verbatim copying and distribution of this site is permitted for non-commercial use provided this notice is preserved.
All other rights reserved.
This page was accessed on 2012-02-07 06:07:43 EST by 38.107.179.237