hidden field in php - php

For hidden fields, can i use a field of the type
<input type="hidden" name="field_name" value="<?php print $var; ?>"/>
and retrieve it after the GET / POST method as $_GET['field_name'] / $_POST['field_name'] ?
are there any other ways of using hidden fields in php?

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.
Field definition:
<input type="hidden" name="foo" value="<?php echo $var;?>" />
Access w/ PHP:
$_GET['foo'] or $_POST['foo']
Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php
Cheers!

Yes, you can access it through GET and POST (trying this simple task would have made you aware of that).
Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.

Can I use a field of the type ... and retrieve it after the GET / POST method ...
Yes (haven't you tried?)
Are there any other ways of using hidden fields in PHP?
You mean other ways of retrieving the value? No.
Of course you can use hidden fields for what ever you want.
Btw. input fiels have no end tag. So write either just <input ...> or as self-closing tag <input .../>.

Related

Get Tag As Value For Imput Type

I am needing a GET value to be placed display in a forum option, however I do not know how to do this, as the get value can not have quotes in it. The xxx is where I want to display the get value.
<input type="text" name="test" value="xxx">
This is really basic stuff. Should not be any problems to find by Google.
<input type="text" name="test" value="<?php echo $_GET['your_parameter']; ?>" />
You should escape the GET parameter before echoing it, unlike the other answer. This will prevent someone from injecting extraneous tags into your code.
<?php
$parameter = (isset($_GET["your_parameter"])) ? htmlspecialchars($_GET["your_parameter"]) : '';
?>
<input type="text" name="test" value="<?= $parameter ?>" />
If you have short tags disabled, you'll need to use <?php echo in place of <?=. Many (most?) PHP developers will argue that you shouldn't use short tags at all. I personally never use them because I don't write my templates in PHP.
As Jimmie Johansson mentioned before this is really basic stuff and easy to search for.
Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.
Source: http://www.php.net/manual/en/tutorial.forms.php
If you transmit data via a FORM to php there are to ways to transmit the data. The first one ist via GET the other way is via POST.
If you choose GET your information will be stored as URL-Parameters
An associative array of variables passed to the current script via the
URL parameters.
Source: http://www.php.net/manual/en/reserved.variables.get.php
Post instead just sends the data to the PHP-Script so you can use this data like GET but you do not have any URL-Parameters here.
An associative array of variables passed to the current script via the
HTTP POST method.
Source: http://www.php.net/manual/en/reserved.variables.post.php
To choose one of this two Methods you have to edit your HTML-Form
Now that we transmitted the data either with GET or POST we can access them in PHP via the global variables
$_GET
and
$_POST
They are Arrays and you can access specific data with a key which represents the name of the input field or other form constructs. In your example the input fields name is "test" so we would access it like this
<?php $_GET["test"]; ?>
You can use
<?php ... ?>
Wherever you want in your HTML-Code as long it's an PHP File. So if you want to output something via PHP just use the and put you statements between them.
<input type="text" name="test" value="<?php echo $_GET['your_parameter']; ?>" />
Documentation
Arrays:
http://php.net/manual/de/language.types.array.php
Forms:
http://www.php.net/manual/en/tutorial.forms.php
http://www.w3schools.com/php/php_forms.asp
PHP and HTML:
http://www.php.net/manual/en/faq.html.php
POST and GET:
http://php.net/manual/de/reserved.variables.post.php
http://php.net/manual/de/reserved.variables.get.php
Further Reading
Further reading
http://en.wikipedia.org/wiki/Separation_of_presentation_and_content
http://wp.tutsplus.com/tutorials/creative-coding/improving-your-work-flow-separate-your-mark-up-from-your-logic/
http://www.w3schools.com/tags/ref_httpmethods.asp
And the important things at the end. For security you should check what was entered into the input field
http://www.w3schools.com/php/php_form_validation.asp
If you have problems to follow my answer feel free to ask me. Check the links!

POST a custom Tag?

I have the following input in a form
<input name="email" type="text" id="email"size="50" english="Email address" />
I have a custom tag called english, My question is can I send this as post data and can I recover it on my new page ?
Any help would be much appreciated , Thanks
If you use JavaScript to submit your form, you can read you custom tags' values ad append them to the form data to send. Otherwise, clean HTML form just submits only input tags value.
The best method I can think of right now is to have hidden field with the label as value. Like
<input name="email_label" type="hidden" id="email_label" value="Email address" />
The short answer is: no. The post data received from the HTML in your question will be an array with email as the key, and whatever the user typed as the value.
The solution depends on the problem you're trying to solve. Consider using a hidden input tag instead. For example:
<input name="language" type="hidden" value="English" />
Alternatively, a neater solution would be to store the language in the session (assuming that does what you need). You should never rely on the front end of a website "telling" the back end stuff like this, at least to a certain degree. The back end should just "know".

PHP, pass array through POST

Which is the most secure way to send an array through POST?
foreach ($id as $array)
{
<input type="hidden" name="prova[]" value="<?php echo $array; ?>"/>
}
<input type="submit" name="submit"/>
or using implode() to create a single variable, pass the variable and then use explode() to get back the values into a new array?
Edit If you are asking about security, see my addendum at the bottom Edit
PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.
$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);
This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.
Addendum
I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.
http://php.net/manual/en/reserved.variables.post.php
The first comment answers this.
<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>
<?php
var_dump($_POST['person']);
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>
The name tag can work as an array.
You could put it in the session:
session_start();
$_SESSION['array_name'] = $array_name;
Or if you want to send it via a form you can serialize it:
<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />
$passed_array = unserialize($_POST['input_name']);
Note that to work with serialized arrays, you need to use POST as the form's transmission method, as GET has a size limit somewhere around 1024 characters.
I'd use sessions wherever possible.
There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).
XSS
XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:
" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="
This would be written into your form like so:
<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>
The best way to protect against this is to use htmlspecialchars() to secure your input. This encodes characters such as < into <. For example:
<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>
You can read more about XSS here: https://www.owasp.org/index.php/XSS
Form Modification
If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.
I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg with ../index.php or ../db-connect.php).
In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.
Why are you sending it through a post if you already have it on the server (PHP) side?
Why not just save the array to s $_SESSION variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.
It all depends on what you really want to do.

How can I populate the fields of a PHP form automatically when the field values are in the url?

I have a have in PHP and I have common fields such as 'Name' and 'Surname'.
Now when the user visits the page e.g. http://www.example.com/form.php the form fields 'Name' and 'Surname' are empty.
I would like to now have a link similar to this http://www.example.com/form.php?name=John
so that when the client hits the link the PHP form will now have the name field already filled with 'John' in it.
I know this can be done in HTML but how can I do it in PHP?
Just to let to know I do not own the PHP form - I just want a link from my website to fill the PHP form (which I do not have control over).
Thanks in advance.
Can be done using $_GET
An associative array of variables passed to the current script via the URL parameters.
e.g.:
<? php
if(isset($_GET['name']))
{
$test = $_GET['name'];
}
?>
<html>
<body>
<form>
<input type="text" name="test" value="<?php if(isset($test)){echo "$test";}?>"/>
</form>
</body>
</html>
Note: code isnt tested or anything.. Also, there are possible security risks with getting values from your URL (can be considered user input), so make sure you are aware of that and how to prevent
You could store that value and then when you're about to output the input fields
you just pass along the stored value.
$name = $_GET['name'];
// ... later on
echo '<input type="text" value="'.$name.'"/>';
By using $_GET superglobal
<input name="name" value="<?php echo !empty($_GET['name']) ? $_GET['name'] : '';?>" />
<input name="surname" value="<?php echo !empty($_GET['surname']) ? $_GET['surname'] : '';?>" />
You can use the get method in php to get the name and make use of it
You can retrive this information by the $_GET["name"] function, or $_REQUEST["name"].
Reserver variables
Be carefull with those operations, you might have validation a/o security problem.
Note: if you are not sure that the "name" variable is set or not, you have to use also the
isset function to test it.
You can use the $_GET superglobal, so your input could look like this:
<input type="text" name="name" value="<?php if(isset($_GET['name'])) { echo $_GET['name']; } ?>" />
The $_REQUEST superglobal does a similar thing but I would just use $_GET.
It looks like everyone's answers here assume you are building the form yourself, which doesn't appear to be the case based on your question.
The thing that you want to do may or may not be possible. If the form accepts certain kinds of parameters in certain ways, you may be able to hook in to that functionality and set it up so that when someone clicks a link on your page, that information gets passed to the other page.
One way forms can accept this information is in the form of a "get" request. With this method, values are passed as part of the url, as in your example: http://www.example.com/form.php?name=John. Assuming your page has access to a php variable called $name, you can create a link from your code to build this kind of url like this:
Sign up!
If the page does not accept get parameters in this way (and I have a hard time imagining that they would), you may have to try other techniques to send along the information (assuming that they will even accept it!). The two other ways I imagine you could do this are by passing the value with "post" or creating a cookie for the page. If you tell us what page you are trying to set up this behavior on, we might be able to examine it and give you a better answer.

Simplifying PHP forms that pre-populate with dabase data and error check, so actively overwrite with $_POST data

Ok, so this is a common scenario.
You have an html form that involves editing information. The original information comes from the database. When you post the form, it may not save the information immediately, because something may need fixing when the data-checking is done, maybe one of the required fields is left blank. As a result, you want to redisplay the form field, but if there was post data, display the post data, if not, display the original data from the database.
So I created a function to check post, then default to some arbitrary data (in this case from the database).
But overall, the approach feels inelegant, the POST data is being pulled invisibly inside the function from a global, but if I pass the post data in I have to pass it in for every function call, and it's almost as verbose as just doing it by hand each time, so specifically I'm looking for alternatives to this approach, and generally I'd love advice on better ways to deal with this form scenario that I deal with every single time I edit html forms.
// Pull from post or get, or else use data, e.g. from the database, to populate a form.
function in_or_data($index, $data, $trim=false){
return $_POST[$index]? ($trim ? trim($_POST[$index]) : $_POST[$index]) : $data[$index];
}
<?php
$item_name = in_or_data('item_name', $data_from_database_somewhere); // Pull post data, with defaults coming from the
?>
// ..... Later, some example html that just escapes & echoes out the data. .....
<td id='item-name'><input name="item_name" type="text" id="item_name" value="<?php echo escape($item_name); ?>" size="47" maxlength="100" tabindex="9"></td>
How can I improve dealing with forms that get their data either from the database initially, or from post after some kind of submission is being done?
<input type="text" name="abc" value="<?php array_key_exists('abc', $_REQUEST) ? $_REQUEST['abc'] : "default value goes here" ?>" />
A more elegant solution, though a serious amount of work, would involve using ajax (jquery, etc.) to perform server-side validation on the form BEFORE actually submitting.
What you are doing seems fine to me. Basically what I do in the same situation is have a hidden field in the form something like
<input name="is_edit"` ... />
and in my PHP just check for $_POST['is_edit'] so that I don't populate anything from the database. One problem with doing every field individually like you are doing it above is that for certain things (for example checkboxes) if the user doesn't check the checkbox, $_POST['checkbox_data'] is not going to be set, so I believe you would end up pulling that from the database using the function you have above. It should be either all or nothing that is pulled by the DB. I therefore do something like this:
<?php
if (isset($_POST['is_edit'])) {
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
// etc
}
else {
$data = do_db_query_and_get_data();
$var1 = $data['var1'];
$var2 = $data['var2'];
// etc
}
?>
<input type="something" value="<?php echo $var1; ?>" />
<input type="something" value="<?php echo $var2; ?>" />
<input type="hidden" name="is_edit" value="1" />
Doing it like this also has the other advantage of not having to do the database query unless it is necessary.
In addition to my initial php code, I have started using the html5 attributes like required and setting the html5 form types like number, email, etc. It has really really made my forms much better for browsers that support html5 form aspects, and it degrades to standard text boxes and ignores the required attribute in browsers that don't support html5 form stuff.

Categories