METANIT.COM

Php echo form method

Одним из основных способов передачи данных веб-сайту является обработка форм. Формы представляют специальные элементы разметки HTML, которые содержат в себе различные элементы ввода — текстовые поля, кнопки и т.д. И с помощью данных форм мы можем ввести некоторые данные и отправить их на сервер. А сервер уже обрабатывает эти данные.

Создание форм состоит из следующих аспектов:

  • Создание элемента в разметке HTML
  • Добавление в этот элемент одно или несколько поле ввода
  • Установка метода передачи данных. Чаще всего используются методы GET или POST
  • Установка адреса, на который будут отправляться введенные данные

POST-запросы

Итак, создадим новую форму. Для этого определим новый файл form.php , в которое поместим следующее содержимое:

     

Форма ввода данных

Имя:

Возраст:

Атрибут action=»user.php» элемента form указывает, что данные формы будет обрабатывать скрипт user.php , который будет находиться с файлом form.php в одной папке. А атрибут method=»POST» указывает, что в качестве метода передачи данных будет применяться метод POST.

Теперь определим файл user.php , который будет иметь следующее содержание:

 if(isset($_POST["age"])) < $age = $_POST["age"]; >echo "Имя: $name 
Возраст: $age"; ?>

Для обработки запросов типа POST в PHP используется встроенная глобальная переменная $_POST . Она представляет ассоциативный массив данных, переданных с помощью метода POST. Используя ключи, мы можем получить отправленные значения. Ключами в этом массиве являются значения атрибутов name у полей ввода формы.

Например, так как атрибут name поля ввода возраста имеет значение age ( ), то в массиве $_POST значение этого поля будет представлять ключ «age»: $_POST[«age»]

И поскольку возможны ситуации, когда поле ввода будет не установлено, то в этом случае желательно перед обработкой данных проверять их наличие с помощью функции isset() . И если переменная установлена, то функция isset() возвратит значение true .

Теперь мы можем обратиться к скрипту form.php и ввести в форму какие-нибудь данные:

Обработка форм в PHP

И по нажатию кнопки введенные данные методом POST будут отправлены скрипту user.php :

массив <img decoding=

Форма ввода данных

Имя:

Возраст:

Поскольку в данном случае мы отправляем данные этому же скрипту — то есть по тому же адресу, то у элемента форма можно не устанавливать атрибут action .

Отправка формы в PHP

Стоит отметить, что в принципе мы можем отправлять формы и запросом GET, в этом случае для получения тех же значений формы применяется массив $_GET , который был рассмотрен в прошлой теме:

      if(isset($_GET["age"])) < $age = $_GET["age"]; >echo "Имя: $name 
Возраст: $age"; ?>

Форма ввода данных

Имя:

Возраст:

Источник

How to echo on same html page after form submit?

When the form is submitted, my page is redirected to the PHP and the echo is displayed. How can I display the echo without being redirected to the PHP page? So the echo should be displayed in the html page (where the html form is located).

Not exactly sure if I understand what your saying but it sounds like your trying to display something without a page refresh which you could do with AJAX

When they hit one of the submit buttons, I want to echo a result but not leave the page. How can the echoed message be displayed on the html page where the form is located instead of the PHP? I mean without Ajax. My idea is to send the value from the PHP to an input textfield in the html page. Does that make sense?

Читайте также:  Sorted tree set java

5 Answers 5

I guess you can use a combination of and javascript to get the results.

You can’t do it on the same page — at least not without asynchronous client-server communication techniques such as AJAX. Otherwise, you can use the following:

as your form opening tag, then put the PHP processing code at the top of the document, like this:

 HTML in case of Form filled in goes here else < ?>HTML in case of Form not filled in goes here ?> HTML in any case goes here 

This way you can change the layout of your page depending on whether the form was filled in or not. the $_SERVER[‘PHP_SELF’] contains the reference to the currently requested page, and therefore is always set to the correct page even if it is renamed. This can save you time when bug-tracking.

Источник

PHP why use «echo» in action

I am learning php, but I really don’t get why do you have to use the «echo» here. We do not need to print or show the variable $_SERVER, it is more like an internal code. So are there any rules regarding when to using the «echo» for php scripts ?

2 Answers 2

The $_SERVER[«PHP_SELF»] is a superglobal that returns the name of the currently running script. So if that form is on index.php than the php server is going to echo index.php .

There are really no rules as to when to use echo . The only time you can’t use it is on an array. If you attempt to use it on an array it will return the object rather than the string. For an array you can either iterate through it printing every object, var_dump(array) , or print array[0] and if it’s a dictionary print array[‘key’] The most important thing to remember with php is that after all the processing is done all it does is sends the browser a plain html file.

That’s not completely true because an array can only be sown by using print_r() . If you would use echo for an array you will end up with an error.

@SuperDJ That’s wrong, you will end up with Array , if the variable is an array. But $_SERVER[‘PHP_SELF’] is a string.

But do I really need the «echo» on the action, because the global variable will get the name of the running script, and that’s all I need, no need to print it or do I really need to «print» the value, I tested it and it works without the echo, or maybe I did something wrong.

@FraK No, it would work without the echo. The reason it would work without the echo is doing:

submits to the current page. For example if your page was called index.php doing , and Источник

Simple Php Echo

You’re trying to make the echo appear right after pressing the button. You can’t do that with PHP, it’s a server-side technology. Try JavaScript or another client-side technology.

Читайте также:  Javascript получение координат мыши

3 Answers 3

the correct attribute for your form tag is «action», not «actions»

When the form is submitted, a new request is sent to the server (in your case, using GET).

So to do it all in one page:

You will first need to check if PHP has received your GET parameter using isset or array_key_exists :

if(isset($_GET['name']) && !empty($_GET['name']))
if(array_key_exists('name', $_GET) && !empty($_GET['name'])) < $Name = $_GET['name']; echo "Hello $Name"; >else < //example: default to something if nothing has been passed echo "Hello Guest"; >

Also note, if you’re submitting to the same page, you can omit the action attribute from your form tag altogether:

@Jonathan Fingland, magic quotes is what PHP uses to automatically escape data — karim79’s example has nothing to do with that.

You’ve just gained an HTML-injection vulnerability. If someone sends your user to:

http://www.example.com/madlib01.php?name= 

Yes, this is a My First PHP Script. That doesn’t make security optional. This is a mistake every tutorial makes: teaching bad practice from the start, treating correctness (and security, which is a subset of correctness) as an optional extra.

The result is that most PHP code out there is full of holes. But there’s no need for yours to be! Every time you place a pure-text string into a surrounding HTML context, escape it properly:

echo htmlspecialchars($hello); 

I tend to define a function with a shorter name than ‘htmlspecialchars’ to do that for me, as I’m lazy.

 $name= ''; if (isset($_REQUEST['name'])) $name= trim($_REQUEST['name']); ?> .  

Hello, !

?>

Now if you say your name is Mister , the page will greet you exactly as such, angle brackets and all, instead of trying to run JavaScript. This is the correct output and thus also secure.

Источник

How to echo a tag [duplicate]

Here is what is happening.

Here is some pseudo code

echo "   . Some inputs and such go here.
";
  if($_SESSION['school'] == "drl") < $sql = 'SELECT id, student_name, student_id, grad_year, grade, test_name, individual, team_event, member_number, team_number, captain FROM drl'; >elseif($_SESSION['school'] == "Butler Tech") < $sql = 'SELECT id, student_name, student_id, grad_year, grade, test_name, individual, team_event, member_number, team_number, captain FROM butlertech'; >elseif($_SESSION['school'] == "MIT") < $sql = 'SELECT student_name, student_id, grad_year, grade, test_name, individual, team_event, member_number, team_number, captain FROM mit'; >mysql_select_db('contestants'); $retval = mysql_query( $sql, $conn ); if(! $retval ) < die('Could not get data: ' . mysql_error()); >while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) < echo "
' name='student_name' /> ' name='student_id' /> ' type='number' />
";> mysql_close($conn); ?>

Everything works as intended, except for the form part. As you can see in the picture, the form is being echoed before everything else. What I want is for to be inside the form.

Источник

Оцените статью