post/Form.php

56 lines
1.2 KiB
PHP
Raw Permalink Normal View History

2019-08-14 19:22:54 +02:00
<?php
namespace Post;
class Form {
public $fields;
public $action;
public function __construct($fields) {
$this->fields=$fields;
}
public function denyCsrf() {
$this->fields["_csrf"]=new HiddenFormField();
$this->fields["_csrf"]->setValue($this->getCsrfToken());
}
public function getEnctype() {
foreach ($this->fields as $name=>$field) {
if ($field instanceof FileUpload) {
return "multipart/form-data";
}
}
return "application/x-www-form-urlencoded";
}
public function reset() {
foreach ($this->fields as $name=>$field) {
$field->reset();
}
}
public function preseedFromUrl() {
foreach ($this->fields as $name=>$field) {
if (isset($_GET[$name])) {
$field->setValue($_GET[$name]);
}
}
}
2019-08-14 19:22:54 +02:00
public function loadFromEnv() {
foreach ($this->fields as $name=>$field) {
$field->loadFromEnv($name);
}
if (isset($this->fields['_csrf']) && $this->fields['_csrf']->getValue() !== $this->getCsrfToken()) {
throw new CsrfException();
}
}
public static function getCsrfToken() {
if (!isset($_SESSION['csrf'])) {
$_SESSION['csrf']=bin2hex(openssl_random_pseudo_bytes(16));
}
return $_SESSION['csrf'];
}
}