PHP Shorthand for isset form POST value - php

I am creating a form and am just looking for more efficient ways to do things. What I have so far is:
<p><input type="text" name="transmission" value="" /></p>
<p><input type="text" name="model" value="<?=$model;?>" /></p>
So some of them will have a value already set, and some will be blank. What I want to do is see if the form has been set, and if it has then use $_POST['name'] as the value, if not then use either blank or use the previous variable I have.
<p><input type="text" name="name" value="<?php if isset($_POST['submit'])) { echo $_POST['name']; } else { echo ""; } ?>" /></p>
But there has to be a shorter way to do that.
IF anyone could point me in the direction I would really appreciate it.
Thank you!

You can define variables in beginning of your script before HTML output, for example:
$name = isset($_POST['submit']) ? $_POST['name'] : null;
in your html section you can print $name without worrying it was not defined
<p><input type="text" name="name" value="<?php echo $name ?>" /></p>
Also if $_POST['submit'] does not contain any value you are more likely to receive FALSE statement. To avoid such issues use array_key_exists

Like Nazariy said, you should avoid as much PHP in the template as possible.
In fact, you should have in your template already prepared variables only.
So, in your code have something like this
$FORM = array();
$form_fields = array('name','sex');
foreach($form_fields as $fname) {
if (isset($_POST[$fname])) {
$FORM[$fname] = htmlspecialchars($_POST[$fname]);
} else {
$FORM[$fname] ='';
}
}
and then you have smooth and neat template:
<p><input type="text" name="name" value="<?=$FORM['name']?>" /></p>

Without going into the reasons not to use <p> to structure your forms, there's not much that can be done besides removing the else.
<p><input type="text" name="name" value="<?php if isset($_POST['name'])) echo $_POST['name']; ?>" /></p>

Shorthand <?=$_POST['name'] ?: ''?>

Use the php error control operator: #.
<?php
$posted_text = #$_POST['posted_text'];
echo $posted_text
?>
If the POST variable is set, it will be echo-ed out. If not, nothing will show up.

You could try this...
$_POST['submit'] ? echo $_POST['name'] : echo '';
I'm using a boolean compare instead of the isset function (see link for table)
http://www.php.net/manual/en/types.comparisons.php
or an other option is...
echo ($_POST['submit'] ? $_POST['name'] : '');

<?= isset($_POST['submit'])? $_POST['name'] : ""; ?>
Is the shortest you'll get it, apart from say <?= $_POST['name']; ?> (if submit is not set name should be empty anyway) - you probably need to turn warnings off.
All that being said, this is very very poor practice and opens you up to cross site scripting (XSS). You should NOT be doing this. Even on an intranet, if an attacker ever owns a computer that has access to it they can use XSS to perform any actions the user can.
From your question and how much distaste you have for this type of echoing on screen I'd suggest you use some form of templating library such as Smarty. This allows your html code to look like this:
<p><input type="text" name="name" value="{name}" /></p>

I just saw this from wordpress coding standard. although they not encourage for the readability..
isset( $var ) || $var = some_function();
reference here

Related

Trouble writing a string value with spaces to a form [duplicate]

When I use PHP to set the value of a HTML form input element, it works fine provided I don't have any spaces in the data.
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? "value = ".$_POST["username"] : "value = \"\""; ?> />
If I enter "Jonathan" as the username, it is repeated back to me as expected. If I enter "Big Ted", however, I only get "Big" repeated back when I submit the form.
Note that the $_POST["Username"] variable is correct; when I echo it using PHP, it is set to "Big Ted".
Quote it. Otherwise the space will just become an attribute separator and everything after spaces will be seen as element attributes. Rightclick page in webbrowser and view source. It should not look like this (also see syntax highlight colors):
<input value=Big Ted>
but rather this
<input value="Big Ted">
Not to mention that this would still break when someone has a quote in his name (and your code is thus sensitive to XSS attacks). Use htmlspecialchars().
Kickoff example:
<input value="<?php echo (isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''); ?>">
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? "value = '".$_POST["username"]' : "value = ''"; ?> />
You have to wrap the variable result with quotes, so that the browser can know what's the content of the input.
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? ('value = "'.$_POST["username"].'"') : "value = \"\""; ?> />
Be aware of your quote usage.
As you see its not PHP5 or even PHP question at all.
Basic HTML knowledge is obligatory for one who want to be a PHP user.
And with using templates it looks way more neat:
Getting data part code:
$username = "";
if isset($_POST['username'])) $username = htmlspecialchars($_POST["username"]);
And template code:
<input type="text" name="username" value="<?=$username?>">
If you divide your code to 2 parts it become way more supportable and readable.
just make sure you put the colon after the field for example :
<option value="'.$row['name'].'">
Used quotes and it worked.
On the other side, needed to use the following:
$param=preg_replace('/[^A-Za-z0-9 ]/','', $param);

pass php value to html element without using echo

I am getting a value with php $_GET[], and I want to pass it as the value of a simple html input element. I know I can do it like this:
<?
$value = $_GET['value'];
echo '<input type="text" name="value" value="'.$value.'" />';
?>
But is there any way to separate the php from html, giving the value to the textbox without echoing it?
I would like to create the textbox as regular html element, and only use php in the part where I set its value.
The answer of Iaroel was more practical for my purposes, but I liked the way that the accepted answer covered many concerns - I think it will be more valuable to other users.
You don't want an error when the $_GET['value'] becomes undefined.
<?php
$value = isset($_GET['value'] ? $_GET['value'] : '');
?>
<input type="text" name="value" value="<?php echo $value; ?>">
But be mindful with malicious data that can be inserted in $_GET['value'] so you've got to apply proper sanitation to $value
With regards to "Getting $_GET['value'] without PHP"
You can get it without PHP script by creating a small javascript function:
<script type="text/javascript">
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
</script>
What the hell was that regular expression? It's just a matter of matching pattern from the URL.
Now, you can use this $_GET() method to assign the value to that textbox. In this example, I used jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('input[name="value"]').attr('value', $_GET('value'));
});
</script>
Now your HTML code will be as simple as this:
<input type="text" name="value">
Reference: http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
If you don't wish to echo anything inside HTML, use Ajax call to get values.
$.ajax({
url: 'getValues.php',
type: 'post',
dataType: 'json',
success: function (json) {
if (json) {
$.each(json, function (k, v) {
$(k).val(v);
});
}
}
});
[PHP]
echo json_encode(array('#first_input_id' => 'val1', '#second_input_id' => 'val2', '.some_classes' => 'val5'));
Or if values are static, you can use local json file.
Do you mean like this?
<?php
$value = $_GET['value'];
?>
<input type="text" name="value" value="<?php echo $value;?>" />
Or this (not advised):
<?php
$value = $_GET['value'];
?>
<input type="text" name="value" value="<?= $someVar ?>" />
But i would suggest looking into a template engine for example http://www.smarty.net/
If your php configuration allows short tags you can do this:
<input type="text" name="value" value="<?=$_GET['value'];?>" />
you can try without echo
<?php $value = $_GET['value'];?>
<input type = "text" name = "value" value="<?= $value; ?>" />
If its really important for your project, ideally you want to separate your php code from your html tags. this can achieve by using some template engine.
There are some well known options available, best if you check and see which one suites your use-case best.
Mustache
Smarty
and of course Twig
You can use PHP Heardoc option. find the link here.
http://www.hackingwithphp.com/2/6/3/heredoc

Initialise a html input text field from a php variable

I'm a beginner to web programming and need help with html input field initialisation from a php variable. I have one php file with a table with input fields and buttons etc. javascript and jquery is used to handle the processing. Now I want to get data from a server which will be stored in php variables. This is a code extract:
<body>
<php?
$voltage = "012";
// $_POST['voltage']; // tried this
?>
<table>
<td><input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo $_POST['voltage'];?>" size="3" maxlength="3" />
%</td>
</table>
</body>
I get a message Undefined index : voltage
At this stage I am working with XAMPP localhost and don't have any database, I need to be able to handle the variables locally before worrying about the DB.
Any help would be much appreciated.
Try isset()
<input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo isset($_POST['voltage'])?$_POST['voltage']:'';?>" size="3" maxlength="3" />
if you want to use the variable $voltage your code should look like this:
<input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo $voltage; ?>" size="3" maxlength="3" />
you can set $voltage with a specific posted var
$voltage = $_POST['voltage'];
but you should test if your variable $_POST['voltage'] is set, because you will get your mentioned error if nothing or just this variable is not posted
you can do this with isset
if(isset($_POST['voltage'])
{
$voltage = $_POST['voltage'];
}
else
{
$voltage = '';
}
I get a message Undefined index : voltage
Was there a voltage value posted in the form? There's an order of events taking place here. First your server-side code executes, then the page renders, then the user posts the form value to server-side code. So if in the first step you're looking for a form value:
$_POST['voltage'];
That value isn't going to be there because the user hasn't posted it yet. You can test for the value before trying to use it:
if (isset($_POST['voltage'])) {
// the value exists
}
This is commonly used when the same page (and, thus, the same server-side code) is used for both creating the form and handling the posted form. If that's the case for you then you'll need to include such conditionals because the server-side code can't use form values that aren't posted yet.
Just use $voltage. The $_POST array will only have values in it if a form submitted values to your script.
<td><input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo $voltage;?>" size="3" maxlength="3" />
1) May-be you should consider doing : (despite it's not recommanded, that's what you're trying to do)
$voltage = "012";
$_POST['voltage'] = $voltage;
2) You don't need $_POST variables. Just echo $voltage !

CodeIgniter highlight fields with errors on form submission

I could use some guidance in how to proceed on form validation in CodeIgniter. I am using CodeIgniter's built-in form validation and works fine as far as it goes. It returns individual error messages for each field where there is an error by using and wrapping it in some HTML/CSS for styling:
<?php echo validation_errors('<p class="error">'); ?>
But what we want to do is highlight the fields where there are errors. CI will let you put the error messages next to where the form errors are. But it requires you to use the error message for the value, like this:
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
which by the way is in CI's manual in non-CI syntax, which puzzles me. Anyway, we also want the data from the field when the form is submitted to be preserved and returns. So I've done:
$email = array('name' => 'email', 'value' => $em);
?><div style="padding:5px;">Email* </div><?php echo form_input($email) . '<br/>';
$em is returned from the controller like this:
$data['em'] = $this->input->post('email');
So my question is, how do I accomplish all of what is outlined above? Obviously, what CI suggests and what I have done collide. But I don't know how else to do it, so I could use some help.
EDIT: Upon further digging, I see that you can put the error message next to the field by doing this:
<?php echo form_error('email'); ?>
But I'm not getting any message upon an error, even though I have the rule written and I get an error with the first line of code above.
form error($field) returns an empty string '' so better use:
<input type="text" name="email" <?php if (form_error($email) !=='') { echo 'class="error"'; } ?> value="<?php echo set_value('email'); ?>" size="50" />
Tested.
In order to display error individually you should use the function form_error('email'). And for you to get a value of a field being checked, use the function set_value('email'). For these two functions to work, you would have had to, in your controller, set a rule for the 'email' field. Where you specify wich validation rules apply to that field.
<?php echo form_error('email'); ?>
<input type="text" name="username" value="<?php echo set_value('email'); ?>" size="50" />
source: http://codeigniter.com/user_guide/libraries/form_validation.html#individualerrors
untested, but form_error($field) should return true if there is an error:
So perhaps:
<input type="text" name="email" <?php if (form_error($email)) { echo 'class="error"'; } ?> value="<?php echo set_value('email'); ?>" size="50" />
untested. worth a shot?
Perhaps also consider using JQuery or similiar to validate and style the form fields, and use CI as a fallback (for presentation purposes, obviously).
That way your form validation can be styled as you required without CI limitations for 99% of validation rules, and then anything else, the default CI way can kick in.

How to set HTML value attribute (with spaces)

When I use PHP to set the value of a HTML form input element, it works fine provided I don't have any spaces in the data.
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? "value = ".$_POST["username"] : "value = \"\""; ?> />
If I enter "Jonathan" as the username, it is repeated back to me as expected. If I enter "Big Ted", however, I only get "Big" repeated back when I submit the form.
Note that the $_POST["Username"] variable is correct; when I echo it using PHP, it is set to "Big Ted".
Quote it. Otherwise the space will just become an attribute separator and everything after spaces will be seen as element attributes. Rightclick page in webbrowser and view source. It should not look like this (also see syntax highlight colors):
<input value=Big Ted>
but rather this
<input value="Big Ted">
Not to mention that this would still break when someone has a quote in his name (and your code is thus sensitive to XSS attacks). Use htmlspecialchars().
Kickoff example:
<input value="<?php echo (isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''); ?>">
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? "value = '".$_POST["username"]' : "value = ''"; ?> />
You have to wrap the variable result with quotes, so that the browser can know what's the content of the input.
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? ('value = "'.$_POST["username"].'"') : "value = \"\""; ?> />
Be aware of your quote usage.
As you see its not PHP5 or even PHP question at all.
Basic HTML knowledge is obligatory for one who want to be a PHP user.
And with using templates it looks way more neat:
Getting data part code:
$username = "";
if isset($_POST['username'])) $username = htmlspecialchars($_POST["username"]);
And template code:
<input type="text" name="username" value="<?=$username?>">
If you divide your code to 2 parts it become way more supportable and readable.
just make sure you put the colon after the field for example :
<option value="'.$row['name'].'">
Used quotes and it worked.
On the other side, needed to use the following:
$param=preg_replace('/[^A-Za-z0-9 ]/','', $param);

Categories