php input type hidden
Php input type hidden
elements of type hidden let web developers include data that cannot be seen or modified by users when a form is submitted. For example, the ID of the content that is currently being ordered or edited, or a unique security token. Hidden inputs are completely invisible in the rendered page, and there is no way to make it visible in the page’s content.
Note: There is a live example below the following line of code — if it is working correctly, you should see nothing!
Value | A DOMString representing the value of the hidden data you want to pass back to the server. |
Events | None. |
Supported Common Attributes | autocomplete |
IDL attributes | value |
Methods | None. |
Note: The input and change events do not apply to this input type. Hidden inputs cannot be focused even using JavaScript (e.g. hiddenInput.focus() ).
Value
The element’s value attribute holds a DOMString that contains the hidden data you want to include when the form is submitted to the server. This specifically can’t be edited or seen by the user via the user interface, although you could edit the value via browser developer tools.
Important: While the value isn’t displayed to the user in the page’s content, it is visible—and can be edited—using any browser’s developer tools or «View Source» functionality. Do not rely on hidden inputs as a form of security.
Additional attributes
In addition to the attributes common to all elements, hidden inputs offer the following attributes:
Attribute | Description |
---|---|
name | Like all input types, the name of the input to report when submitting the form; the special value _charset_ causes the hidden input’s value to be reported as the character encoding used to submit the form |
This is actually one of the common attributes, but it has a special meaning available for hidden inputs. Normally, the name attribute functions on hidden inputs just like on any other input. However, when the form is submitted, a hidden input whose name is set to _charset_ will automatically be reported with the value set to the character encoding used to submit the form.
Using hidden inputs
As mentioned above, hidden inputs can be used anywhere that you want to include data the user can’t see or edit along with the form when it’s submitted to the server. Let’s look at some examples that illustrate its use.
Tracking edited content
One of the most common uses for hidden inputs is to keep track of what database record needs to be updated when an edit form is submitted. A typical workflow looks like this:
The idea here is that during step 2, the ID of the record being updated is kept in a hidden input. When the form is submitted in step 3, the ID is automatically sent back to the server with the record content. The ID lets the site’s server-side component know exactly which record needs to be updated with the submitted data.
You can see a full example of what this might look like in the Examples section below.
Improving website security
Hidden inputs are also used to store and submit security tokens or secrets, for the purposes of improving website security. The basic idea is that if a user is filling in a sensitive form, such as a form on their banking website to transfer some money to another account, the secret they would be provided with would prove that they are who they say they are, and that they are using the correct form to submit the transfer request.
This would stop a malicious user from creating a fake form, pretending to be a bank, and emailing the form to unsuspecting users to trick them into transferring money to the wrong place. This kind of attack is called a Cross Site Request Forgery (CSRF); pretty much any reputable server-side framework uses hidden secrets to prevent such attacks.
As stated previously, placing the secret in a hidden input doesn’t inherently make it secure. The key’s composition and encoding would do that. The value of the hidden input is that it keeps the secret associated with the data and automatically includes it when the form is sent to the server. You need to use well-designed secrets to actually secure your website.
Validation
Hidden inputs don’t participate in constraint validation; they have no real value to be constrained.
Examples
Let’s look at how we might implement a simple version of the edit form we described earlier (see Tracking edited content), using a hidden input to remember the ID of the record being edited.
The edit form’s HTML might look a little bit like this:
Let’s also add some simple CSS:
The server would set the value of the hidden input with the ID » postID » to the ID of the post in its database before sending the form to the user’s browser and would use that information when the form is returned to know which database record to update with modified information. No scripting is needed in the content to handle this.
The output looks like this:
Note: You can also find the example on GitHub (see the source code, and also see it running live).
When submitted, the form data sent to the server will look something like this:
Even though the hidden input cannot be seen at all, its data is still submitted.
Методы скрытия элементов веб-страниц
Веб-разработчикам приходится скрывать элементы веб-страниц по самым разным причинам. Например, есть кнопка, которая должна быть видимой при просмотре сайта на мобильном устройстве, и скрытой — при использовании настольного браузера. Или, например, имеется некий навигационный элемент, который должен быть скрыт в мобильном браузере и отображён в настольном. Элементы, невидимые на странице, могут пребывать в различных состояниях:
HTML5-атрибут hidden
Рассмотрим следующий пример:
В CSS я воспользовался атрибутом hidden для вывода элемента только в том случае, если область просмотра страницы имеет необходимый размер.
Вот CSS-код, который здесь использован:
→ Вот пример этой страницы на CodePen
▍Атрибут hidden и доступность контента
Если рассмотреть атрибут hidden с точки зрения доступности контента, то окажется, что этот атрибут полностью скрывает элемент. В результате с этим элементом не смогут работать средства для чтения с экрана. Не используйте этот атрибут в тех случаях, когда некие элементы страниц нужно делать невидимыми для человека, но не для программ для чтения с экрана.
CSS-свойство display
Представим, что мы хотим скрыть изображение из предыдущего примера и решили воспользоваться следующим CSS-кодом:
При таком подходе изображение будет полностью исключено из документа (из так называемого document flow — «потока документа»), оно будет недоступно программам для чтения с экрана. Возможно, вы не очень хорошо представляете себе понятие «поток документа». Для того чтобы с этим понятием разобраться — взгляните на следующий рисунок.
Синюю книгу убрали из стопки
Вот анимированный вариант примера с книгами, показывающий то, что происходит в том случае, если одну из них убирают из стопки.
Если убрать книгу из стопки — положение других книг в ней изменится
▍Производится ли загрузка ресурсов, скрытых средствами CSS?
Если коротко ответить на этот вопрос — то да, загрузка таких ресурсов производится. Например, если элемент скрыт средствами CSS, и мы показываем этот элемент в некий момент работы со страницей, к этому моменту изображение уже будет загружено. Наличие на странице изображения, даже скрытого средствами CSS, приведёт к выполнению HTTP-запроса на его загрузку.
Исследование страницы, содержащей скрытое изображение
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
I am curious about the original purpose of the tag.
Nowadays it is often used together with JavaScript to store variables in it which are sent to the server and things like that.
Therefore, the existed before JavaScript, so what was its original purpose? I can only imagine of sending a value from the server to the client which is (unchanged) sent back to maintain a kind of a state. Or do I get something wrong in the history of it and was always supposed to be used together with JavaScript?
If possible, please also give references in your answers.
5 Answers 5
I can only imagine of sending a value from the server to the client which is (unchanged) sent back to maintain a kind of a state.
Precisely. In fact, it’s still being used for this purpose today because HTTP as we know it today is still, at least fundamentally, a stateless protocol.
This use case was actually first described in HTML 3.2 (I’m surprised HTML 2.0 didn’t include such a description):
type=hidden
These fields should not be rendered and provide a means for servers to store state information with a form. This will be passed back to the server when the form is submitted, using the name/value pair defined by the corresponding attributes. This is a work around for the statelessness of HTTP. Another approach is to use HTTP «Cookies».
While it’s worth mentioning that HTML 3.2 became a W3C Recommendation only after JavaScript’s initial release, it’s safe to assume that hidden fields have pretty much always served the same purpose.
Php input type hidden
Это поле, которое позволяет выбрать цвет.
Пример
Атрибут value используют для установки исходного цвета, его можно не указывать.
Поле ввода даты
Поле типа date позволяет ввести дату с помощью календаря.
Можно задать нижнюю и верхнюю границу диапазона дат атрибутами min и max.
Пример
Поле ввода адреса электронной почты
Для ввода нескольких адресов можно добавить атрибут multiple, при этом для разделения адресов используется запятая (,)
Пример
Файл FILE
Позволяет передать сценарию любой файл. Максимальный размер файла в байтах задается скрытым полем max_file_size.
Пример
Сценарий получения файла на PHP:
Браузер Chrome понимает дополнительные атрибуты «webkitdirectory directory«, указание которых у input позволяет выбирать целые папки:
Скрытое поле HIDDEN
Это специальный (скрытый) тип текстового поля. Если один сценарий обрабатывает несколько разных форм, то в скрытом поле каждой формы можно указать идентификатор, который позволит определить, с какой формой вы имеете дело.
Пример
Браузер не отображает скрытое поле, хотя его можно обнаружить, если перевести броузер в режим просмотра HTML-файла и проанализировать текст Web-страницы. Скрытые поля полезны, если необходимо указать требуемую для сценария информацию, но при этом нежелательно, чтобы пользователь имел возможность вносить в нее изменения. Однако учтите, что сообразительный пользователь может сохранить вашу форму в файле, отредактировать его, а затем передать эту форму серверу в измененном виде. Поэтому не стоит полагаться на скрытые поля с целью создания какой-либо защиты.
Пример
Сценарий получит переменную с именем FormVersion, которой будет присвоено значения 1.2. Эта информация может использоваться для определения способа обработки остальной информации, полученной от формы. Если пользователь изменит это значение, то программа сценария может повести себя неожиданным образом.
Поле ввода чисел NUMBER
Поле предназначено для ввода чисел. Дробная часть при вводе может отделяться как точкой (2.5), так и запятой (2,5). Если пользователь введет буквы, то отправить форму на сервер не удастся.
Пример
Можно задать минимальное, максимальное значение поля и шаг изменения числа. Значение шага может быть как целым, так и дробным, но должно быть больше 0. Если введенное в поле число не будет отвечать заданным ограничениям, то отправка на сервер не произойдет.
Пример
Для задания любого шага используйте step=»any».
Пример
Поле number отображается по-разному: некоторые браузеры показывают стрелочки всегда, некоторые – только при наведении или получении полем фокуса.
Если нужно, чтобы стрелочки в поле number были всегда, задайте стиль:
Если нужно убрать стрелочки в поле number, задайте стиль:
Поле ввода пароля PASSWORD
Поле ввода пароля очень похоже на простое текстовое поле. Отличается оно тем, что вместо вводимых символов в нем отображаются точки. Такая возможность очень важна, когда нужно ввести секретную информацию, типа пароля, которую не должны видеть другие.
Пример
Переключатель RADIO
Переключатель напоминает флажок, поскольку он тоже может находиться во включенном или выключенном состоянии.
По смыслу всегда предполагается, что в форме имеется несколько переключателей с одинаковым атрибутом name. У каждого из них свое значение атрибута value. Группа переключателей с одним и тем же именем в форме ведет себя таким образом, что только один из них может быть включенным. При передаче данных передается значение только выбранного переключателя.
Один переключатель из группы может быть изначально выбран по умолчанию с помощью атрибута checked.
Пример
Ползунок RANGE
Поле предназначено для ввода числа в указанном диапазоне.
Можно задать минимальное значение (по умолчанию 0), максимальное значение (по умолчанию 100), шаг изменения числа (по умолчанию 1) и текущее значение (по умолчанию среднее арифметическое минимального и максимального значений).
Пример
Ползунок сам по себе не даёт пользователю представление, какое же число он выбрал. Поэтому здесь без JavaScript не обойтись.
Пример
Поле range отображается разными браузерами по-разному.
Если хотите своё оформление, задайте стили для ползунка:
Но победить до конца стили IE11 не удастся!
Кнопка RESET
Это кнопка очистки формы. При ее нажатии всем измененным элементам возвращается значение по умолчанию. Применяется она достаточно редко. Однако в некоторых случаях может быть весьма полезна.
Совет: осторожно относитесь к выбору надписи на кнопке RESET. Вполне наглядным (и, главное, интуитивно понятным даже чайнику из чайников) будет что-нибудь вроде «Очистить», «Начать сначала», «Удалить ввод» и т.п. В общем, надо, чтобы у пользователя не закралось и тени сомнения относительно предназначения этой клавиши.
Пример
Кнопка SUBMIT
Эта кнопка предназначена для передачи формы. В большинстве браузеров внешне почти не отличима от кнопки BUTTON. Сама она не передается, а служит только для управления.
Атрибут onclick для кнопки SUBMIT практически не используется, так как лучше использовать обработчик событий onsubmit, заданный в теге
Атрибут value дает определенные преимущества при использовании более одной кнопки передачи данных. В этом случае на основании значения полученной переменной сценарий сможет определить, как обрабатывать полученную информацию далее.
Пример
Атрибут formnovalidate может быть применен, чтобы предотвратить проверку значений формы.
Пример
Поле ввода TEXT
Текстовое поле ввода используется в формах наиболее часто. Более того, его можно по праву считать основным и главнейшим элементом форм. Этот тип используется тегом по умолчанию, его можно не указывать, чтобы вывести текстовое поле. Однако, если возникнет необходимость задать стиль для селектора input[type=»text»], то тогда атрибут type=»text» пропускать нельзя.
Имя поля, задаваемое атрибутом name, всегда обязательно, так как базируясь именно на этом параметре, браузер передает сценарию пару имя=значение.
Пример
Текст «Иванов» помещается в созданное поле в качестве начального значения. Если пользователь не внесет изменений или нажмет кнопку RESET, то значение Иванов будет отправлено сценарию в качестве фамилии пользователя.
hidden
The hidden global attribute is a Boolean attribute indicating that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can’t be used until the login process has been completed. Browsers won’t render elements with the hidden attribute set.
The hidden attribute must not be used to hide content just from one presentation. If something is marked hidden, it is hidden from all presentations, including, for instance, screen readers.
Hidden elements shouldn’t be linked from non-hidden elements, and elements that are descendants of a hidden element are still active, which means that script elements can still execute and form elements can still submit. Elements and scripts may, however, refer to elements that are hidden in other contexts.
For example, it would be incorrect to use the href attribute to link to a section marked with the hidden attribute. If the content is not applicable or relevant, then there is no reason to link to it.
It would be fine, however, to use the ARIA aria-describedby attribute to refer to descriptions that are themselves hidden. While hiding the descriptions implies that they are not useful on their own, they could be written in such a way that they are useful in the specific context of being referenced from the element that they describe.
Similarly, a canvas element with the hidden attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control could refer to a hidden form element using its form attribute.
Note: Changing the value of the CSS display property on an element with the hidden attribute overrides the behavior. For instance, elements styled display: flex will be displayed despite the hidden attribute’s presence.