I am just starting to learn php, how would I initiate a echo statement after a submit button is pushed, or even a anchor tag.
Here is my code so far
form name="myform" method="get" actions="madlib01.php"
Name: <input type="text" name="name" /> <br />
<input type="submit" name="submit" />
form
<?php
$Name = $_GET['name'];
$hello .= "Hello $Name";
echo $hello //I would prefer the echo to happen after the submit button is hit
?>
the correct attribute for your form tag is "action", not "actions"
When the form is submitted, a new request is sent to the server (in your case, using GET).
So to do it all in one page:
form.php:
<form action="form.php" method="GET">
<input type="text" name="name"/>
<input type="submit">
</form>
<?PHP
if (! empty($_GET['name'])){
echo 'Hello, ' . $_GET['name'];
}
?>
You will first need to check if PHP has received your GET parameter using isset or array_key_exists:
if(isset($_GET['name']) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
}
or:
if(array_key_exists('name', $_GET) && !empty($_GET['name'])) {
$Name = $_GET['name'];
echo "Hello $Name";
} else {
//example: default to something if nothing has been passed
echo "Hello Guest";
}
Also note, if you're submitting to the same page, you can omit the action attribute from your form tag altogether:
<form method="GET">
echo $hello
You've just gained an HTML-injection vulnerability. If someone sends your user to:
http://www.example.com/madlib01.php?name=<script>stealYourCookies()</script>
you've got problems.
Yes, this is a My First PHP Script. That doesn't make security optional. This is a mistake every tutorial makes: teaching bad practice from the start, treating correctness (and security, which is a subset of correctness) as an optional extra.
The result is that most PHP code out there is full of holes. But there's no need for yours to be! Every time you place a pure-text string into a surrounding HTML context, escape it properly:
echo htmlspecialchars($hello);
I tend to define a function with a shorter name than ‘htmlspecialchars’ to do that for me, as I'm lazy.
<?php
function h($text) {
echo(htmlspecialchars($text, ENT_QUOTES));
}
$name= '';
if (isset($_REQUEST['name']))
$name= trim($_REQUEST['name']);
?>
...
<?php if ($name!=='') { ?>
<p> Hello, <?php h($name); ?>! </p>
<?php } ?>
<form method="get" action="madlib01.php">
<p>
<label for="namefield">Name:</label>
<input id="namefield" type="text" name="name" />
</p>
<p>
<input type="submit" />
</p>
</form>
Now if you say your name is Mister <script>, the page will greet you exactly as such, angle brackets and all, instead of trying to run JavaScript. This is the correct output and thus also secure.
Related
I can't seem to apply the $_POST function properly to retrieve the data from a simple HTML form. I'm new to PHP, so I may be overlooking something simple.
I have a form with action directing to the same page, but if the form is filled out, the value of $_POST['input_name'] will have changed, so I can trigger the php function using that condition. Is this the best way to structure this kind of action?
Here's my HTML code (thispage.php is the current/same page):
<form action="thispage.php" method="post">
Name: <input type="text" name="userName" id="userName" />
<input type="submit" />
</form>
Here's my PHP code from the same page:
if("" == trim($_POST['userName'])){
echo $_POST['userName'];
}
Thanks a lot in advance!!
First remove the action from form if your server side code is in the same page. And Use the empty() or isset() functions for checking the value.
For Example:
if(!empty(trim($_POST['userName']))){
echo $_POST['userName'];
}
if(isset(trim($_POST['userName']))){
echo $_POST['userName'];
}
if("" == trim($_POST['userName'])){
echo $_POST['userName'];
}
This is actually checking if the value is empty and echoes it if it is.
You probably want to use !empty($_POST['userName']) to check if it's not empty and then echo it if it is not.
try this:
HTML code
<form action="thispage.php" method="post">
Name: <input type="text" name="userName" id="userName" />
<input type="submit" name="submit" />
</form>
PHP code on the same page:
if(isset($_POST['submit']))
{
if(isset(trim($_POST['userName']))){
echo $_POST['userName'];
}
}
Try this...
if(trim($_POST['userName']) != ' '){
echo $_POST['userName'];
}
you can try it:
if(isset($_POST['userName'])){
$name = $_POST['userName'];
echo $name;
}
I'm learning PHP and trying to understand the if .. else statements a little better, so I'm creating a little quiz. However, I have come across an issue and I don't seem to know what the issue is. My problem is that whenever I type in the age in the input area, it will give me the $yes variable every time even if I enter the wrong age.
Here is my code so far:
My html file:
<form action="questions.php" method="post">
<p>How old is Kenny?<input></input>
<input type="submit" name="age" value="Submit"/>
</p></form>
My php file:
<?php
$age = 25;
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25){
echo "$yes";
}else{
echo "$no";
}
?>
You catch the user input inside the $_POST superglobal var (because the method of your form is POST.
So
<?php
$age = 25;
should be
<?php
$age = $_POST['age'];
There is an error in HTML too. This
<input type="submit" name="age" value="Submit"/>
should be
<input type="text" name="age" value=""/>
<input type="submit" value="Click to submit"/>
Because you want one input and one button. So one html element for each element.
and <input></input> must be cleared because it's not valid syntax :-)
<form action="questions.php" method="post">
<p>How old is Kenny?</p><input type="text" name="age"></input>
<input type="submit" value="Submit"/>
</form>
$age = (int) $_POST["age"];
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25) {
echo $yes;
} else {
echo $no;
}
<?php
/* Test that the request is made via POST and that the age has been submitted too */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['age'] ) ){
/*
ensure the age is an integer rather than a string ..
though for this not overly important
*/
$age=intval( $_POST['age'] );
if( $age==25 ) echo "Congratulations";
else echo "Bad luck!";
}
?>
<form action="questions.php" method="post">
<p>How old is Kenny?
<input type='text' name='age' placeholder='eg: 16' />
<input type="submit" value="Submit" />
</p>
</form>
A simple html form, note that the submit button does not carry the values you want to process, they are supplied via the input text element.
First of all, you need to echo the variable; echoing "$no" will keep it as a string. Remove the quotes from "$no" and "$yes" in your if then statement. Otherwise, your code seems sound!
every time i am refreshing the page and i am getting the same value stored in the post array.
i want execution of echo statement only after submit and after refreshing no echo results..
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
From just a form, you won't be able to check if it was a refresh, or a first submit, regardless of using GET or POST method.
To ensure a single message, you need to:
a. redirect the user to somewhere else after you processed the request.
if(isset($_POST['submit'])) {
// process data
header("Location: new-url");
}
And display the message on the other URL.
b. set a cookie / session variable, which tells you the form was already processed.
if(isset($_POST['submit']) && !isset($_SESSION['form_processed'])) {
$_SESSION['form_processed'] = true;
}
This second approach will kill your form until the user closes the browser, so you should do something more complex - like storing another hidden field in the form, and storing that in the session.
If you submit a form and then refresh the resulting page, the browser will re-post the form (usually prompts first). That is why the POST data is always present.
An option would be to store a session variable and have it sent in the form, then check if it matches in the form processing code - to determine if it is a re-post or not.
Within the form:
<input type="hidden" name="time" value="<?php echo $time; ?>" />
In the PHP:
session_start();
if(isset($_POST['submit']))
{
if(isset($_SESSION['time']) && $_SESSION['time'] == $_POST['time'])
{
echo "User name : <b> $name </b>";
}
}
$time = $_SESSION['time'] = time();
Another option is to redirect after processing the post data:
if(isset($_POST['submit']))
{
...
...
header('Location: ' . basename($_SERVER['PHP_SELF']));
exit();
}
You need to maintain a state as to whether $name has already been displayed or not. The easiest way is probably to maintain that state in a browser cookie.
<?php
$nonce = $_COOKIE['nonce'];
$new_nonce = mt_rand();
setcookie('nonce', $new_nonce);
if(isset($_POST['submit']) && $_POST['nonce'] == $nonce)
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="nonce" value="<?php echo $new_nonce ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
Problems
you are polluting the user “session” with stale variable.
this will break if your user opens several windows (or tabs) to the same page. To fix this you would have to change the nonce cookie into an array of nonces, and update it accordingly.
if you want refresh page after submit use
<form method="get"
sure if your form hasn't a lot of data and also need to use $_GET instead of $_POST variable:)
correct way for you, but this logic is not good, need to refactor this script:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User name : <b> $name </b>";
unset($_POST['submit']);
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
I am pretty new to programming and have absorbed some 150 pages of a book. I was going smooth with PHP when the code below bumped me hard. Can anyone explain about the positioning of opening and closing PHP tags.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<p>Thanks for Registering</p>",
"Username: ", htmlentities ($_POST['username']), "<br />",
"Email: ", htmlentities ($_POST['email']), "<br />";
}
else { ?>
<form action = "test.php" method = "post">
<label for = "username">Username: </label>
<input type = "text" name = "username" />
<label for = "email">Email: </label>
<input type = "text" name = "email" />
<input type = "submit" value = "Register" />
</form>
<?php }
?>
What I suppose is that, there should be only one pair of PHP tags:
The opening tag <?php at the very begining of the code above
The closing tag ?> at the closing of the code above
Anything else is hard for me to digest, please help me to understand that why the php tags are there in between the code at very weird positions.
Thank you
As per the manual on PHP tags
When PHP parses a file, it looks for opening and closing tags, which
are which tell PHP to start and stop interpreting the
code between them. Parsing in this manner allows PHP to be embedded in
all sorts of different documents, as everything outside of a pair of
opening and closing tags is ignored by the PHP parser.
Which means the code between the php tags will be echo'd and outside one:
<form action = "test.php" method = "post">
<label for = "username">Username: </label>
<input type = "text" name = "username" />
<label for = "email">Email: </label>
<input type = "text" name = "email" />
<input type = "submit" value = "Register" />
</form>
will be treated as a normal HTML. In the case above PHP checks if the form has been POSTed, and if so, it displays a thank you message. If the HTTP request is not POST, it will display a form for the user to post.
In general it's not good practice to mix HTML and PHP and you should avoid this sort of structure.
The easiest way to think about it is to do what the parser does, that is, replace the content outside of the php tags with echo statements within php tags.
The main benefit of doing it like this is that you don't have to escape the HTML in php strings, plus, if well structured, you can view it pretty well in a WYSIWYG editor
Here's an example of code that is equivalent to what you wrote and doesn't switch out of php mode
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<p>Thanks for Registering</p>",
"Username: ", htmlentities ($_POST['username']), "<br />",
"Email: ", htmlentities ($_POST['email']), "<br />";
}
else {
echo "
<form action = \"test.php\" method = \"post\">
<label for = \"username\">Username: </label>
<input type = \"text\" name = \"username\" />
<label for = \"email\">Email: </label>
<input type = \"text\" name = \"email\" />
<input type = \"submit\" value = \"Register\" />
</form>";
}
?>
The PHP manual does a poor job of explaining what actually happens. The PHP parser definitely does not ignore the text outside the block. Instead the PHP parser turns that text into an echo operation. Don't believe me? You can see for yourself in the source code. In zend_language_parser.y, you will find the following line:
| T_INLINE_HTML { zend_do_echo(&$1 TSRMLS_CC); }
When you see <?php if($condition) { ?><div>...</div><?php } ?> it's exactly equivalent to <?php if($condition) { echo '<div>...</div>'; ?>.
The syntax might look odd, but it's actually very useful in some situation. For example, all our web pages typically share the same header and footer. People often handle this by doing an include('header.html') at the beginning of the script and an include('footer.html') at the end. It's not a very flexible approach. Moreover, you end up with two halves of one HTML document that won't render correctly in a browser.
A better way is to slices up the HTML doc with function declaration:
<?php function printHeader($title = "Default Title", $extraJSScrpts = array(), $extraCSSFiles = array()) { ?>
<html>
<head>
<title>
<?php echo $title; ?>
</title>
</head>
<body>
<div style="position: absolute; left: 150px; top: 35px;">
<?php } ?>
<?php function printFooter() { ?>
</div>
</body>
</html>
<?php } ?>
If you ignore the <?php ... ?>, what you have is a regular HTML doc. Looking at the PHP again, you see I have two functions, printHeader() and printFooter(). Instead of doing includes, all my pages now just call these two functions. Each page can pass optional arguments to deal with any special needs (an extra stylesheet, for example). Should I want to implement different themes on my site, it'd be very straight forward. All I have to do is change which file I include at the beginning to bring in different versions of these functions.
Control structures in PHP (e.g. loops, functions, etc.) can be split across pairs of end tags. Effectively, anything not enclosed in PHP tags is just emitted as though it were being echoed (or captured in the current output buffer, if there is one).
Try this
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<p>Thanks for Registering</p>",
"Username: ", htmlentities ($_POST['username']), "<br />",
"Email: ", htmlentities ($_POST['email']), "<br />";
}
else {
echo '
<form action = "test.php" method = "post">
<label for = "username">Username: </label>
<input type = "text" name = "username" />
<label for = "email">Email: </label>
<input type = "text" name = "email" />
<input type = "submit" value = "Register" />
</form>';
}
?>
The opening and closing <?php tags are to tell the interpreter which code is php code (and therefore it should interpret) and which code is something else - HTML, CSS, JS etc.
You'll notice this:
echo "<p>Thanks for Registering</p>";
This is a valid PHP statement and is okay to send to the PHP interpreter.
However, later on in the script the author want to output a load more HTML - he could of course do something like this:
echo '<form action = "test.php" method = "post">
<label for = "username">Username: </label>
<input type = "text" name = "username" />
<label for = "email">Email: </label>
<input type = "text" name = "email" />
<input type = "submit" value = "Register" />
</form>';
But instead chooses to tell the interpreter to just ignore all of this HTML content by closing the PHP section with a ?> and output normal HTML.
He needs to finish the else{} block though, so reopens PHP with <?, adds the closing } and then completes with a closing ?>
Note that PHP also provides an alternative syntax for control structures that improves readability when they're employed to control HTML. The following code creates a table with alternating background color from a list of items:
<table style="width: 100%">
<?php foreach($items as $index => $item): ?>
<?php if(!($index & 0x0001)): // even ?>
<tr style="background-color: #FFFFAA">
<td>
<?php echo $item ?>
</td>
</tr>
<?php else: ?>
<tr style="background-color: #AAFFFF">
<td>
<?php echo $item ?>
</td>
</tr>
<?php endif ?>
<?php endforeach ?>
</table>
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?
I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""
I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.
I tried using
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?
Form code:
echo ' <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
Name: <input name="name" type="text" /><br />
Email: <input name="email" type="text" /><br />
Phone Number: <input name="phone" type="text" /><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"></textarea><br /><br />
<input type="submit" name="submit" value="Submit Email"/>
</form></div>
<div style="clear:both;"></div><br /><br />';
and the vaildator:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!is_numeric($phone)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
} else {
mail( "email#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!
Second: you could(should?) use a hidden field instead of specifing it in the action?
But if you have an error, it refreshes
the page and removes any text that was
inserted before the submit button was
clicked and you have to re-enter all
of the information. Anyway to fix
this?
You could use ajax to fix it(I believe plain old HTML has this side-effect?).
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.
In case you display the form again, you could set the values of the inputs like this:
$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';
Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:
<input type="hidden" name="date" value="'.$date.'"/>
A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.
Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:
If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:
Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.
Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.
A very basic form handling script would look something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] = 'POST') {
# do this only if actually handling a POST
$field1 = $_POST['field1'];
$field2 = $_POSt['field2'];
...etc...
if ($field1 = '...') {
// validate $field1
}
if ($field2 = '...') {
// validate $field2
}
... etc...
if (everything_ok) {
// do whatever you want with the data. insert into database?
redirect('elsewhere.php?status=success')
} else {
// handle error condition(s)
}
} // if the script gets here, then the form has to be displayed
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>
?>
Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.
As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.
first, a few general changes:
change
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
to
<form method="post" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="data" value="'.$date.'" />
the answer to your original question:
set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);
For example: the name field
<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />