search
HomeBackend DevelopmentPHP TutorialPHP data filtering function and method examples, PHP filtering function examples_PHP tutorial

Examples of php data filtering functions and methods, examples of php filtering functions

1. Basic principles of php submitted data filtering

 1) When submitting variables into the database, we must use addslashes() performs filtering. For example, our injection problem can be solved with just addslashes(). In fact, when it comes to variable values, the intval() function is also a good choice for filtering strings.

2) Enable magic_quotes_gpc and magic_quotes_runtime in php.ini. magic_quotes_gpc can change the quotation marks in get, post, and cookie into slashes. magic_quotes_runtime can play a formatting role in data entering and exiting the database. In fact, this parameter was very popular back in the old days when injection was crazy.

3) When using system functions, you must use escapeshellarg() and escapeshellcmd() parameters to filter, so that you can use system functions with confidence.

4) For cross-site, the two parameters of strip_tags() and htmlspecialchars() are both good. All tags with html and php submitted by users will be converted. For example, angle brackets "
The code is as follows Copy the code

$new = htmlspecialchars("Test", ENT_QUOTES);

strip_tags($text,);

5) For Filtering of related functions, just like the previous include(), unlink, fopen(), etc., as long as you specify the variables you want to perform the operation or filter the related characters strictly, I think this will be impeccable.

2. PHP simple data filtering

1) Inbound: trim($str), addslashes($str)

2) Outbound: stripslashes($str )

 3) Display: htmlspecialchars(nl2br($str))

Look at the example below for further discussion of dispatch.php script:

The code is as follows Copy the code

  /* 全局安全处理 */

  switch ($_GET['task'])

  {

  case 'print_form':

  include '/inc/presentation/form.inc';

  break;

  case 'process_form':

  $form_valid = false;

  include '/inc/logic/process.inc';

  if ($form_valid)

  {

  include '/inc/presentation/end.inc';

  }

  else

  {

  include '/inc/presentation/form.inc';

  }

  break;

  default:

  include '/inc/presentation/index.inc';

  break;

  }

  ?>

 



If this is the only publicly accessible PHP script, you can be sure that the program is designed to ensure that the initial global security handling cannot be bypassed. It also makes it easy for developers to see the control flow of specific tasks. For example, it is easy to know without browsing the entire code: when $form_valid is true, end.inc is the only one displayed to the user; since it is before process.inc is included and has just been initialized to false, it can be determined that The internal logic of process.inc will set it to true; otherwise the form will be displayed again (possibly with an associated error message).

Note

If you use a directory directive file such as index.php (instead of dispatch.php), you can use the URL address like this: http://example.org/?task= print_form.

You can also use ApacheForceType redirection or mod_rewrite to adjust the URL address: http://example.org/app/print-form.

Containing methods

Another way is to use a single module, which is responsible for all security processing. This module is included at the front (or very front) of all public PHP scripts. Refer to the following script security.inc

The code is as follows Copy the code

switch ($_POST['form'])

  {

  case 'login':

  $allowed = array();

  $allowed[] = 'form';

  $allowed[] = 'username';

  $allowed[] = 'password';

  $sent = array_keys($_POST);

  if ($allowed == $sent)

  {

  include '/inc/logic/process.inc';

  }

  break;

  }

  ?>

 


In this example, each submitted form is considered to contain the unique verification value form, and security.inc independently processes the data in the form that needs to be filtered. The HTML form that implements this requirement is as follows:

Copy the code as follows

Username:

Password:

An array called $allowed is used for verification Which form variables are allowed? This list should be consistent before the form is processed. Process control decides what to execute, and process.inc is where the actual filtered data arrives.

NOTE

A better way to ensure that security.inc is always included at the beginning of every script is to use the auto_prepend_file setting.

Example of filtering

Creating a whitelist is very important for data filtering. Since it's impossible to give examples for every type of form data you may encounter, some examples can help you get a general understanding.

The following code verifies the email address:

The code is as follows Copy the code

$clean = array();

  $email_pattern = '/^[^@s<&>]+@([-a-z0-9]+.)+[a-z]{2,}$/i';

  if (preg_match($email_pattern, $_POST['email'])) {

  $clean['email'] = $_POST['email'];

  }

  ?>

 



The following code ensures that the content of $_POST['color'] is red, green, or blue:

The code is as follows Copy the code

 $clean = array();

  switch ($_POST['color']) {

  case 'red':

  case 'green':

  case 'blue':

  $clean['color'] = $_POST['color'];

  break;

  }

  ?>

 



The following code ensures that $_POST['num'] is an integer:

The code is as follows Copy the code

     
    $clean = array();

  if ($_POST['num'] == strval(intval($_POST['num']))) {

  $clean['num'] = $_POST['num'];

  }

 



The following code ensures that $_POST['num'] is a floating point number (float):

The code is as follows Copy the code

$clean = array();

  if ($_POST['num'] == strval(floatval($_POST['num'])))

  {

  $clean['num'] = $_POST['num'];

  }

 



  ?>

  名字转换

  之前每个例子都使用了数组$clean。对于开发人员判断数据是否有潜在的威胁这是一个很好的习惯。 永远不要在对数据验证后还将其保存在$_POST或者$_GET中,作为开发人员对超级全局数组中保存的数据总是应当保持充分的怀疑。

  需要补充的是,使用$clean可以帮助思考还有什么没有被过滤,这更类似一个白名单的作用。可以提升安全的等级。

  如果仅仅将验证过的数据保存在$clean,在数据验证上仅存的风险是你所引用的数组元素不存在,而不是未过滤的危险数据。

  时机

  一旦 PHP 脚本开始执行,则意味着 HTTP 请求已经全部结束。此时,用户便没有机会向脚本发送数据。因此,没有数据可以被输入到脚本中(甚至register_globals被开启的情况下)。这就是为什么初始化变量是非常好的习惯。

  防注入

  
代码如下 复制代码

  //PHP整站防注入程序,需要在公共文件中require_once本文件

  //判断magic_quotes_gpc状态

  if (@get_magic_quotes_gpc ()) {

  $_GET = sec ( $_GET );

  $_POST = sec ( $_POST );

  $_COOKIE = sec ( $_COOKIE );

  $_FILES = sec ( $_FILES );

  }

  $_SERVER = sec ( $_SERVER );

  function sec(&$array) {

  //如果是数组,遍历数组,递归调用

  if (is_array ( $array )) {

  foreach ( $array as $k => $v ) {

  $array [$k] = sec ( $v );

  }

  } else if (is_string ( $array )) {

  //使用addslashes函数来处理

  $array = addslashes ( $array );

  } else if (is_numeric ( $array )) {

  $array = intval ( $array );

  }

  return $array;

  }

  //整型过滤函数

  function num_check($id) {

  if (! $id) {

  die ( '参数不能为空!' );

  } //是否为空的判断

  else if (inject_check ( $id )) {

  die ( '非法参数' );

  } //注入判断

  else if (! is_numetic ( $id )) {

  die ( '非法参数' );

  }

  //数字判断

  $id = intval ( $id );

  //整型化

  return $id;

  }

  //字符过滤函数

  function str_check($str) {

  if (inject_check ( $str )) {

  die ( '非法参数' );

  }

  //注入判断

  $str = htmlspecialchars ( $str );

  //转换html

  return $str;

  }

  function search_check($str) {

  $str = str_replace ( "_", "_", $str );

  //把"_"过滤掉

  $str = str_replace ( "%", "%", $str );

  //把"%"过滤掉

  $str = htmlspecialchars ( $str );

  //转换html

  return $str;

  }

  //表单过滤函数

  function post_check($str, $min, $max) {

  if (isset ( $min ) && strlen ( $str ) < $min) {

  die ( '最少$min字节' );

  } else if (isset ( $max ) && strlen ( $str ) > $max) {

  die ( '最多$max字节' );

  }

  return stripslashes_array ( $str );

  }

  //防注入函数

  function inject_check($sql_str) {

  return eregi ( 'select|inert|update|delete|'|/*|*|../|./|UNION|into|load_file|outfile', $sql_str );

  //进行过滤,防注入

  }

  function stripslashes_array(&$array) {

  if (is_array ( $array )) {

  foreach ( $array as $k => $v ) {

  $array [$k] = stripslashes_array ( $v );

  }

  } else if (is_string ( $array )) {

  $array = stripslashes ( $array );

  }

  return $array;

  }

  ?>

  



 

php表单获取用户输入数据后过滤的流程

addslashes
htmlspecialchars

mysql_real_escape_string
数字的可以用intval(),最好在之前就循环$_POST,挨个的addslashes或者其他函数。
上面都可以,根据需要来。
 

php过滤数据问题

假定你的数据在数据$demo中,我们来写段代码进行过滤。
$count = 0;
foreach($demo as $ditem){
if(($ditem['a']==0)||($ditem['b']==0)||($ditem['c']==0)||($ditem['c']==0)) continue;
echo $ditem['id'].' '.$ditem['a'].' '.$ditem['b'].' '.$ditem['c'].' '.$ditem['d'].' '.$ditem['e']."
";
$count++;

}
echo '总行数:'.$count;
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/908127.htmlTechArticlephp数据过滤函数与方法示例,php过滤函数示例 1、php提交数据过滤的基本原则 1)提交变量进数据库时,我们必须使用addslashes()进行过滤,像...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment