Php-mysql Course

To send e-mails directly from a PHP script, you can use the mail() function.

  - Syntax:
mail(to, subject, body, headers);
- to - a string with the address(es) of the receiver(s). Can be in either of the following formats:
                "name@domain.com"       or       "Some Name <name@domain.com>"
To send to more than one address, use a comma-separated string like this:
                "user@domain.com, another@domain.com, Some Name <name@domain.com>"
- subject - the email's subject line.
- body - is where you put the contents of the email. It must be presented as a single string. New lines must use both a carriage return (\r) and newline character (\n), "\r\n", and the lines should not be larger than 70 characters.
To wrap text to 70 characters, you can use wordwrap() function. It adds a new line every X characters:
                $body = wordwrap($body, 70);
- headers - optional, it's a string used to add extra headers (From, Reply-To, Cc, Bcc, encoding). Each new header, except the final one, should be separated with a "\r\n".
It is recommended that you always include a From value in the "headers" parameter.

mail() returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
• This function doesn't send the email itself. It just transfers email data to a mail server running on the computer, and actually that server sends the email. The computer on which PHP is running must have a working mail server in order for this function to work. But PHP has no way of knowing if the email is delivered to the destination.

Simple form contact script

Usually, data for the mail() function arguments, especially for "body", is received from an HTML form.
  Here is an example of a simple php mail script for a contact form. Sends a text mesage from a form to a specified e-mail address.
<?php
$to = 'your_email@domain.com';          // receiver address

// Check for form submission
if (isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['message'])) {
  // get form data
  $from = 'From: '. $_POST['email'];
  $subject = $_POST['subject'];
  $body = $_POST['message'];
  $body = wordwrap($body, 70);           // makes the body no longer than 70 characters long

  // send the email
  if (mail($to, $subject, $body, $from)) echo 'Thank you for using our mail form';
  else echo 'Error, the message can not be sent';
}
?>

<form action="" method="post">
 E-mail: <input type="text" name="email" /><br />
 Subject: <input type="text" name="subject" /><br />
 Message:<br />
 <textarea name="message" rows="8" cols="30"></textarea><br />
 <input type="submit" value="Send" />
</form>
- First, this script checks if the "email", "subject" and "message" fields are filled out. Gets data from these fields and use the mail() function to send the email, and returns a message for success or error.
- $to variable contains the address where the e-mail will be sent.

Validate email address, filter form data and set headers

The script above is the simplest way to send e-mail, but it is not secure. For example, it should check if the user has completed all fields, also, to validate email address, and other filters.
By default, mail() uses Latin1 (ISO-8859-1) encoding, which doesn't support accented characters. But the Unicode (UTF-8) supports most written languages, including the accents commonly used in European languages.
To ensure that email messages display correctly accents and less usual characters, use the Content-Typeg header to set the encoding to UTF-8 like this:
                $headers = "Content-Type: text/plain; charset=utf-8\r\n";
Another usefull header is Reply-To, this set an address for Reply.
                $headers = "Reply-To: an_email@domain.com";

• Here is a more complete and secure contact form script. It removes tags from form data, checks to be a valid e-mail address, and a minimum number of characters for "subject" and "message". Also, it adds the "From", "Conten-Type" (utf-8), and "Reply-To" headers in the email (for more explanations, see the comments in the script).
<?php
$to = 'your_email@domain.com';          // receiver address

$erors = array();                      // set an empty array that will contains the errors
$regexp_mail = '/^([a-zA-Z0-9]+[a-zA-Z0-9._%-]*@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4})$/';         // an e-mail address pattern

// Check for form submission
if (isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['message'])) {
  // remove tags and whitespace from the beginning and end of form data
  $_POST = array_map("strip_tags", $_POST);
  $_POST = array_map("trim", $_POST);

  // chech if all form fields are filled in correctly
  // (email address and the minimum number of characters in "subject" and "message")
  if (!preg_match($regexp_mail, $_POST['email'])) $erors[] = 'Invalid e-mail address';
  if (strlen($_POST['subject'])<3) $erors[] = 'Subject must contain minimum 3 characters';
  if (strlen($_POST['message'])<5) $erors[] = 'Subject must contain minimum 5 characters';

  // if no errors ($error array empty)
  if(count($erors)<1) {
    // get form data
    $from = 'From: '. $_POST['email'];
    $subject = $_POST['subject'];
    $body = $_POST['message'];
    $body = wordwrap($body, 70);           // makes the body no longer than 70 characters long

    // set headers (From, Encoding utf-8 and Reply-to)
    $headers = $from. "\r\n";
    $headers .= 'Content-Type: text/plain; charset=utf-8';
    $headers .= "Reply-To: ". $_POST['email'];

    // send the email
    if (mail($to, $subject, $body, $headers)) echo 'Thank you for using our mail form';
    else echo 'Error, the message can not be sent';
  }
  else {
    // else, if errors, it adds them in string format and print it
    echo implode('<br />', $erors);
  }
}
?>

<form action="" method="post">
 E-mail: <input type="text" name="email" /><br />
 Subject: <input type="text" name="subject" /><br />
 Message:<br />
 <textarea name="message" rows="8" cols="30"></textarea><br />
 <input type="submit" value="Send" />
</form>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
PHP Sending E-mails

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141749)
  2. Node.js Move and Copy file (28420)
  3. MouseEvent - Events for Mouse (2909)
  4. PHPMailer (2311)
  5. Uploading images to server with Ajax (6095)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (473)
  2. CSS cursor property - Custom Cursors (79)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)