PHP 清理数据
我是编码和 PHP 领域的新手,因此想了解清理表单数据以避免格式错误的页面、代码注入等的最佳方法。我在下面找到的示例脚本是一个很好的例子吗?
代码最初发布于 http://codeassemble.com/How-to-sanitize-你的-php-输入/
/**
* Sanitize only one variable .
* Returns the variable sanitized according to the desired type or true/false
* for certain data types if the variable does not correspond to the given data type.
*
* NOTE: True/False is returned only for telephone, pin, id_card data types
*
* @param mixed The variable itself
* @param string A string containing the desired variable type
* @return The sanitized variable or true/false
*/
function sanitizeOne($var, $type)
{
switch ( $type ) {
case 'int': // integer
$var = (int) $var;
break;
case 'str': // trim string
$var = trim ( $var );
break;
case 'nohtml': // trim string, no HTML allowed
$var = htmlentities ( trim ( $var ), ENT_QUOTES );
break;
case 'plain': // trim string, no HTML allowed, plain text
$var = htmlentities ( trim ( $var ) , ENT_NOQUOTES ) ;
break;
case 'upper_word': // trim string, upper case words
$var = ucwords ( strtolower ( trim ( $var ) ) );
break;
case 'ucfirst': // trim string, upper case first word
$var = ucfirst ( strtolower ( trim ( $var ) ) );
break;
case 'lower': // trim string, lower case words
$var = strtolower ( trim ( $var ) );
break;
case 'urle': // trim string, url encoded
$var = urlencode ( trim ( $var ) );
break;
case 'trim_urle': // trim string, url decoded
$var = urldecode ( trim ( $var ) );
break;
case 'telephone': // True/False for a telephone number
$size = strlen ($var) ;
for ($x=0;$x<$size;$x++)
{
if ( ! ( ( ctype_digit($var[$x] ) || ($var[$x]=='+') || ($var[$x]=='*') || ($var[$x]=='p')) ) )
{
return false;
}
}
return true;
break;
case 'pin': // True/False for a PIN
if ( (strlen($var) != 13) || (ctype_digit($var)!=true) )
{
return false;
}
return true;
break;
case 'id_card': // True/False for an ID CARD
if ( (ctype_alpha( substr( $var , 0 , 2) ) != true ) || (ctype_digit( substr( $var , 2 , 6) ) != true ) || ( strlen($var) != 8))
{
return false;
}
return true;
break;
case 'sql': // True/False if the given string is SQL injection safe
// insert code here, I usually use ADODB -> qstr() but depending on your needs you can use mysql_real_escape();
return mysql_real_escape_string($var);
break;
}
return $var;
}
I am new to the world of coding and PHP hence would like to learn what's the best way to sanitize form data to avoid malformed pages, code injections and the like. Is the sample script I found below a good example?
Code originally posted at http://codeassembly.com/How-to-sanitize-your-php-input/
/**
* Sanitize only one variable .
* Returns the variable sanitized according to the desired type or true/false
* for certain data types if the variable does not correspond to the given data type.
*
* NOTE: True/False is returned only for telephone, pin, id_card data types
*
* @param mixed The variable itself
* @param string A string containing the desired variable type
* @return The sanitized variable or true/false
*/
function sanitizeOne($var, $type)
{
switch ( $type ) {
case 'int': // integer
$var = (int) $var;
break;
case 'str': // trim string
$var = trim ( $var );
break;
case 'nohtml': // trim string, no HTML allowed
$var = htmlentities ( trim ( $var ), ENT_QUOTES );
break;
case 'plain': // trim string, no HTML allowed, plain text
$var = htmlentities ( trim ( $var ) , ENT_NOQUOTES ) ;
break;
case 'upper_word': // trim string, upper case words
$var = ucwords ( strtolower ( trim ( $var ) ) );
break;
case 'ucfirst': // trim string, upper case first word
$var = ucfirst ( strtolower ( trim ( $var ) ) );
break;
case 'lower': // trim string, lower case words
$var = strtolower ( trim ( $var ) );
break;
case 'urle': // trim string, url encoded
$var = urlencode ( trim ( $var ) );
break;
case 'trim_urle': // trim string, url decoded
$var = urldecode ( trim ( $var ) );
break;
case 'telephone': // True/False for a telephone number
$size = strlen ($var) ;
for ($x=0;$x<$size;$x++)
{
if ( ! ( ( ctype_digit($var[$x] ) || ($var[$x]=='+') || ($var[$x]=='*') || ($var[$x]=='p')) ) )
{
return false;
}
}
return true;
break;
case 'pin': // True/False for a PIN
if ( (strlen($var) != 13) || (ctype_digit($var)!=true) )
{
return false;
}
return true;
break;
case 'id_card': // True/False for an ID CARD
if ( (ctype_alpha( substr( $var , 0 , 2) ) != true ) || (ctype_digit( substr( $var , 2 , 6) ) != true ) || ( strlen($var) != 8))
{
return false;
}
return true;
break;
case 'sql': // True/False if the given string is SQL injection safe
// insert code here, I usually use ADODB -> qstr() but depending on your needs you can use mysql_real_escape();
return mysql_real_escape_string($var);
break;
}
return $var;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该脚本有一些不错的功能,但它在清理方面做得不好!
根据您需要(并想要接受)的内容,您可以使用:
< code>abs() 表示正数(注意它也接受浮点数)
preg_replace
('/[^a-zA-Z0- 9 .-]/','',$var)
用于清除字符串中的所有特殊字符,或preg_replace('/\D/','',$var)
删除所有特殊字符非数字字符ctype_* 函数
例如。ctype_digit($var)
filter_var()
和filter_input ()
函数<一个href="http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting" rel="noreferrer">类型转换 例如。
(int)$_GET['id']
转换例如。
$id=$_GET['id']+0;
That script has some nice functions but it doesn't do a good job at sanitizing!
Depending on what you need (and want to accept) you can use:
abs()
for positive numbers (note that it accepts floats also)preg_replace
('/[^a-zA-Z0-9 .-]/','',$var)
for cleaning out any special characters from strings orpreg_replace('/\D/','',$var)
to remove all non-digit charactersctype_* functions
eg.ctype_digit($var)
filter_var()
andfilter_input()
functionstype-cast eg.
(int)$_GET['id']
convert eg.
$id=$_GET['id']+0;
您的示例脚本不太好 - 所谓的字符串清理只是修剪两端的空格。依赖它很快就会给你带来很多麻烦。
没有一种万能的解决方案。您需要为您的应用程序应用正确的清理,这完全取决于您需要什么输入以及它的使用位置。在任何情况下,您都应该在多个级别上进行清理 - 最有可能是在接收数据时、存储数据时以及渲染数据时。
值得一读,可能的欺骗:
什么是最好的消毒方法用户使用 PHP 输入?
Clean & PHP 中的安全字符串
Your example script isn't great - the so called sanitisation of a string just trims whitespace off each end. Relying on that would get you in a lot of trouble fast.
There isn't a one size fits all solution. You need to apply the right sanitisation for your application, which will completely depend on what input you need and where it's being used. And you should sanitise at multiple levels in any case - most likely when you receive data, when you store it and possibly when you render it.
Worth reading, possible dupes:
What's the best method for sanitizing user input with PHP?
Clean & Safe string in PHP
作为一般规则,如果您使用 PHP 和MySQL 您需要像这样清理进入 MySQL 的数据:
http: //php.net/manual/en/function.mysql-real-escape-string.php
As a general rule if you are using PHP & MySQL you will want to sanitize data going into MySQL like so:
http://php.net/manual/en/function.mysql-real-escape-string.php
这还不错。
对于 SQL,最好通过使用 PDO 将参数插入查询来完全避免这种情况的风险。
It's not bad.
For SQL, it'd be best to avoid the need to risk the scenario at all, by using PDO to insert parameters into your queries.