downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Использование старых программ с новыми версиями PHP> <Делаем что-нибудь полезное
[edit] Last updated: Fri, 25 May 2012

view this page in

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

Одно из главнейших достоинств 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']; ?> лет.

Пример вывода данной программы:

Здравствуйте, Сергей.
Вам 30 лет.

Если не принимать во внимание куски кода с 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 и FILE. Также советуем взглянуть на описание функции import_request_variables().

В PHP можно также работать и с XForms, хотя вы найдете работу с обычными HTML-формами довольно комфортной уже через некоторое время. Несмотря на то, что работа с XForms не для новичков, они могут показаться вам интересными. В разделе возможностей PHP у нас также есть короткое введение в обработку данных из XForms.



add a note add a note User Contributed Notes Работа с формами
Andy 14-Apr-2012 12:05
Just a reminder about security: neither POST nor GET are "secure". Any information is transmitted nearly in plan text within the IP packets.

For security of the transmitted information from client to server (and back) you MUST use transport layer security like e. g. SSL, HTTPS etc.
Johann Gomes (johanngomes at gmail dot com) 11-Oct-2010 07:20
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
arnel_milan at hotmail dot com 29-Mar-2008 09:27
I was so shocked that some servers have a problem regarding the Submit Type Name and gives a "Not Acceptable error" or Error 406.

Consider the example below :

<form action="blah.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>
   
    <tr>
      <td colspan="2" align="center">
        <input type="submit" name="Submit_btn" id="Submit_btn" value="Send">
      </td>
    </tr> 
  </table>
</form>

This very simple code triggers the "Not Acceptable Error" on
PHP Version 5.2.5 and Apache 1.3.41 (Unix) Server.

However to fix this below is the right code:

<form action="blah.php" method="POST">
  <table>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name"></td>
    </tr>
   
    <tr>
      <td colspan="2" align="center">
        <input type="submit" name="Submitbtn" id="Submit_btn" value="Send">
      </td>
    </tr> 
  </table>
</form>

The only problem that took me hours to find out is the "_" in the Submit Button.

Hope this help!
SvendK 08-Nov-2006 08:02
As Seth mentions, when a user clicks reload or goes back with the browser button, data sent to the server, may be sent again (after a click on the ok button).

It might be wise, to let the server handle whatever there is to handle, and then redirect (a redirect is not visible in the history and thus not reachable via reload or "back".

It cannot be used in this exact example, but as Seth also mentions, this example should be using GET instead of POST
yasman at phplatvia dot lv 05-May-2005 12:18
[Editor's Note: Since "." is not legal variable name PHP will translate the dot to underscore, i.e. "name.x" will become "name_x"]

Be careful, when using and processing forms which contains
<input type="image">
tag. Do not use in your scripts this elements attributes `name` and `value`, because MSIE and Opera do not send them to server.
Both are sending `name.x` and `name.y` coordiante variables to a server, so better use them.
sethg at ropine dot com 01-Dec-2003 12:55
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.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites