keeping past value of a field - php

i'm using a php page and it gets refreshed(on submit) . i need to keep the value of a textfield from a previous submission. how to make it

If you're just posting data back to the same script that displays the form, just do something like:
<input type="text" name="foo" value="<?PHP echo $_POST['foo']; ?>"/>
If your user is going to go "away", and then come back to the page, you probably can get away with stuffing the stuff you want to save in $_SESSION.

yes, the above thing is correct. Eventually use AJAX so eventually you need not to refresh the page and data will be preserved.

tim is right, but you'll have to be careful about escaping user input. Ideally what you want displayed is exactly what the user types in. You'll probably find that html entities such as ' will get converted.
Slightly better:
<input type="text" name="foo" value="<?PHP echo htmlentities($_POST['foo']); ?>"/>

Related

update_options not updating wp_options table

I am making a form for the admin area of WordPress. Here is the code so far;
<form method="post" action=options.php">
<?php update_option('gpspl_options', $gpspl_options);?>
<input type="text" name="gpspl_options" value="$gpspl_options"/>
<input type="submit" value="Save Changes"/>
</form>
On the page in the admin area the text box is auto filled with "$gpspl_options". However when I add the text and hit submit it does not update the wp_options table in the database.
What am I missing?
You always call update_option() on whatever is stored in $gpspl_options. You never do anything with the posted value ($_POST['gpspl_options']). So the posted value never gets saved. If you want to save the posted value, you need something like this:
if (isset($_POST['gpspl_options'])) {
update_option('gpspl_options', $_POST['gpspl_options']);
}
As for the text field, you always initialize the text field to the literal string "$gpspl_options" (not the value of the variable $gpspl_options). To use the value, you need something like this:
<?php
$gpspl_options = isset($_POST['gpspl_options']) ? $_POST['gpspl_options'] : '';
?>
<input type="text" name="gpspl_options" value="<?php echo $gpspl_options; ?>"/>
You might want to read an introductory PHP tutorial covering variables, variable names, output, and so on.
That said, all this mixing of logic and output is not good practice. It's what Wordpress does and therefore kind of encourages, but that doesn't mean you should do it, too.

I'm using a hidden input field to move data, is there a better way?

I'm using a hidden input tag to pass a variable to a PHP script. This is the tag,
<input type="hidden" name="batch" value="<?php echo $batch; ?>">
The variable $batch is generated on the page upon user input and this variable needs to go a script which is why I have used a hidden input tag.
I feel this isn't very secure as the value left by the variable $batch can be changed using the developer toolbar or firebug.
To make it more clear,
<input type="hidden" name="batch" value="7">
is what I see using firebug. I can change the value of $batch and then submit the form.
Is there a better way to do this?
You can use sessions too. That'd be more secure, in my opinion since it can't be viewed on the client side.
Try this:
$_SESSION['batch'] = $batch;
Once the session is stored, you can access this value in any page you want by writing:
echo $_SESSION['batch']; // Output: 7

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.

Sending form data to one page, then another?

I'm having a bit of trouble with this one, as basic as it may be. I have a simple form with name, email, comments, etc. that outputs itself to one php page, but I want to have a link that sends it to a second page, for example:
<label for="name">Name:</label><input type="text" name="name" size="20" />
Goes to a second page (second.php) with this code and prints it just fine:
print "<div>Thank you, $name.</p></div>";
But if I try to send $name to a third page (third.php) using similar code it shows up like this:
Thank you, $name.
With the actual variable and not what was stored in $name.
I feel like I'm missing one tiny little thing but I'm not sure what it is. I used this:
$name = $_POST['name'];
To bring it to second.php and this to bring it to third.php:
print 'Click here to proceed.';
Just to see if it would get the same information from second.php, but I don't think it works that way. Is there something else I should be doing on the third page? I have a feeling it's something incredibly insignificant but as I'm learning, I just can't quite get a grasp on it.
You can do it this way.
when you declare
$name = $_POST['name'];
you can use in a header to pass this variable
if(isset($_POST['btnname']))
{
header('Location: second.php?name='.$name);
}
The in your second php
you can get it by this way
Thank you, <php echo $_GET['name']; ?>
Or if you want it to be available to all pages use session
$_SESSION['name'] = $_POST['name'];
=D
you can try it using a hidden input
<label for="name">Name:</label>
<input type="hidden" name="name" value="<? echo $name; ?>" size="20" />
Websites are stateless, which means that the variables only last for a few seconds on the server, then the html is rendered, and sent to the clients browser. The server memory is then freed up to serve other clients.
You have a few options:
1) Using a hidden form field and printing (with php) their name to the hidden form field so when they post again it gets saved (if they post again).
2) Sessions
3) cookies
4) Print it out in the url (i.e. page.php?name=".$name; )
It all depends on how you get to your third page (From a link? A form? A php redirect?)
You can store the name in the second page and again set the $_GET variable before the third page is called. This is because the variables are only valid for that particular request and they need to be set again when another request is made.

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