- Saved searches
- Use saved searches to filter your results more quickly
- pierreet/Form-Class
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- PHP Form Validation
- PHP Form Validation
- Text Fields
- Radio Buttons
- The Form Element
- Big Note on PHP Form Security
- How To Avoid $_SERVER[«PHP_SELF»] Exploits?
- Validate Form Data With PHP
- Example
- Php form class with validation
- WordPress 6 с Нуля до Гуру
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A php class which helps you to build and validate form
pierreet/Form-Class
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Form is a library which helps you build and validate forms.
To create and display a new form object you just have to instanciate the class
include 'form.class.php'; $form = new Form('unique_id'); echo $form;
form method pl-s">GET"> p> input name pl-s">uniqid" type pl-s">hidden" value pl-s">unique_id" /> p> form>
You can change method and/or action this way
include 'form.class.php'; $form = new Form('unique_id'); $form->method('POST'); $form->action('index.php'); echo $form;
include 'form.class.php'; $form = new Form('unique_id', 'POST'); $form->action('index.php'); echo $form;
form method pl-s">POST" action pl-s">index.php"> p> input name pl-s">uniqid" type pl-s">hidden" value pl-s">unique_id" /> p> form>
You can add fields by using the method add(‘type’, ‘name’) . E.g.:
include 'form.class.php'; $form = new Form('unique_id', 'POST'); $form->action('index.php'); $form->add('Text', 'name'); echo $form;
form method pl-s">POST"> p> input name pl-s">name" type pl-s">text" /> p> p> input name pl-s">uniqid" type pl-s">hidden" value pl-s">unique_id" /> p> form>
include 'form.class.php'; $form = new Form('unique_id', 'POST'); $form->action('index.php'); $form->add('Text', 'name'); ->label('Your name'); echo $form;
form method pl-s">POST"> p> label id pl-s">id_name">Your namelabel> input for pl-s">id_name" name pl-s">name" type pl-s">text" /> p> p> input name pl-s">uniqid" type pl-s">hidden" value pl-s">unique_id" /> p> form>
- single line text : Text
- multi lines text : Textarea
- password : Password
- hidden field : Hidden
- validate button : Submit
- button : Button
- radio button : Radio
- select option : Select
- checkbox : Checkbox
- file upload : File
- e-mail address : Email
- date / time : Date
- captcha : Captcha
This will render an field.
This will render an field. You can specify the size with rows() and cols() methods : $form->add(‘Textarea’, ‘comment’)->rows(15)->cols(74); .
This will render an button.
This will render an button.
This will render field. You can specify the list of choices with the choices() method: $form->add(‘Radio’, ‘sex’)->choices(array(‘m’ => ‘Male’,’f’ => ‘Female’));
This will render an fields. As for the radio button you have the choices() method :
$form->add('Select', 'country') ->choices(array( 'Europe' => array( 'fr' => 'France', 'de' => 'Germany' ), 'Asia' => array( 'cn' => 'China', 'jp' => 'Japan' ) ));
This will render an field. You can specify the maximum size and the extensions authorized like this:
$form->add('File', 'avatar') ->max_size(4096) //=> 4kb ->extensions(array('jpg', 'gif', 'png'));
This will render an field. When the form will be submitted the field won’t be validated if the address entered is not a valid one.
This will render an field. As for the e-mail field the form won’t be validated if the date isn’t correct. You need to specify the format of the date with the method format : $form->add(‘Date’, ‘date’)->format(‘mm/dd/yyyy’); Supported formats are the following:
This will render an field with an image. To validate this field user will have to copy the text which is in the image into the field.
There is other methods that exists for all the field:
- required(bool) : Specify if the field is required to validate the form (default true)
- autocomplete(bool) : Display the autocomplete HTML property (default false)
- maxlength(int) : Specify the maximum length that can have a text field
- minlength(int) : Specify the minimum length that can have a text field
- javascript(string) : Allow to add some javascript code (ie: onclick, . ) to the field (actually you can add anything you want, eg: other html attributes)
There is other methods for the form object:
You can fill the form with the method bound(array) : E.g.:
To check if the form is valid you have the method : bool is_valid(array) . This will return true if all fields are correctly filled with the data in the array. To retrieve fields values the method is : get_cleaned_data(array | string [, string [, . ]]) . This will return the value of the listed fields. E.g.:
if($form->is_valid($_POST))< list($name, $country) = $form->get_cleaned_data('name', 'country'); echo 'Your name is: '.$name; >
This class is licensed under the LGPL public license
About
A php class which helps you to build and validate form
PHP Form Validation
This and the next chapters show how to use PHP to validate form data.
PHP Form Validation
Think SECURITY when processing PHP forms!
These pages will show how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers!
The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:
The validation rules for the form above are as follows:
Field | Validation Rules |
---|---|
Name | Required. + Must only contain letters and whitespace |
Required. + Must contain a valid email address (with @ and .) | |
Website | Optional. If present, it must contain a valid URL |
Comment | Optional. Multi-line input field (textarea) |
Gender | Required. Must select one |
First we will look at the plain HTML code for the form:
Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this:
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
The Form Element
The HTML code of the form looks like this:
When the form is submitted, the form data is sent with method=»post».
What is the $_SERVER[«PHP_SELF»] variable?
The $_SERVER[«PHP_SELF»] is a super global variable that returns the filename of the currently executing script.
So, the $_SERVER[«PHP_SELF»] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form.
What is the htmlspecialchars() function?
The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and >with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
Big Note on PHP Form Security
The $_SERVER[«PHP_SELF»] variable can be used by hackers!
If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users.
Assume we have the following form in a page named «test_form.php»:
Now, if a user enters the normal URL in the address bar like «http://www.example.com/test_form.php», the above code will be translated to:
However, consider that a user enters the following URL in the address bar:
In this case, the above code will be translated to:
This code adds a script tag and an alert command. And when the page loads, the JavaScript code will be executed (the user will see an alert box). This is just a simple and harmless example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the tag! A hacker can redirect the user to a file on another server, and that file can hold malicious code that can alter the global variables or submit the form to another address to save the user data, for example.
How To Avoid $_SERVER[«PHP_SELF»] Exploits?
$_SERVER[«PHP_SELF»] exploits can be avoided by using the htmlspecialchars() function.
The form code should look like this:
The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries to exploit the PHP_SELF variable, it will result in the following output:
The exploit attempt fails, and no harm is done!
Validate Form Data With PHP
The first thing we will do is to pass all variables through PHP’s htmlspecialchars() function.
When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:
— this would not be executed, because it would be saved as HTML escaped code, like this:
The code is now safe to be displayed on a page or inside an e-mail.
We will also do two more things when the user submits the form:
- Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
- Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again).
We will name the function test_input().
Now, we can check each $_POST variable with the test_input() function, and the script looks like this:
Example
// define variables and set to empty values
$name = $email = $gender = $comment = $website = «»;
?php
if ($_SERVER[«REQUEST_METHOD»] == «POST») $name = test_input($_POST[«name»]);
$email = test_input($_POST[«email»]);
$website = test_input($_POST[«website»]);
$comment = test_input($_POST[«comment»]);
$gender = test_input($_POST[«gender»]);
>
function test_input($data) $data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
>
?>
Notice that at the start of the script, we check whether the form has been submitted using $_SERVER[«REQUEST_METHOD»]. If the REQUEST_METHOD is POST, then the form has been submitted — and it should be validated. If it has not been submitted, skip the validation and display a blank form.
However, in the example above, all input fields are optional. The script works fine even if the user does not enter any data.
The next step is to make input fields required and create error messages if needed.
Php form class with validation
WordPress 6 с Нуля до Гуру
Этот курс научит Вас созданию самых разных сайтов на самой популярной в мире CMS — WordPress. Вы увидите установку и настройку локального сервера, разбор каждой настройки, каждой кнопки и каждого пункта меню в панели WordPress.
Также Вы получите и всю практику, поскольку прямо в курсе с нуля создаётся полноценный Интернет-магазин, который затем публикуется в Интернете. И всё это прямо на Ваших глазах.
Помимо уроков к курсу идут упражнения для закрепления материала.
И, наконец, к курсу идёт ценнейший Бонус по тому, как используя ChatGPT и создавая контент для сайта, можно выйти на пассивный доход. Вы наглядно увидите, как зарегистрироваться в ChatGPT (в том числе, и если Вы из России), как правильно выбрать тему для сайта, как правильно генерировать статьи для него(чтобы они индексировались поисковыми системами) и как правильно монетизировать трафик на сайте.
Подпишитесь на мой канал на YouTube, где я регулярно публикую новые видео.
Подписаться
Подписавшись по E-mail, Вы будете получать уведомления о новых статьях.
Подписаться
Добавляйтесь ко мне в друзья ВКонтакте! Отзывы о сайте и обо мне оставляйте в моей группе.
Мой аккаунт Моя группа
Какая тема Вас интересует больше?