Since PHP is a server side language it is very easy to send emails from PHP, for e.g. on a contact form.
Emails are sent using mail function, and passing the emailTo, subject, body, and header options as parameters. Each line of the body can only be 70 characters long and must be separated by CRLF ( \r\n). There is another PHP function called wordwrap that can be used to format the body of the email if the body is greater then 70 characters long. For example
wordwrap($body, 70, "\r\n");
In the headers options parameter you must specify whom the email is being sent by. In other words, From: parameter is mandatory and must be passed as additional header option. Some other parameters you can pass in additional header are Reply-To:, Cc:, Bcc:. Each header options should be separated by CRLF (\r\n).
The mail function returns a 1 or blank based on whether the email was successfully sent or not. Therefore, the mail function can be treated as a Boolean and checked for whether the email was successfully sent.
As users can turn their JavaScript off and/or figure out other ways to bypass validations carried out in JavaScript, all validations must be carried out at BOTH JavaScript level and PHP level.
In the example below we have made the first name and email fields manadatory using HTML. However, we need to implement the same logic at PHP level. Furthermore, we are going to validate in both JavaScript and PHP that a reason for contacting us is provided.
JavaScript can be used to validate a form and prevent it from submitting if errors are encountered. In order to do that we need to trigger the Javascript on the form element when submitting the form using the following syntax and carry out the validations inside this JavaScript:
$("form").submit(function(e){
...
...
...
})
There are two ways to interact with the browser if the validations fail, and preventing the browser from actually submitting the form.
e.preventDefault();
$("form").unbind("submit").submit();
return false;
return true;
As we know, PHP can NOT contain HTML but PHP can be placed anywhere inside HTML. As such you can either place your PHP all on top and display errors using echo (another set of PHP code) where you want to display them, or at the position where you want to display (echo) the content (as/when applicable)