Hi folks.
This is my 1st attempt at making a form. Unfortunately I’m struggling to get it working.
The form itself works great, just not the send part.
I’ve tried to follow other forms from other forums as best I can, but I’m missing something.
I’ve messed about with:
Is the code for sending the email in a separate PHP file, and is it named suitably? You quote the action as “contactform” - shouldn’t that be “contactform.php”?
As for actually sending the email, lots of commercial email servers won’t just send emails “from” the address that your user typed into the forum. A proper email server will be configured to only send emails from a domain that it’s supposed to be sending from, otherwise it’s a thing called “Open Relay” which is A Bad Thing. Use an email address that you have configured the server to support, and use the “reply-to” header if you want to make it easier to reply.
I should also mention that the built-in PHP mail() function isn’t considered to be a good way of sending email, you should look at a library such as PHPMailer. That might be particularly needed if you’re using gmail as your mail server, as that will need a secure connection on an alternate port. Is your development system configured correctly to support sending emails?
As mentioned, you form element(s) is wrong. Have just one form element with all the attributes in it.
Aside form that, there are things that could be done differently.
You can’t rely on client side validation alone, it should be backed up by server side validation too.
I would probably do away with the js validation, as basic things like that are now built into browsers if you use the correct attributes in the inputs, such as the required keyword. That will leave you to concentrate on the server side validation.
It looks like you have the PHP form processing in with the HTML from page. That is doable, but if you do it, do it differently. Put the PHP at the beginning of the file, before any HTML and wrap the processing in a condition, to only fire on submission:-
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Form processing here
}
?>
<!DOCTYPE html>
<!-- HTML form page here -->
In this way you don;t even need the action attribute, as it will default to itself.
It also means that if a submission fails the server side validation, you can return the user to the form and list the errors they made.
A successful submission can be redirected to a success page via headers.
The header redirect should be the last line. Also, this code is vulnerable to an Email Header Injection Attack. Never ever trust user supplied data. Do not create variables for nothing.
So the PHP lesson here is “Syntax error, unexpected [something]” means, "Look immediately before [something]. You’ve forgotten something. Semicolon, close parenthesis, close brace… something was expected between the previous statement and this one.