PHP and HTML
PHP and HTML interact a lot: PHP can generate HTML, and HTML can pass information to PHP. Before reading these faqs, it’s important you learn how to retrieve variables from external sources. The manual page on this topic includes many examples as well.
- What encoding/decoding do I need when I pass a value through a form/URL?
- I’m trying to use an tag, but the $foo.x and $foo.y variables aren’t available. $_GET[‘foo.x’] isn’t existing either. Where are they?
- How do I create arrays in a HTML ?
- How do I get all the results from a select multiple HTML tag?
- How can I pass a variable from Javascript to PHP?
What encoding/decoding do I need when I pass a value through a form/URL?
- HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.
- URL: A URL consists of several parts. If you want your data to be interpreted as one item, you must encode it with urlencode() .
Example #1 A hidden HTML form element
echo ‘. htmlspecialchars ( $data ) . ‘» />’ . «\n» ;
?>?php
Note: It is wrong to urlencode() $data , because it’s the browsers responsibility to urlencode() the data. All popular browsers do that correctly. Note that this will happen regardless of the method (i.e., GET or POST). You’ll only notice this in case of GET request though, because POST requests are usually hidden.
Example #2 Data to be edited by the user
echo «» ;
?>?php
Note: The data is shown in the browser as intended, because the browser will interpret the HTML escaped symbols. Upon submitting, either via GET or POST, the data will be urlencoded by the browser for transferring, and directly urldecoded by PHP. So in the end, you don’t need to do any urlencoding/urldecoding yourself, everything is handled automagically.
Example #3 In a URL
Note: In fact you are faking a HTML GET request, therefore it’s necessary to manually urlencode() the data.
Note: You need to htmlspecialchars() the whole URL, because the URL occurs as value of an HTML-attribute. In this case, the browser will first un- htmlspecialchars() the value, and then pass the URL on. PHP will understand the URL correctly, because you urlencode() d the data. You’ll notice that the & in the URL is replaced by & . Although most browsers will recover if you forget this, this isn’t always possible. So even if your URL is not dynamic, you need to htmlspecialchars() the URL.
I’m trying to use an tag, but the $foo.x and $foo.y variables aren’t available. $_GET[‘foo.x’] isn’t existing either. Where are they?
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y .
Because foo.x and foo.y would make invalid variable names in PHP, they are automagically converted to foo_x and foo_y . That is, the periods are replaced with underscores. So, you’d access these variables like any other described within the section on retrieving variables from external sources. For example, $_GET[‘foo_x’] .
Note:
Spaces in request variable names are converted to underscores.
How do I create arrays in a HTML ?
To get your result sent as an array to your PHP script you name the , or elements like this:
Notice the square brackets after the variable name, that’s what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It’s also possible to assign specific keys to your arrays:
The AnotherArray array will now contain the keys 0, 1, email and phone.
Note:
Specifying array keys is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.
How do I get all the results from a select multiple HTML tag?
The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.
Each selected option will arrive at the action handler as:
var=option1 var=option2 var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP’s «array from form element» feature. The following should be used:
This tells PHP to treat $var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0] , the next $var[1] , etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.
Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it’s numerical form element ID instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:
variable = document.forms[0].elements['var[]'];
How can I pass a variable from Javascript to PHP?
Since Javascript is (usually) a client-side technology, and PHP is (usually) a server-side technology, and since HTTP is a «stateless» protocol, the two languages cannot directly share variables.
It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this — it allows PHP code to capture screen height and width, something that is normally only possible on the client side.
Example #4 Generating Javascript with PHP
if (isset( $_GET [ ‘width’ ]) AND isset( $_GET [ ‘height’ ])) // output the geometry variables
echo «Screen width is: » . $_GET [ ‘width’ ] . «
\n» ;
echo «Screen height is: » . $_GET [ ‘height’ ] . «
\n» ;
> else // pass the geometry variables
// (preserve the original query string
// — post variables will need to handled differently)
?php
User Contributed Notes
There are no user contributed notes for this page.
- FAQ
- General Information
- Mailing lists
- Obtaining PHP
- Database issues
- Installation
- Build Problems
- Using PHP
- Password Hashing
- PHP and HTML
- PHP and COM
- Miscellaneous Questions
как связать html и php-файлы?
Добрый день. Недавно начал изучать html и php, и столкнулся с проблемой, которую никак не могу решить. Есть простейшая html-форма для введения значений 5 полей, и php-файл, который должен записывать введенные данные в БД. К php прикреплен файл, содержащий данные для входа (связка с ним работает и данные не из формы, а вбитые как значения переменных,отправляет нормально). Однако, при попытке ввести данные в форму страница просто обновляется.Соответственно, ничего не выводится и не записывается в БД. Подскажите пожалуйста, в чем моя ошибка? (у меня есть смутное чувство, что для этого нужно прописать что-то в php, связанное со ссылками,но вот что?) Upd0: добавил в index.html кнопку с submitom и переправил названия полей (спасибо за подсказку ArchDemon’у и прошу прощения — делал все это в жестком цейтноте). На всякий случай убрал экранирование символов. Увы, это ничего не дало. Может, я ставлю неправильное условие или что-то такое? P.S. Насколько моих обрывочных знаний хватает, я припоминаю, что php работает раньше html. Правда ли это и не в этом ли заключается проблема? UPD1: Решил упростить файлы настолько, насколько это возможно. Заодно проверил через GET — так результат просто записывается в адресную строку. Через POST опять же, обновление и никаких результатов. index.html
HTML-форма добавления новых данных // выполняем запрос $result = mysqli_query($link, $query) or die("Ошибка!" . mysqli_error($link)); if($result) < echo " Данные добавлены"; // закрываем подключение mysqli_close($link); >?>Как связать php и html?
Запустить веб-сервер в директории где был создан файл, например командой:
$ php -S 127.0.0.1:8080
Открыть в браузере страницу 127.0.0.1:8080/example.php, после нажатия кнопки отправки данных на этой странице будет выведено число 123456789.Ответ написан более трёх лет назад
Комментировать
Нравится 1 КомментироватьSoftware engineer
Советую начать с азов.
Отвечу на ваши вопросы:1. Как сделать чтобы считывал что в input,
www.w3schools.com/php/php_forms.asp
2. как вообще сделать переменнуюОтвет написан более трёх лет назад
Игорь Касперский @HHabar Автор вопроса
хорошо, а чтоб хранила данные, то что в input есть
Игорь Касперский: я дополнил ответ, перейдите по ссылке там все подробно расписано.
Игорь Касперский @HHabar Автор вопросаDARWIN Yuri: неее(( вот если простой пример, я ввожу в инпут число, число сохраняется в переменной,операция сложения над числом и вывод
Игорь Касперский @HHabar Автор вопроса
DARWIN Yuri: а то эти _POST связанны с этим же, с отправкой формы и т.д. не знаю
Игорь Касперский @HHabar Автор вопроса
DARWIN Yuri: а можно без ссылки на документ в форме, а прям там написать?
Для начало вам надо передать value на сервер, это можно сделать простыми методами GET и POST, чтобы потом на сервере PHP получил value сделал операцию сложения и вернул вам обратно. Вам нужно четче сформулировать вопрос.
Игорь Касперский @HHabar Автор вопроса
DARWIN Yuri: а как это пишется, не так же $int = value?Игорь Касперский: чувак, зачем тупить и задавать глупые вопросы, людей отвлекать? Лень потратить 5 минут на вводную часть «PHP для чайников»?
PHP Form Handling
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:
Welcome John
Your email address is john.doe@example.comThe 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!
