Робота з формами

Одна з самих потужних особливостей PHP - це її спосіб обробки HTML форм. Важливо знати, що будь-який елемент форми автоматично стає доступним для скрипта PHP. Детальнішу інформацію та приклади використання форм в PHP, можна прочитати в розділі Змінні, отримані із зовнішніх джерел . Тут ми продемонструємо приклади HTML форм:

Приклад #1 Проста HTML форма

<form action="action.php" method="post">
 <p>Ваше ім'я: <input type="text" name="name" /></p>
 <p>Ваш вік: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>

В цій формі немає нічого особливого. Це звичайна HTML форма без будь-яких спеціальних тегів. Коли користувач заповнить цю форму і натисне кнопку відправки, буде викликано сторінку action.php. В цьому файлі можна написати щось таке:

Приклад #2 Друк даних з нашої форми

Привіт, <?php echo htmlspecialchars($_POST['name']); ?>.
Вам <?php echo (int)$_POST['age']; ?> років.

Зразок видачі цього скрипта:

Привіт, Костя. Вам 34 роки.

Записи в цьому скрипті, окрім htmlspecialchars() та (int), мають бути зрозумілими. Функція htmlspecialchars() гарантує, що будь-який введений символ, який є спеціальним в HTML, правильно кодується, щоб ніхто не зміг ввести теги HTML чи Javascript на вашій сторінці. Оскільки ми знаємо, що поле age має бути числовим, ми просто конвертуємо його значення до integer (цілого), і таким чином позбуваємось від будь-яких сторонніх символів. PHP може це робити автоматично, якщо встановити розширення filter. Змінні $_POST['name'] та $_POST['age'] автоматично встановлюються через PHP. Раніше ми використовували суперглобальну змінну $_SERVER; вище ми ввели просто ще одну суперглобальну змінну $_POST, котра містить всі POST-дані (відправлені дані). Зауважте, що method нашої форми вказано як POST. Якщо ми використовуємо метод GET, то дані форми будуть знаходитись в іншій суперглобальній змінній - в $_GET. Можна ще використовувати суперглобальну змінну $_REQUEST, якщо ви не впевнені яким методом відправлено вам дані. Ця змінна містить об'єднані дані від методів GET, POST та COOKIE.

В PHP також можна працювати з XForms, але, через деякий час, ви виявите, що зі звичайними HTML формами працюється комфортніше. З іншої сторони, хоча робота з XForms не для початківців, вони також можуть вас зацікавити. В наших наступних розділах є коротке ознайомлення для обробки даних, отриманих з XForms.

add a note add a note

User Contributed Notes 3 notes

up
162
sethg at ropine dot com
20 years ago
According to the HTTP specification, you should use the POST method when you're using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it's almost always an error -- you shouldn't be posting the same comment twice -- which is why these pages aren't bookmarked or cached.

You should use the GET method when your form is, well, getting something off the server and not actually changing anything.  For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.
up
62
Johann Gomes (johanngomes at gmail dot com)
13 years ago
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
up
25
nucc1
6 years ago
worth clarifying:

POST is not more secure than GET.

The reasons for choosing GET vs POST involve various factors such as intent of the request (are you "submitting" information?), the size of the request (there are limits to how long a URL can be, and GET parameters are sent in the URL), and how easily you want the Action to be shareable -- Example, Google Searches are GET because it makes it easy to copy and share the search query with someone else simply by sharing the URL.

Security is only a consideration here due to the fact that a GET is easier to share than a POST. Example: you don't want a password to be sent by GET, because the user might share the resulting URL and inadvertently expose their password.

However, a GET and a POST are equally easy to intercept by a well-placed malicious person if you don't deploy TLS/SSL to protect the network connection itself.

All Forms sent over HTTP (usually port 80) are insecure, and today (2017), there aren't many good reasons for a public website to not be using HTTPS (which is basically HTTP + Transport Layer Security).

As a bonus, if you use TLS  you minimise the risk of your users getting code (ADs) injected into your traffic that wasn't put there by you.
To Top