I am a PHP newb so please bear with me for this rather simplistic question.
I have a PHP form setup like so >>
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$comments = $_POST['comments'];
if($comments)
$error = "There was an error, please give us a call at ### ###-####.";
else{
if($name=="Name" || $email=="Email" || $message=="Message"){
$error = "All fields are required, please fill them out and try again.";
}else
$header = "From: $name <$email>";
$message = "Name: $name\n\nEmail: $email\n\nMessage: $message";
if(mail("email#domain.com", 'Form Submission', $message, $header))
$success = "Thanks for sending us your message, we'll get back to you shortly.";
else
$error = "There was an error, please give us a call at ### ###-####.";
}
if($error)
echo '<div class="msg error">'.$error.'</div>';
elseif($success)
echo '<div class="msg success">'.$success.'</div>';
}
?>
The basic idea is that the form has descriptive text pre-filled in each field but when you click on them they are cleared via Javascript. I want to prevent people from pressing send on the form without filling it out, hence the "if($name=="Name" || $email=="Email" || $message=="Message"){" bit. However while that message is working the form is still submitting. Why is this. Also please note that the "comments" field is in fact a honeypot. Thanks!
Because php is server-side. You need to look into javascript validation for what you want. To validate with php you HAVE to submit the form.
One tutorial but I recommend Jquery validation
"I want to prevent people from pressing send on the form without filling it out, hence the "if($name=="Name" || $email=="Email" || $message=="Message"){"
All you need to do is disable the submit button client side until the proper validation is met, then also validate server side. As #Iznogood said, that's why your gettin your error
Like lznogood said, PHP validates the form on the server, so you need to send the information to the server before PHP can process it.
If you want the form to be checked on the user side before sending it to the server you should use JavaScript to do that (jQuery is a great tool to use), and after checking it on the user side you can decide whether to send the form to the server or not.
Though this isn't an answer to your question, you might be interest in the new html5 feature placeholder. Read about it here. You can check to see which browsers it works in here (stupid internet explorer!). 5 years ago, I would put those "hints" as the value, which was a pain to validate. placeholder makes it sooooooo much easier. Your tag would look like:
<input type="text" name="email" placeholder="Enter Your Email Here" value="">
Note that value is empty. You can omit the value attribute, I left it in to show it's not needed here.
As far as an answer to your original question, everybody else is correct, javascript is the way to go.
Related
So I've set everything up so my contact form submits and I get an email in my inbox. They problem is that every time I refresh the page, or come back to the page, I get ANOTHER copy of the same email in my inbox.
How do I ensure that I'll only get the email once, and also that a user won't accidentally keep sending me messages after they've written and successfully sent the one they want.
I'd also love to know how to make sure the success message isn't just showing ALL the time.
If it's helpful, here are my PHP and jQuery codes:
PHP: https://www.tehplayground.com/Z7mCYfoSz09WEEVj
jQuery: https://www.tehplayground.com/cN9U4HpE0J5czkyS
Thanks for the help!
You can redirect the user to another page, and it will "reset" the form requests:
header("Location: index.php");
document.onload = function () {document.getElementById("form").reset();}
$("#refresh").click(function(){
$("#myModal").find('input:text, input:password, select, textarea').val('') ;
$("#myModal").find('input:radio, input:checkbox').prop('checked', false);
$("#weak").html('') ;
$("#moderate").html('') ;
$("#strong").html('') ;
$("#show_error").html('') ;
$("#show_success").html('') ;
$("#new_password").attr("disabled", "disabled") ;
$("#confirm_password").attr("disabled", "disabled") ;
$("#reset_pass").attr("disabled", "disabled") ;
});
Use the above and it will reset a form .
this is a common problem if you are submitting forms using post. if a user accidentally refreshes a page after submission. it can cause duplicate form submission. read more more about post redirect get pattern here for clarity on what am talking about.so in a nutshell the basic procedure to do here is to redirect the page after submission either to a different page or the same page. like so
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$error .= "<p>• Don't forget to write your name!</p>";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$error .= "<p>• An email address is required. </p>";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["message"])) {
$error .= "<p>• Don't forget to write your message!</p>";
} else {
$message = test_input($_POST["message"]);
}
if ($_POST["email"] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
$error .= "<p>• Please input a valid email! </p>";
}
header('Location: index.php');// redirect so that the pages is recieved through get method
exit()
//note that if you are redirecting to the same page you wont be able to use variable, you can instead use session knowing that the page refreshess
}
?>
I think the best way to handle this issue is to create a unique identifier for each submission.
foreach($_POST as $data){
$s = md5($s . $data);
}
Now $s holds a value of 32 chars in length that is pretty much unique to any input.
You have multiple options:
You can insert this value into a table (2 columns) where 1 is this value and the other the date of insert and delete the record after 1 day.
Use sessions and just append this id to the array (and reset it from time to time)
Any other method of storage, just keep in mind that storing it on the client is not the best way to do it.
This pretty much eliminates double submissions. However this is more or less an example code to give you a general idea. Perhaps not all fields should be used, and maybe you want to add a date() to it as well.
All depends on your needs.
You can use other techniques to do the same thing, this however is something that should be handled by the server and not the client. So using Javascript is an escape goat, just not a permanent solution.
Thanks all. Got it sorted!
I ended up splitting up the PHP into a “process.php” and “form.php”, which has helped with stopping duplicates, and then used an AJAX to effectky refresh and rest the form without refreshing the whole page.
Everything works wonderfully now - although hard to say whether its as secure as it can be!
The best way is to use JQuery to submit the form and email and reset it without refreshing the page . Don't use "form" tag , instead use "div" tag with the same class , otherwise the page will get refreshed and the click event will be called .
I am trying to make a contact form in Blogger. The default contact form widget exists and works like a charm, but it only provides 3 fields. Name, email and message.
I needed more fields added.
Adding more fields to the widget is impossible, since there are specific tags that the widget accepts, that correspond to the three fields "data:contactFormNameMsg" for the name, "data:contactFormEmailMsg" for the email and "data:contactFormMessageMsg" for the message.
So, the solution was to create my own form. I did not want to use the action=mailto because I don't want windows jumping up, Outlook or Mail starting and tabs getting opened. So, I had to use .php to control the sending of the form.
I wrote my .php code.
So, since Blogger does not provide the option to host your .php file, I had to look elsewhere for hosting.
I googled it. And I was directed to the use of Google Drive as the best option to host a .php file for Blogger. So I tried it. I tried the steps described here (and everywhere else on the web), but as this page says (and it must be a new addition, because all other unofficial -and most probably outdated-sites claim to be able to host their .php files on Google Drive)
"Google Drive does not support web resources that make use of server-side scripting languages like PHP."
I tried Dropbox. But, as answered here, "Dropbox doesn't support server-side execution of your PHP scripts" either. All these must be new, because every blogger suggests Dropbox and Google Drive as the best options for hosting .php files.
Then, I tried 000webhost. It worked. My .php script ran and I received the form in my email, BUT (big big BUT) on clicking the button that triggered the action and the .php, the user is also redirected to the first page of 000webhost.
I tried hosting it on another free web hosting service, but the same thing happened. The moment the user clicked the "Send" button on my form, they were redirected to the first page of the free webhosting service.
I thought of adding the php code inline html (?php) ---code--- (/php) but I did not know how to refer to it.
So, I have two questions:
How could I refer to an inline part of php code, in my html code? Remember, we are on Blogger, that little is allowed. I want to refer to the php code from the "form action=" part.
Why does the "Send" button redirects the user to the front page of the free webhosting service? Is it the "Free webhosting service"'s way of advertising itself? I mean, is it implemented in the service? Is there something wrong with my code?
My php code is this:
<?php
$errors = '';
$myemail = 'mymail#mymail.com';
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
}
?>
And the HTML part where I call the .php file is this:
<form action='http://myusername.mywebhost.com/contact-form-handler.php' method='POST' name='contact-form'>
So, that's all. If anybody has encountered a similar problem or has needed to use a .php form handler in Blogger RECENTLY, you will be of great help.
Thank you very very much in advance!
What you can do is send the form via AJAX to whatever host you want - the user won't be redirected there. Here is some example code, you can customize it further
$("#theform").submit(function(e) {
e.preventDefault();
$.post('http://example.com/contact.php', $('#theform').serialize());
}
serialize is used to collect the data from inputs and POST it to the given url.
AJAX Serialize Documentation
I have a form and this bit of code to send it:
if($feedback != $errorMessage){
$emailTo = 'me#mywebsite.com';
$emailFrom = 'submissions#mywebsite.com';
$subject = 'Submission';
$body = filter_var("$contactName made a submission.
Contact Information:
Contact Name:\t$contactName
blah:\t$blah
Address:\t$address
Telephone:\t$telephone
Mobile:\t$mobile
E-mail Address:\t$userEmail
Website:\t$website
Vacancy Information:
field1:\t$field1
field2 Benefits:\t$field2
field3:\t$field3
field4:\t$field4
field5:\t$field5
field6:\t$field6
field7:\t$field7
field8:\t$field8
field9:\t$field9", FILTER_SANITIZE_STRING);
mail($emailTo, $subject, $body, "From: ".$emailFrom);
}
From what I understand from reading other threads this should be enough. I tried emailing just a single dot on a line in one of the textareas and it did turn it into 2 dots. Just running one function on it seems far too simple though.
Is this secure enough? I've read things online that seem inconsistent like that I don't even have to sanitize the body. The email body is the only thing that takes user input here.
Thanks.
Not entirely sure what you mean by secure here. Your script is just sending an email. The content of the fields will be what the user filled in. It could be link to virus, crap, spam or real content. Not easy to say, really. Not much to do with it either.
Sanitizing is much more important once databases are in use.
I am an amateur at php and I made this simply submit form (see bellow). Now, when I click submit, it acts as if it went through it displays that the messages was received but I don't get any msg in my actual e-mail. The 3 form inputs names are: name, email, msg. Am I doing something wrong?
<?php
$message="$msg";
$mail_from="$email";
$header="from: $name <$mail_from>";
$to ='anomanomanom#gmail.com';
$send_contact=mail($to,$message,$header);
if($send_contact){
echo "I've received your message and I will get back to you shortly! You will be redirected in less than 5 seconds!";
header("refresh:5;url=http://google.com");
}
else {
echo "ERROR";
}
?>
You need to access the submitted data either via $_GET or, more likely, via $_POST, e.g., $_POST['msg'].
Whatever you are using to learn PHP is heavily outdated, as it still depends on something called autoglobals. These were deprecated almost 5 years ago. You can find more info here.
I've got a submission page in php with an html form that points back to the same page. I'd like to be able to check if the required fields in the form aren't filled so I can inform the user. I'd like to know how to do that with php and javascript each. However, I imagine this is a common issue so any other answers are welcome.
Do the check in posting part of your php
if(isset($_POST['save']))
{
$fields=array();
$fields['Nimi'] = $_POST['name'];
$fields['Kool'] = $_POST['school'];
$fields['Aadress'] = $_POST['address'];
$fields['Telefon'] = $_POST['phone'];
$fields['Email'] = $_POST['email'];
foreach ($fields as $key => $val)
{ if(trim($val)=='')
{ $errmsg=$key." is not filled!";
break;
}
}
}
if($errmsg == '')
{ //do your saving here
exit();
}
if(!isset($_POST['save']) || $errmsg != '')
{ //show your form here
// and make it to return to the same page on submit
//<input name="save" type="submit" value="Save" onclick="return true;">
}
For extra credit, once you know how to do it in PHP and JavaScript from Riho and annakata's answers, then build a way of defining a field constraint in a single form that can both be rendered as JavaScript for client-side validation and run on the server.
Since you need both (client-side for user convenience, server-side because we're really very much past trusting the client at this point), it seems like quite a decent idea to support both from a single infrastructure.
As far as JS goes you have to check before you submit. Generally this involves binding some validation function to the onsubmit event trigger of the form, and that validation function will consist of some tests for each field you're interested.
Most JS libraries have validation implementations that will do most of the work for you, which sounds like it might be a good idea for you. Googling "client side validation" will yield infinite results, but this (I'm library agnostic, read and choose for yourself) should get you started*:
http://blog.jquery.com/2007/07/04/about-client-side-form-validation-and-frameworks/
http://tetlaw.id.au/view/blog/really-easy-field-validation-with-prototype/
http://dojotoolkit.org/book/dojo-book-0-4/part-4-more-widgets/forms/validation
*this is on the teaching you to fish plan
The LiveValidation library would help you out a lot:
http://www.livevalidation.com/