Hướng dẫn how to sanitize form input in php - cách khử trùng đầu vào biểu mẫu trong php

PHP có các chức năng mới filter_input mới, ví dụ như giải phóng bạn khỏi việc tìm kiếm 'Regex e-mail cuối cùng' Bây giờ có một loại ____2 tích hợp


Lớp lọc của riêng tôi (sử dụng JavaScript để làm nổi bật các trường bị lỗi) có thể được bắt đầu bằng yêu cầu AJAX hoặc bài đăng mẫu bình thường. (Xem ví dụ dưới đây)

/**
 *  Pork.FormValidator
 *  Validates arrays or properties by setting up simple arrays. 
 *  Note that some of the regexes are for dutch input!
 *  Example:
 * 
 *  $validations = array('name' => 'anything','email' => 'email','alias' => 'anything','pwd'=>'anything','gsm' => 'phone','birthdate' => 'date');
 *  $required = array('name', 'email', 'alias', 'pwd');
 *  $sanitize = array('alias');
 *
 *  $validator = new FormValidator($validations, $required, $sanitize);
 *                  
 *  if($validator->validate($_POST))
 *  {
 *      $_POST = $validator->sanitize($_POST);
 *      // now do your saving, $_POST has been sanitized.
 *      die($validator->getScript()."");
 *  }
 *  else
 *  {
 *      die($validator->getScript());
 *  }   
 *  
 * To validate just one element:
 * $validated = new FormValidator()->validate('blah@bla.', 'email');
 * 
 * To sanitize just one element:
 * $sanitized = new FormValidator()->sanitize('blah', 'string');
 * 
 * @package pork
 * @author SchizoDuckie
 * @copyright SchizoDuckie 2008
 * @version 1.0
 * @access public
 */
class FormValidator
{
    public static $regexes = Array(
            'date' => "^[0-9]{1,2}[-/][0-9]{1,2}[-/][0-9]{4}\$",
            'amount' => "^[-]?[0-9]+\$",
            'number' => "^[-]?[0-9,]+\$",
            'alfanum' => "^[0-9a-zA-Z ,.-_\\s\?\!]+\$",
            'not_empty' => "[a-z0-9A-Z]+",
            'words' => "^[A-Za-z]+[A-Za-z \\s]*\$",
            'phone' => "^[0-9]{10,11}\$",
            'zipcode' => "^[1-9][0-9]{3}[a-zA-Z]{2}\$",
            'plate' => "^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}\$",
            'price' => "^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?\$",
            '2digitopt' => "^\d+(\,\d{2})?\$",
            '2digitforce' => "^\d+\,\d\d\$",
            'anything' => "^[\d\D]{1,}\$"
    );
    private $validations, $sanatations, $mandatories, $errors, $corrects, $fields;
    

    public function __construct($validations=array(), $mandatories = array(), $sanatations = array())
    {
        $this->validations = $validations;
        $this->sanitations = $sanitations;
        $this->mandatories = $mandatories;
        $this->errors = array();
        $this->corrects = array();
    }

    /**
     * Validates an array of items (if needed) and returns true or false
     *
     */
    public function validate($items)
    {
        $this->fields = $items;
        $havefailures = false;
        foreach($items as $key=>$val)
        {
            if((strlen($val) == 0 || array_search($key, $this->validations) === false) && array_search($key, $this->mandatories) === false) 
            {
                $this->corrects[] = $key;
                continue;
            }
            $result = self::validateItem($val, $this->validations[$key]);
            if($result === false) {
                $havefailures = true;
                $this->addError($key, $this->validations[$key]);
            }
            else
            {
                $this->corrects[] = $key;
            }
        }
    
        return(!$havefailures);
    }

    /**
     *
     *  Adds unvalidated class to thos elements that are not validated. Removes them from classes that are.
     */
    public function getScript() {
        if(!empty($this->errors))
        {
            $errors = array();
            foreach($this->errors as $key=>$val) { $errors[] = "'INPUT[name={$key}]'"; }

            $output = '$$('.implode(',', $errors).').addClass("unvalidated");'; 
            $output .= "new FormValidator().showMessage();";
        }
        if(!empty($this->corrects))
        {
            $corrects = array();
            foreach($this->corrects as $key) { $corrects[] = "'INPUT[name={$key}]'"; }
            $output .= '$$('.implode(',', $corrects).').removeClass("unvalidated");';   
        }
        $output = "";
        return($output);
    }


    /**
     *
     * Sanitizes an array of items according to the $this->sanitations
     * sanitations will be standard of type string, but can also be specified.
     * For ease of use, this syntax is accepted:
     * $sanitations = array('fieldname', 'otherfieldname'=>'float');
     */
    public function sanitize($items)
    {
        foreach($items as $key=>$val)
        {
            if(array_search($key, $this->sanitations) === false && !array_key_exists($key, $this->sanitations)) continue;
            $items[$key] = self::sanitizeItem($val, $this->validations[$key]);
        }
        return($items);
    }


    /**
     *
     * Adds an error to the errors array.
     */ 
    private function addError($field, $type='string')
    {
        $this->errors[$field] = $type;
    }

    /**
     *
     * Sanitize a single var according to $type.
     * Allows for static calling to allow simple sanitization
     */
    public static function sanitizeItem($var, $type)
    {
        $flags = NULL;
        switch($type)
        {
            case 'url':
                $filter = FILTER_SANITIZE_URL;
            break;
            case 'int':
                $filter = FILTER_SANITIZE_NUMBER_INT;
            break;
            case 'float':
                $filter = FILTER_SANITIZE_NUMBER_FLOAT;
                $flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND;
            break;
            case 'email':
                $var = substr($var, 0, 254);
                $filter = FILTER_SANITIZE_EMAIL;
            break;
            case 'string':
            default:
                $filter = FILTER_SANITIZE_STRING;
                $flags = FILTER_FLAG_NO_ENCODE_QUOTES;
            break;
             
        }
        $output = filter_var($var, $filter, $flags);        
        return($output);
    }
    
    /** 
     *
     * Validates a single var according to $type.
     * Allows for static calling to allow simple validation.
     *
     */
    public static function validateItem($var, $type)
    {
        if(array_key_exists($type, self::$regexes))
        {
            $returnval =  filter_var($var, FILTER_VALIDATE_REGEXP, array("options"=> array("regexp"=>'!'.self::$regexes[$type].'!i'))) !== false;
            return($returnval);
        }
        $filter = false;
        switch($type)
        {
            case 'email':
                $var = substr($var, 0, 254);
                $filter = FILTER_VALIDATE_EMAIL;    
            break;
            case 'int':
                $filter = FILTER_VALIDATE_INT;
            break;
            case 'boolean':
                $filter = FILTER_VALIDATE_BOOLEAN;
            break;
            case 'ip':
                $filter = FILTER_VALIDATE_IP;
            break;
            case 'url':
                $filter = FILTER_VALIDATE_URL;
            break;
        }
        return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false;
    }       
    


}

Tất nhiên, hãy nhớ rằng bạn cần thực hiện truy vấn SQL của mình thoát ra quá tùy thuộc vào loại DB mà bạn đang sử dụng (ví dụ: mysql_real_escape_string () là vô dụng đối với máy chủ SQL). Bạn có thể muốn tự động xử lý việc này tại lớp ứng dụng thích hợp của bạn như ORM. Ngoài ra, như đã đề cập ở trên: Để xuất ra HTML, sử dụng các chức năng chuyên dụng PHP khác như htmlspecialchars;)

Đối với thực sự cho phép đầu vào HTML với các lớp bị tước và/hoặc thẻ phụ thuộc vào một trong các gói xác thực XSS chuyên dụng. Đừng viết regexes của riêng bạn để phân tích HTML!

Làm thế nào để bạn khử trùng các đầu vào hình thức?

Vệ sinh đầu vào của người dùng..
Không cho phép nội dung để bạn hiển thị lỗi nếu người dùng cố gắng gửi nội dung xấu ..
Nội dung thoát nên HTML được hiển thị dưới dạng văn bản. ....
Nội dung sạch để chỉ cho phép HTML an toàn thông qua. ....
Nội dung dải để không cho phép bất kỳ HTML nào cả. ....
Thay thế nội dung để người dùng có thể nhập các thẻ không HTML mà bạn chuyển đổi thành HTML ..

Vệ sinh đầu vào trong PHP là gì?

Vệ sinh dữ liệu có nghĩa là loại bỏ bất kỳ ký tự bất hợp pháp nào khỏi dữ liệu.Vệ sinh đầu vào của người dùng là một trong những tác vụ phổ biến nhất trong một ứng dụng web.Để làm cho nhiệm vụ này dễ dàng hơn, PHP cung cấp tiện ích mở rộng bộ lọc gốc mà bạn có thể sử dụng để vệ sinh dữ liệu như địa chỉ e-mail, URL, địa chỉ IP, v.v.removing any illegal character from the data. Sanitizing user input is one of the most common tasks in a web application. To make this task easier PHP provides native filter extension that you can use to sanitize the data such as e-mail addresses, URLs, IP addresses, etc.

Làm thế nào tôi có thể vệ sinh mã PHP của mình?

Phương pháp vệ sinh đầu vào của người dùng với PHP:..
Sử dụng các phiên bản hiện đại của MySQL và PHP ..
Đặt Charset một cách rõ ràng: $ mysqli-> set_charset ("utf8");thủ công ... .
Sử dụng các ký tự an toàn: ....
Sử dụng chức năng không gian: ....
Kiểm tra biến chứa những gì bạn đang mong đợi:.

Chức năng nào có thể vệ sinh văn bản trong PHP?

Hàm Filter_var () Hàm Filter_var () Chức năng cả xác thực và vệ sinh dữ liệu.filter_var() Function The filter_var() function both validate and sanitize data.