|
|
Одно из главнейших достоинств PHP - то, как он работает с формами HTML.
Здесь основным является то, что каждый элемент формы автоматически
станет доступен вашим программам на PHP. Для подробной информации об
использовании форм в PHP читайте раздел "
Переменные из внешних
источников". Вот пример формы HTML:
Пример 2-6. Простейшая форма HTML <form action="action.php" method="POST">
Ваше имя: <input type="text" name="name" />
Ваш возраст: <input type="text" name="age" />
<input type="submit">
</form> |
|
В этой форме нет ничего особенного. Это обычная форма HTML без каких-либо
специальных тегов. Когда пользователь заполнит форму и нажмет кнопку
отправки, будет вызвана страница action.php. В
этом файле может быть что-то вроде:
Пример 2-7. Выводим данные нашей формы |
Здравствуйте, <?php echo $_POST["name"]; ?>.
Вам <?php echo $_POST["age"]; ?> лет.
|
Пример вывода данной программы:
Здравствуйте, Сергей.
Вам 30 лет. |
|
Принцип работы данного кода прост и понятен. Переменные
The $_POST["name"] и $_POST["age"]
автоматически установлены для вас средствами PHP. Ранее мы использовали
переменную $_SERVER, здесь же мы точно также используем
суперглобальную переменную
$_POST, которая содержит
все POST-данные. Заметим, что метод отправки нашей
формы - POST. Если бы мы использовали метод GET,
то информация нашей формы была бы в суперглобальной переменной
$_GET.
Также можно использовать переменную
$_REQUEST, если
источник данных не имеет значения. Эта переменная содержит смесь
данных GET, POST, COOKIE и FILE. Также советуем взглянуть на описание
функции import_request_variables().
add a note
User Contributed Notes
Работа с формами
maheshs60 at gmail dot com
30-Jul-2007 10:46
Here is a PHP script to add more form fields in a page by clicking on a button on the same page.You can add unlimited number of fields dynamically(in run time) in a page by using this script.
(For the alligning of form fields,forms are given in layers)
<html>
<style type="text/css">
#Layer1 {
position:absolute;
left:413px;
top:123px;
width:203px;
height:35px;
z-index:1;
}
#Layer2 {
position:absolute;
left:21px;
top:122px;
width:389px;
height:50px;
z-index:2;
}
</style>
<body>
<?
$n=0;
$n1=$_POST['hf'];
if($n1>=$n){
$t=$n1;}
else{
$t=$n;}
/*For example this script allows user to add more and more file upload fields in a page by clicking on a button*/
?>
<!--creating a form--><!--save this page as "upload.php" -->
<div id="Layer1">
<form name="form1" method="post" action="upload.php">
<!--creating a hidden field and sets it's value as $t-->
<input name="hf" type="hidden" id="hf" value="<? echo ++$t; ?>">
<!--creating a button.When we click this, a new field will be generated-->
<input type="submit" name="Submit" value="one more">
</form>
<!--another form to submit the uploaded file to be processed-->
<!--the upload script should be written in the file "uploader.php"-->
</div>
<div id="Layer2">
<form action="uploader.php" method="post" enctype="multipart/form-data">
<p>
<?
$i=0;
while($i<$t){
echo "Filename:"
?>
<label for="file">
<input type="file" name="file" id="file" >
<input type="submit" name="submit" value="Submit" >
<?++$i;}?>
</form>
</div>
</body>
</html>
Like this, you can add any type of form field into the same page by the click of a button.
danrulz98 at yahoo dot com
30-Apr-2007 08:40
If you use ALL of the code above, it works fine. If you misspell "method" it will use $_GET by default ( it did on my server anyway). Make sure you use a spell check.
danrulz98 at yahoo dot com
30-Apr-2007 08:24
In the sample above, the code dose not work. Even if you copy and paste the sample code you will get:
Hi . You are 0 years old
The code should look more like this on the main page:
<?php echo '<p>Hello World</p>'; ?>
<form action="action.php" methhod="get">
<p>Your name: <input type="text" name="name" /></p>
<p>your age: <input type="text" name="age" /></p>
<p><input type="submit" /></p>
Then the action page should look like this:
Hi <?php echo htmlspecialchars($_GET['name']); ?>.
You are <?php echo (int)$_GET['age']; ?> years old
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.
|