jshuter / php-form-builder-class

Automatically exported from code.google.com/p/php-form-builder-class
GNU General Public License v3.0
0 stars 0 forks source link

New element : Validation\Select to enhance security #194

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
I propose this pieces of code to enhance the security on Select elements.

============
// PFBC\Element\Select (adding 3 lines)

class Select extends \PFBC\OptionElement {
    protected $_attributes = array();

    public function render() { 
        if(isset($this->_attributes["value"])) {
            if(!is_array($this->_attributes["value"]))
                $this->_attributes["value"] = array($this->_attributes["value"]);
        }
        else
            $this->_attributes["value"] = array();

        if(!empty($this->_attributes["multiple"]) && substr($this->_attributes["name"], -2) != "[]")
            $this->_attributes["name"] .= "[]";

        echo '<select', $this->getAttributes(array("value", "selected")), '>';
        $selected = false;
        $list_of_authorized_values = array();
        foreach($this->options as $value => $text) {
            $value = $this->getOptionValue($value);
            $list_of_authorized_values[] = $value;
            echo '<option value="', $this->filter($value), '"';
            if(!$selected && in_array($value, $this->_attributes["value"])) {
                echo ' selected="selected"';
                $selected = true;
            }   
            echo '>', $text, '</option>';
        }   
        echo '</select>';

        $this->validation[] = new \PFBC\Validation\Select($list_of_authorized_values);
    }
}

===========
// PFBC\Validation\Select (new Validation class)

namespace PFBC\Validation;

class Select extends \PFBC\Validation {
    protected $message = "Error: %element%, the returned value does not match any proposed values."; // or a better sentence...
    protected $list_of_authorized_values = array();

    public function __construct ($list) {
        $this->list_of_authorized_values = $list;
    }

    public function isValid($value) {
        if(in_array($value, $this->list_of_authorized_values))
            return true;
        return false;
    }
}

Original issue reported on code.google.com by nrenv...@finindev.com on 5 Feb 2013 at 4:51