How do I show a message from the php action script of a form?
The form is a user login with these fields.
<div id="register_user_box" class="inline_form" style="position: absolute; top: 20px; right: 10px; <br/>
<span id="user_msg"></span><br/>
<form action="register_user.php" method="post">
<input type="hidden" name="id" id="id" value="add" />
<input type="hidden" name="edit_user" id="edit_user" value="y" />
<table cellspacing="0px"> <tr><td>Username:</td></tr><tr><td>
<input type="text" name="uname" size="30" value="" class="inline_input"/></td> </tr> <tr><td>Email:</td></tr><tr><td>
<input type="text" name="uemail" size="30" value="" class="inline_input"/></td> </tr> <tr><td>Password:</td></tr><tr><td>
<input type="password" name="upass" size="30" class="inline_input"/></td> </tr> <tr><td>Confirm Password:</td></tr><tr> <td>
<input type="password" name="cpass" size="30" class="inline_input"/></td></tr> </table></td></tr> </table> <p>
<input class="button" type="submit" name="register" value="Register" style="float:right;"/></p>
</form>
</div>
The php script register_user.php checks the if the passwords match and shows an error message if they don't. The script checks all the other fields and prints a message if necessary.
<?php
$messages = array( 'usr_cred_req' => 'Must specify username, email, password.',
'usr_name_bad' => 'Bad username selection. Select a different usrename.',
'usr_name_exists' => 'Username selected already exists. Select a different username.',
'usr_email_bad' => 'Bad email selection. Select a different email.',
'usr_email_exists' => 'Email selected already exists. Select a different email.',
'usr_pass_notmached' => 'Passwords do not match. Type passwords again.',
'usr_not_added' => 'User not added.',
'usr_not_updated' => 'User not updated.',
'usr_added' => 'User added.'
);
$username = trim($_REQUEST['uname']);
$email = trim($_REQUEST['uemail']);
$password = md5(trim($_REQUEST['upass']));
$copasswd = md5(trim($_REQUEST['cpass']));
if ( $password != $copasswd ) { echo '<script> $("#usr_msg").html("'.$messages['usr_pass_notmached'].'"); </script>'; return;}
?>
The error message isn't shown and the browser leaves the page. I'd like the browser to stay on the page and add the error message to the span user_msg.
If you don't want the browser to leave the page when the form is submitted, then you will have to use AJAX to submit the form in the background to communicate with the server and then update the container with the error message (or something different on success).
Alternatively, have the PHP form post to itself, check the error messages before you output your HTML and if there was an error, insert the error message in the form markup in the desired location and re-populate the form with all of the values that were originally submitted.
http://jquery.malsup.com/form/
Here's a good jQuery AJAX form plugin. This will prevent page refresh upon submission.
Hope this helps.
Why are you echoing a JS script to display the error message? The way you have it written out it won't display a little popup, you just having it filling the span. A better way to do it is something like this:
if ( $password != $copasswd ) {
$display_msg = $messages['usr_pass_notmached']
}
Then in your HTML do this:
<span><?php echo $display_msg?></span>
If the variable is empty then nothing is displayed. If you do this for all the fields, then you can ensure all the information from the form is returned on error, whether the actual field IS the error or not, preventing the user from having to retype all the information again. Have the form do a $_SERVER['PHP_SELF'] to ensure it reloads the same page
I would build the PHP functionality (which can't be turned off by the user) and ensure your form works properly 100% (or close to that) of the time. Then, once you have that script working, add your JS funcionality to compliment your existing code.
What I do in mine, is I build an extra array, in this case $display_msg and I run a check of all the input fields. If a field fails, I add that to the array, $display_msg['password'] then I move on to the next field. Once all the fields have been check, I check if the $display_msg variable is empty or not. If it's not empty, then I have it fill all the span next to the input boxes with red letters explaining the error. This will print out ALL of the errors at the same time, instead of one at a time while it works it's way down the form. Next to each input I have a span with the given variable name, in this instance <?php echo $display_msg['password']?>, then next to the username, <?php echo $display_msg['username']?> and so on. Hope this is clear enough and helps.
Related
I have multiple inquiry forms all of which call the same file used for email forwarding, so it's titled emailForwarding.php. I apparently managed to separate the forms using jQuery on the front end, but the script in emailForwarding.php is processed the same number of times as the number of the inquiry forms. I just want the php script to work for the form I submit.
I tried isolating the effect of the script using .eq() and .index() and passing an argument named $arg to only trigger form submission event for the div.vendor-wrapper containing the selected form.
single.php:
echo
'<div class="vendor-wrapper"><form method="post" action="" name="form" class="commentForm">
<textarea name="comment" placeholder="Please enter your message in the space of 300 characters and hit the Confirm button." value="" class="message" maxlength="300"></textarea>
<input name="confirm" type="button" value="Confirm">
<input class="send" name="send'.$i++.'" type="submit" value="Send">
<input type="hidden" name="position" val="">
</form></div>;
<script>
$('.confirm').click(function(){
$('.vendor-wrapper').find('.position').val('');
var index = $(this).parents('.vendor-wrapper').index()-1;
if($('.vendor-wrapper').eq(index).find('.message').val()){
$('.vendor-wrapper').eq(index).find('.confScreen').show();
$('.vendor-wrapper').eq(index).find('.position').val(index);
}
});
</script>
emailForwarding.php:
if(isset($_POST['position'])):
$arg = 'send';
$arg .= $_POST['position'];
echo "<script>console.log('PHP: ".$arg."');</script>";
if(isset($_POST[$arg])):
if(isset($_POST['comment'])):
$EmailCustomer = $_POST['email'] = $current_user->user_email;
//The rest of the script for email processing omitted.
The form is submitted the same number of times as the number of the forms on the page.
Inserting include() before tag of single.php disabled duplicate submission.
Could you provide more code? Because I was trying to reproduce the problem but could not with the provided code. As, what $_POST['position'] stands for is not clear from code.
Is the echo statement user any loop. Can you try by giving a different name to FORM?
<form method="post" action="" name="form-$i" class="commentForm">
I am looking for some help about how to make input form handling in PHP.
What I need is when a user writes data into a text form (table1), and moves to another text form (like pressing TAB, or selecting with mouse), then it should start and MySQL query to see if such data written at table1 already existing in the matching MySQL table.
My goal is like to do it without pressing submit button. Something like when google checks if an username you want to register already exists.
I am thinking about something like this:
$duplicate_data_test ="";
if (focus has moved to another form field - how to check ?) {
$query = "SELECT table1 FROM testdatabase WHERE table1 = "' . (table1 from the form below - how to get data from the this form field without POST?) .'";
$result = mysqli_query($con,$query);
if(mysqli_num_rows($result)>0) {
$duplicate_data_test = "This data is already found in the database. Choose something else";
}
}
echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">';
echo '<input type="text" maxlength="30" name="table1">';
echo '<span class="duplicaterror">'. $duplicate_data_test.' </span>';
echo '<input type="text" maxlength="30" name="table2">';
echo '<input type="submit" value="OK">';
echo '</form>';
Thank you very much for your help!
You cannot do your "interface" check with php.
Your "focus has moved to another form field" has to be done with javascript.
First, Build your form with html like this
<form name="testForm" action="postForm.php" method="POST" id="myForm">
<label>INPUT 1 : </label>
<input type="text" id="in1" value="" name="input1" />
<label>INPUT 2 : </label>
<input type="text" id="in2" value="" name="input2" />
<div style="color:red;font-weight:bold;" id="error"></div>
<button id="submitButton">SUBMIT</button>
</form>
Then make your checks when user clicks on submit button with javascript/jquery & ajax (prevent event form posting) like this :
$(document).on('click','#submitButton',function(event){
event.preventDefault();
if($.trim($('#in1').val()) == ''){
//input 1 is empty
$("#error").html('INPUT ONE IS EMPTY');
}//....continue checks
Finally, if your checks are good, then post your form
$("#myForm").submit();
and if your checks are not good then display user a message!
$("#error").html("MESSAGE!");
I made you a little example on how to do it (it's not the best way to do it but it's just an example) on jsfiddle, check this link : http://jsfiddle.net/9ayo89jt/2/
hope it helps!
checking if something exists will need an AJAX call
put the query that checks the database in a separate php file and call it with AJAX
to submit once all input fields are filled, you will need to use javascript .. check if field 1,2,3,..etc. are not empty .. formName.submit()
this is a bad approach in my opinion
I have created a form where a user can add a review. Perhaps this is very obvious but how can I avoid a user inserting a url in the text area. Is there a way to check this?
I have put in a captcha to check for humans.
<form action="" method="POST" name="form">
some other input fields
<span id="sprytextarea1">
<textarea name="Comments" cols="50" rows="3" ></textarea>
<span class="textareaRequiredMsg">A value is required.</span></span></p>
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" /><input type="text" name="captcha_code" size="10" maxlength="6" />
[ Different Image ]
<input name="Submit" type="submit" value="Submit your form ">
<input type="hidden" name="MM_insert" value="form">
</form>
Any suggestions welcome.
Just put the if condition,before insert db.
if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$_POST['comment'])){
echo 'error please remove URLs';
}else
{....
Using PHP you can try two things using preg_match() and strip_tags() or a combination of them both. below will clean the textarea, escape it as well for database.
Once the form is submitted try this.
$post = array();
foreach($_POST as $k => $v){
// strip all HTML and escape values for database
$post[$k] = strip_tags(mysql_real_escape_string($v));
}
// check of we have URL in text area
if(preg_match('/www\.|http:|https:/'i,$post['Comments']){
// prevent form from saving code goes here
echo 'error please remove URLs';
}else{
// let form be saved
}
Simply, there is no any automatic way to check a URL in input text. You just have to use a human check for the user input.
For example: suppose that you tried to apply regex check for a URL and I want to trick it, I may able to write infinite string that shown as a URL:
http: example .com
h ttp:// ecxampleDOTcom
ht-tp: / / ecample. Com
etc
So any commenting system to achieve the ultimate spam protection, it applies moderator review in which a human being check the content.
So I've always heard and read that you need to sanitize any user input if it's to be output back to html. What I'm wondering is, do I need to sanitize any input that is output if there was an error?
For example, in my form error handling, I have it so the page gets re-displayed with the error message showing and telling the user what went wrong but also outputting their input as the form's value so they don't have to re-type it and they can see where they went wrong. My question is do I need to use htmlspecialchars() to sanitize the user's input when its output as the value of the form field?
Here is what one of my input fields looks like right now.
<label for="email">E-mail Address: <?php if($btnPressed) { checkInput($_POST['email'], true, true); } // Check the validity of the input ?></label>
<input type="text" name="email" id="email" value="<?php if($btnPressed) { echo $_POST['email']; } // Output the user's input if an error occurred ?>" maxlength="50" />
Here is what I think I should be doing.
<label for="email">E-mail Address: <?php if($btnPressed) { checkInput($_POST['email'], true, true); } // Check the validity of the input ?></label>
<input type="text" name="email" id="email" value="<?php if($btnPressed) { echo htmlspecialchars($_POST['email']); } // Output the user's input if an error occurred ?>" maxlength="50" />
Any help is greatly appreciated.
Yes, you need to run the data through htmlspecialchars.
Otherwise you have two major problems.
A third party could link (or submit a hidden form with JS (since you are using $_POST they would have to use this approach)) to your site sending whatever data they liked (including "><script...) as the user who visited their attack site.
If the user enters a " in their data (either because it is a typo or because their data really does include a " character), it will break when you display it back to them.
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'] : ''; ?>" />