It always passes the text in the quotes. In this case «selected» . How do I pass one of the strings from the option?
6 Answers 6
Both your select control and your submit button had the same name attribute, so the last one used was the submit button when you clicked it. All other syntax errors aside.
check.php
Obligatory disclaimer about using raw $_POST data. Sanitize anything you’ll actually be using in application logic.
As your form gets more complex, you can a quick check at top of your php script using print_r($_POST); , it’ll show what’s being submitted an the respective element name.
To get the submitted value of the element in question do: $website_string = $_POST[‘website_string’];
It appears that in PHP you are obtaining the value of the submit button, not the select input. If you are using GET you will want to use $_GET[‘website_string’] or POST would be $_POST[‘website_string’] .
You will probably want the following HTML:
With some PHP that looks like this:
$website = $_POST[«website_string»]; Yes thats the code. When I had it as a text box it sent the proper text. But the free form style let people make mistakes. So I wanted to change to a drop down box. But I cannot get the right text passed.
I changed it to your code. in the php file I added print_r($_POST); The result is: Array ( [website_string] => Submit ) . So its sending the text Submit.
@Joe: Oh wow, my bad. Please remove ‘name=»website_string»‘ from the submit input. I edited my code to remove this; it should function correctly now. Sorry.
Assuming you’ve fixed the syntax errors (you’ve closed the select box before the name attribute), you’re using the same name for the select box as the submit button. Give the select box a different name.
I changed each and get the same results. If I change the first to website_str, I still get the text returned as submit instead of the string I want.
I changed the location of the /select. It does not change the result. The problem is submit is not sending the proper value. If I put value=»fff» it will send fff. otherwise it is sending submit. There must be a way to specify the value as selected.
For your actual form, if you were to just post the results to your same page, it should probably work out all right. Try something like:
method mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:
Example
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
The output could be something like this:
The same result could also be achieved using the HTTP GET method:
Example
and "welcome_get.php" looks like this:
The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.
Think SECURITY when processing PHP forms!
This page does not contain any form validation, it just shows how you can send and retrieve form data.
However, the next 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!
GET vs. POST
Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, . )). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
Developers prefer POST for sending form data.
Next, lets see how we can process PHP forms the secure way!
Для передачи данных от пользователя Web-страницы на сервер используются HTML-формы. Для работы с формами в PHP предусмотрен ряд специальных средств.
Предварительно определенные переменные
В PHP существует ряд предварительно определенных переменных, которые не меняются при выполнении всех приложений в конкретной среде. Их также называют переменными окружения или переменными среды. Они отражают установки среды Web-сервера Apache, а также информацию о запросе данного браузера. Есть возможность получить значения URL, строки запроса и других элементов HTTP-запроса.
Все предварительно определенные переменные содержатся в ассоциативном массиве $GLOBALS . Кроме переменных окружения этот массив содержит также глобальные переменные, определенные в программе.
В результате на экране появится список всех глобальных переменных, включая переменные окружения. Наиболее часто используемые из них:
Переменная
Описание
Содержание
$_SERVER['HTTP_USER_AGENT']
Название и версия клиента
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.45 Safari/535.19
$_SERVER['REMOTE_ADDR']
IP-адрес
95.143.190.109
getenv('HTTP_X_FORWARDED_FOR')
Внутренний IP-адрес клиента
$_SERVER['REQUEST_METHOD']
Метод запроса ( GET или POST )
GET
$_SERVER['QUERY_STRING']
При запросе GET закодированные данные, передаваемые вместе с URL
$_SERVER['REQUEST_URL']
Полный адрес клиента, включая строку запроса
$_SERVER['HTTP_REFERER']
Адрес страницы, с которой был сделан запрос
https://htmlweb.ru/
$_SERVER['PHP_SELF']
Путь к выполняемой программе
/index.php
$_SERVER['SERVER_NAME']
Домен
htmlweb.ru
$_SERVER['REQUEST_URI']
Путь
/php/php_form.php
Обработка ввода пользователя
PHP-программу обработки ввода можно отделить от HTML-текста, содержащего формы ввода, а можно расположить на одной странице.
Пример 2
Номер карточки:
Здесь отсутствует кнопка передачи данных, т.к. форма, состоящая из одного поля, передается автоматически при нажатии клавиши .
При обработки элемента с многозначным выбором для доступа ко всем выбранным значениям нужно к имени элемента добавить пару квадратных скобок. Для выбора нескольких эллементов следует удерживать клавишу Ctrl.
Пример 3.1
Пример 3.2
Пример 4. Прием значений от checkbox-флажков
$v) < if($v) echo "Вы знаете язык программирования $k! "; else echo "Вы не знаете языка программирования $k. "; > > ?> Какие языки программирования вы знаете?
Пример 5
Можно обрабатывать формы, не заботясь о фактических именах полей.
Для этого можно использовать (в зависимости от метода передачи) ассоциативный массив $HTTP_GET_VARS или $HTTP_POST_VARS . Эти массивы содержат пары имя/значение для каждого элемента переданной формы. Если Вам все равно, Вы можете использовать ассоциативный массив $_REQUEST .
Пример 6
$value ) echo "$key == $value "; ?>
Пример 7. Обработка нажатия на кнопку с использованием оператора '@'
С помощью функции header() , послав браузеру заголовок "Location" , можно перенаправить пользователя на новую страницу.
Передача файла на сервер. Залить файл. UpLoad
PHP позволяет передавать на сервер файлы. HTML-форма, предназначенная для передачи файла, должна содержать аргумент enctype="multipart/form-data" .
Кроме того в форме перед полем для копирования файла должно находиться скрытое поле с именем max_file_size . В это скрытое поле должен быть записан максимальный размер передаваемого файла (обычно не больше 2 Мбайт).
Само поле для передачи файла - обычный элемент INPUT с аргументом type="file" .
После того, как файл передан на сервер, он получает уникальное имя и сохраняется в каталоге для временных файлов. Полный путь к файлу записывается в глобальную переменную, имя которой совпадает с именем поля для передачи этого файла. Кроме этого PHP сохраняет еще некоторую дополнительную информацию о переданном файле в других глобальных переменных:
Переменная
Описание
$_FILES['userfile']['name']
оригинальное имя файла, такое, каким его видел пользователь, выбирая файл
$_FILES['userfile']['type']
mime/type файла, к примеру, может быть image/gif; это поле полезно сохранить, если Вы хотите предоставлять интерфейс для скачивания загруженных файлов
$_FILES['userfile']['size']
размер загруженного файла
$_FILES['userfile']['tmp_name']
полный путь к временному файлу на диске
$_FILES['userfile']['error']
код ошибки, который равен 0, если операция прошла успешно
Если возникнут проблемы с перекодировкой сервером загруженного файла, символ с кодом 0х00 заменен на пробел (символ с кодом 0х20 ), допишите в файл httpd.conf из каталога Апача (/usr/local/apache) следующие строки.
I'm sorry, but you'll need to supply a whole lot more information here. You want to know how to submit to the Paypal API? Try here: developer.paypal.com - If you want some general PHP form info, there are loads and loads of demos and sample code online.
I hope these hidden fields are checked on server side, otherwise I could change the value to 0.00 and pay nothing :).
If you're wanting this form to submit as soon as the page is loaded, you can add this to the bottom of the page if you're determined in using PHP to submit the form:
But that seems like a long way around it. You could just write the javascript into the page. maybe I'm not sure what you're wanting to do, but I thought I'd throw this out.