Concept Of Name And ID in PHP & HTML - php

I am doing programming in PHP and HTML these days. But the problem I am facing is that many times the data is accepted by the PHP engine using NAME attribute used in the HTML syntax of Forms but many times (like when there was a multi-radio button program) ID and NAME together gave me the required output.
Can anyone here give me a nice explanation of the concept and the difference between these two? I already tried googling but I could not understand.
Help will be appreciated :)

The name attribute is used on form controls (like <input>) to associate a known label with a (possibly) variable value that will appear in the submitted data. It does not have to be unique, but PHP will only handle multiple fields which share a name properly if that name ends in [].
<input name="foo" value="bar"> will be available through $_POST['foo'] or $_GET['foo'] when the form is submitted.
The id attribute can be used on any HTML element so it can be referenced with client side technologies (such as <label for>, JavaScript and fragment identifiers in URIs). It does have to be unique.
NB: It is possible to use a name attribute to reference an element with client side technologies, but it is almost always a better idea to use id (or class for groups of elements) rather then adding a name attribute.

Related

Is there a way to pass the **type** HTML input attribute value to the $_POST array in a HTML/PHP Form?

Can we somehow pass the type HTML input attribute value to the $_POST array or grab it anyhow else with PHP?
I am aware that I can create a hidden field and basically put the type of the real input into the value of the hidden field, but this seems a bit like "repeating" work to me.
I want to create a Form, where input values are submitted to the $_POST and I can detect the type of that input without the need to hardcode/map the single inputs to each a type.
In this way I could detect the field type and act upon without the need to create a "map" that maps my custom inputs (by name or ID) to a certain type, which I already declare in HTML form anyway.
It seems a real shortcoming that the type of an input is undetectable in a Form Submit - or perhaps (hopefully) I miss something?
Can we somehow pass the type HTML input attribute value to the $_POST array or grab it anyhow else with PHP?
Not per se.
I am aware that I can create a hidden field and basically put the type of the real input into the value of the hidden field
That is a way to do it.
It seems a real shortcoming that the type of an input is undetectable in a Form Submit
Usually you know what type of data you expect for a given field because you aren't processing them generically, so it would rarely be a useful feature.
perhaps (hopefully) I miss something?
No.
Well here is the breakdown;
GET accessed via $_GET in PHP tackling and POST accessed via $_POST in PHP are transport methods, so is PUT, and DELETE etc for a from it does not matter what method you use it only works on client side and only knows to map every thing in it into serialised query string or at least have it read for being serialised.
For example
<input type="text" id="firstname" name="fname">
it takes the name attribute and converts into this
?fname=ferret
See it didn't even bother with ID attribute. When we hit submit button form will only run through name attributes of each input and make LHS of the with value and add user input as RHS to the value. It will not do anything else at all.
On PHP side we ask $_GET tunnel are there any query strings in the request or $_POST tunnel. Each of these if there is any query string - emphasis on word string. explodes the string into array and gives it you. hence $POST['fname'].
Looks something like this
$_POST = [
fname => 'ferret',
someothingelse => 'someothervalue']
SO what you are trying to do is or at least asking to do is ...make browser change its BOM behaviour - which we cannot in real sense of the matter; to make form add some thing like this.
?fname=ferret,text
?fname=ferret-text
?fname=ferret/text
form by default will not do this, unless you run custom function updating each query before submit and that is pron to what we call escaping, 3/100 time you would miss it given the chance
Then on PHP side you want PHP to figure out on its own that after slash is type like so
$_POST = [
fname => 'ferret/text']
PHP would not do that on its own, unless you fork it make custom whatever like Facebook has done and then run it or at least make some kind of low level library but that too would be after the fact.
in case your not wondering, thats how XSS and injections happen.
SO query string standards are rigid to keep things a string with militaristic data and serialised.
So yes what you intended to do with hidden field is one tested way of achieving what you are want.

Reuse of html element ids?

I have a page with three different forms. The second has to have access to the post vars submitted by the
first. The third has to have the cumulative post vars.
Even though an element such as a hidden field has the same id as another form element, it should
be valid if it exists under a different form element, right? I have done this in the past without problem
as far as submission processing, but the xhtml doctype syntax checker in my text editor (BBedit on Mac OSX) marks
the re occurrence of an element id as an error.
To be completely valid with respect to doctype I have to use xhtml transitional to allow name attributes (forms
won't submit with out them)
I don't want to have three different sets of hidden fields to transmit the same values for each different form
That requires huge amounts of redundant processing on the server side.
Thanks for reminding me that I can use the same name attribute and different ids. Sometimes I get wrapped up
in details and loose sight of the bigger picture
By the way, I posted a problem with using one form for the entire setup at:
https://stackoverflow.com/questions/21315920/browser-caching-post-vars
and I have not received any definitive answer there.
The id attribute MUST be unique per document. However, if you simply want various fields to accessible using the same key server-side, simply set the name attribute. name has no such requirement and can differ from the id.

Why is the `NAME` attribute considered unsafe?

I'm passing user-generated HTML into a database and I'm trying to make sure that no malicious code is passed through. One of the steps I'm taking is to run passed code through pear's HTML_Safe class to remove vulnerable markup. However, one thing I've noticed is that the name attribute of submitted elements gets removed. Sure enough, when you look at the source code, name is one of the few attributes that's blacklisted by default:
http://pear.php.net/package/HTML_Safe/docs/latest/HTML_Safe/HTML_Safe.html#var$attributes
What's the danger in allowing users to pass values for name? How can values for name be used to nefarious ends? Any thoughts? If not, I'm tempted to modify the blacklist.
In HTML form elements, the name attribute is used as an identifier. Therefore, if you allow name then someone may be able to override your HTML name attributes (that you may have used) with one of their own. The first matching name found is often the one used by either Javascript or server side processing.
This would then allow someone to exploit any possible Javascript or server side form processing you may be using that references the first matching name attribute found.
It is not just form elements that can use name, but they would be the least safe ones.
Another override issue is if you are using Javascripts getElementsByName in any of your functions (as pointed out below), you could end up with a function that does not do what you expect.
Edit: Some corrections and a note about getElementsByName issue (as pointed out below).

Is it always bad practice to start an ID with a number? (CSS)

In my project I have submissions and comments, each with an ID. Currently the ID's are just numeric and correspond to their database ID's. Everything is working fine but when I run it through the W3 validator I get the error:
value of attribute "id" invalid: "1" cannot start a name
I suppose instead that I could just precede all ids with some sort of string but then whenever I was using or manipulating the id in JQuery or PHP I have to do a id.replace('string', '') before using it. This seems rather cumbersome. Any advice?
Yes, using numbers as HTML element IDs is bad practice.
It violates W3C specification.
You noted this in your question, and it is true for every HTML specification except HTML5
It is detrimental to SEO.
Search-engine optimized HTML element IDs SHOULD reflect the content of the identified element. Check out How To Compose HTML ID and Class Names like a Rockstar by Meitar Moscovitz. It provides a good overview of this concept.
There can be server-side scripting issues.
Back when I first started programming in ASP classic, I had to access submitted form fields by a syntax like Request.Form("some_id"). However, if I did Request.Form(1) it would return the value of the second field in the form collection, instead of the element with an Id equal to 1. This is a pretty standard behavior for working with collections. Its also similar with javascript, and could make your client side scripting more complicated to maintain as well.
I suggest you to use prefixes "comment-ID" or "post-ID".
If you need the id in JavaScript, you just have to id.substring(8) (for "comment-")
The HTML 5 Specification lifts this restriction. If you're worried about validity you might simply consider changing the DTD to HTML5's.
http://www.w3.org/TR/html5/elements.html#the-id-attribute
If you're manipulating the element then you can just use $(this).jQueryOperation() - therefore you can have a prefix without having to replace anything!
The best way for your need is having the prefix for your class, I mean something like item-x and x is the number that you need.
But from my personal experience, it is better to use classes for your elements, and you know that you must use classes if the item is not unique in the page

Form input field names containing square brackets like field[index]

I've seen a lot of PHP code that handles form input in which the input field names contain square brackets. I understand that this somehow results in PHP arrays when a PHP script examines the $_POST variable.
Example HTML:
<form action='http://zzz.com' method='post'>
<input name='fruit[1]' value='apple' />
<input name='fruit[2]' value='banana' />
</form>
Example URL:
http://zzz.com?fruit[1]=apple&fruit[2]=banana
Example PHP:
assert($_POST['fruit'] === array(1=>'apple', 2=>'banana'));
My questions about this:
What is the mechanism behind it? At what point do these names that contain brackets get converted into arrays? Is this a feature of the HTTP protocol? Of web servers? Of the PHP language?
Continuing the previous question, is this a commonly used hack or a normal programming tool?
What are (all) the rules for using brackets in input field names?
Can multidimensional arrays be created this way?
What is the mechanism behind? At which
point this names that merely contain
brackets are converted to arrays? Is
this a feature of the HTPP protocol?
Of web servers? Of the PHP language?>
This is a feature of the PHP language. In fact, the HTTP protocol does not forbid the use of multiple identical GET/POST parameters. According to the HTTP spec, the following:
foo=bar&foo=baz
Should not result in foo == baz. These are two parameters with two different values. However, PHP will overwrite the former foo with the latest, resulting in $_POST['foo'] == 'baz', even if they could be parsed separately.
Continuing the previous question, is
this a commonly used hack or a normal
programming tool?
It depends on the point of view. In the PHP world, it is completely normal, as the language does not support the specification of multiple parameters of the same name without using the brackets []. In the HTTP world though, foo != foo[].
What are (all) the rules of using
brackets in input field names?
The same as PHP arrays, except that you don't have to quote string keys.
Can multidimensional arrays be created
this way?
Yes, you can.
To my knowledge, this is a mechanism of PHP internally seeing (and parsing) elements passed via form (GET/POST) with the [] postfix and interpreting them as an array of elements. The HTTP protocol doesn't care, it merely passes the element's name with it's associated value in the query string.
It's been a normal programming tool as far back as I can remember (I think I even remember it more commonly used for multi-file uploads back when you had "add file" links that appended another element to the form, using the same name (with []) as the previous.)
The same rules that apply in PHP apply in the form. You can use [] to auto-index the elements (for generic lists) or explicitly list them using element IDs (e.g. file[1], file[2], etc. (following my previous example))
Yes, multi-dimensional arrays can be used.
For more information, check out PHP's very own _POST documentation (especially the comments)
This is completely php language feature. HTTP knows nothing about arrays. In http either foo or bar[baz] is just a names of variable
It is a normal practice
Use them when it is handy for you. For example: to group several fields, that belong to one entity, such as news[title] + news[body]
Yes. TIAS

Categories