Archive

Posts Tagged ‘Email’

PHP – Email Advanced

February 8th, 2009 No comments

For a simple introduction to the mail() function see the PHP_Advanced article. This article describes some of the more advanced features that can be achieved through the mail function.

Assign Names to email addresses

When receiving an email you will notice that the To field often contains a name rather than the email address it was send to.

<HTML>
<BODY>
<?PHP
mail(‘bob@email.com’, ‘Test email’,
‘This is a test email’,
“To: Bob Jones <bob@email.com>\n” .
“From: Jane Jones <jane@email.com>\n” .
“cc: Another Person <another@email.com>\n” .
“Bcc: Yet Another <more@email.com\n>”);
?>
</BODY>
</HTML>

HTML Emails

The next stage is sending HTML email messages, this allows for standard HTML tags to be used when composing the message content. When sending a message in HTML it must be declared that is it HTML in the header of the email, this is done through both the Content-type: and MIME-Version headers’:

<HTML>
<BODY>
<?PHP
mail(‘bob@email.com’, ‘Test email’,
‘<html><body><b>Hello! World</b> \n <i>this is a test email</i></body></html>’,
“MIME-Version: 1.0\n” .
“Content-type: text/html; charset=iso-8859-1″);
?>
</BODY>
</HTML>

The MIME-Version (Mulitpurpose Internet Mail Extensions) header indicates that the email follows the internet standards, following that the Content-type header can declare the format being used; text/html; followed by the character set being used charset=iso-8859-1

Mixed Format Emails

Although the majority of email clients support HTML email messages, there are some that don’t. The mixed format ensures that the email clients that do support it see the HTML formatted message, where as the ones that don’t see a plain text version.

The technique involved is to actually send two versions of the message and rely on the email client to read and understand Content-Type: multipart/alternative; header which will make the client only display the supported version.

*** PHP code not fully completed yet ***

Emailing Attachments

Emailing file Attachments work in the same way that mixed format email messages do. The header Content-Type: multipart/mixed; is used and the message split into two parts; one the message and the other the file attachment(s).

This is more complicated than previous email examples, all the steps required are explained below. The examples assume that the email details including the file to be emailed have been submitted to the PHP page from another page.

$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];

Attributes of the file attachment

The first stage is to extract the required attributed from the file that has been passed. The file details in PHP are stored in an array named $_FILES which are extracted to variables.

// example: /tmp/phpfile12345 – tmp file name and loc where uploaded
$file_loc = $_FILES['fileatt']['tmp_name'];
// example: text/text – will vary depending on file type
$file_type = $_FILES['fileatt']['type'];
// example: mywork.txt – always the name of the file
$file_name = $_FILES['fileatt']['name'];

Extract data from file attachment

The data within the file is required to be placed into a variable then used Base64 encoding to convert (possible) binary data into text. The is_uploaded_file function is used to ensure that the file was in fact uploaded by an http get command, this helps to ensure no malicious activity.

if (is_uploaded_file($file_loc)) {
// Read the file in ‘rb’ read binary
$file = fopen($file_loc,’rb’);
$filedata = fread( $file (comma) filesize ($file_loc));
// Base64 encode the file data
$filedata = chunk_split(base64_encode($filedata));

The data is now in a format that is ready to be emailed, the next stage is producing the standard mail parameters.

Producing mail function

The basic mail parameters are set in the same manor, the diffrences come in the header and message parameters

The header parameter contains the MIME version, the Content-Type: multipart/mixed; declares that there will be an attachment, finally the boundary string (containing random text) is used as a marker to split the message into the two sections.

“\nMIME-Version: 1.0\n” .
“Content-Type: multipart/mixed;\n” .
” boundary=\”==Multipart_Boundary_x45985365x\”";

The message section starts with a declaration which MIME compatible email clients will not show, next is the Multipart Boundary string denoting the beginning of the first section. Following this the usual header information is declared, following by the desired message text.

“This is a multi-part message in MIME format. you should not see this\n\n” .
“–==Multipart_Boundary_x45985365x\n” .
“Content-Type: text/plain; charset=\”iso-8859-1\”\n” .
“Content-Transfer-Encoding: 7bit\n\n” .
“This is the message contents, there should be a file attached to this message”

After the text of the message, the next part is the message attachment which follows the same format as above.

“–==Multipart_Boundary_x45985365x\n” .
“Content-Type: {$file_type};\n” .
” name=\”{$file_} \n” .
“Content-Disposition: attachment;\n” .
” filename=\”{$file_name}\”\n” .
“Content-Transfer-Encoding: base64\n\n” .
$filedata . “\n\n” .
“–==Multipart_Boundary_x45985365x–\n”;

Then message should always have the message boundary string followed by to signify the end.

To see the fully working source code, please see here

For more information on different MIME types see here
Many thanks to the tutorials where this information came from, W3Schools & PHP & sitepoint

Categories: How to Tags: , ,

PHP – Advanced

February 8th, 2009 No comments

This article will guide you through some of the more complex features of PHP. a more basic introduction article is also available.

User Data

When browsing the internet you will come across some websites that store information about you or your visits to the site. There are two main methods of storing this data, these are through Cookies and Sessions.

Cookies

Cookies are the older of the two methods, it consists of a client side file that the browser writes to. With PHP you can create new cookies and also retrieve existing values, examples of both are below

To create new cookies the setcookie function is used, the main parameters are:

  • Name – The Name of the cookie
  • Value – Data that the cookie is to store
  • Expire – Time & Date when the cookie will expire

When creating cookies in PHP you must call the setcookie function before any HTML tags are used in the page, an example is shown below:

<?PHP
setcookie(“yeltuor”, “MyValue”, time()+86400);
?>
<HTML>
<BODY>
The cookie named yeltuor has been ’set’
It will expire 24 Hours (86400 seconds) from now.
</BODY>
</HTML>

With the cookie now created, the next stage is to read back the values stored in it. The values in the cookie can be called in the same way variables are:

<HTML>
<BODY>
<?PHP
//Check whether the cookie named yeltuor is set
if (isset($_COOKIE["yeltuor"]))
echo “Welcome back ” . $_COOKIE["yeltuor"] . “<br>”;
else
echo “Welcome newbe <br>”;
?>
</BODY>
</HTML>

Sessions

A Sessions is a server side file that is written to, again PHP support the creation and retrieval of session data. When a session is created a unique session ID is used to reference it, this is all taken care within the underlying PHP code.

The advantage of using sessions is that the user can’t view or edit the data within them; unlike the client side cookie’s. Before using sessions on a PHP page, the session_start(); function must be called, after this a session can be created, however like the cookie functions all session calls must be done before any HTML code on the page:

Below is an example of setting up a server side session:

<?PHP
//start session
session_start();
//if session variable total doesn’t exist create one
if(!isset($_SESSION['total']))
$_SESSION['total'] = ‘0′;
?>
<HTML>
<BODY>
The session variable total set to 0, unless it already existed.
</BODY>
</HTML>

To reference existing session variables and dispose of variables that are no longer required, the following code can be used:

<?PHP
//start session
session_start();
?>
<HTML>
<BODY>
<?PHP
echo “The total is ” . $_SESSION['total'];
//Finished with session variable, disposing of it
unset($_SESSION['total']);
?>
</BODY>
</HTML>

For the security minded individuals, a list of more advanced session functions that are available can be seen here.

Files

PHP supports various file related operations, some examples are below:

Opening a file is done with the fopen( ); function, the first parameter is the filename, the second is the mode to open the file in:

Mode Description
r Read Only, pointer at the beginning of the file
r+ Read and Write, pointer at the beginning of the file
w Write Only, existing file will be truncated or new file will be created.
w+ Write and Read, existing file will be truncated or new file will be created.
a Write Only, Places pointer at end of the file or new file will be created.
a+ Write and Read, Places pointer at end of the file or new file will be created.
x Write Only, If the file already exists the fopen( ) function will return FALSE, or a new file will be created.
x Write and Read, If the file already exists the fopen( ) function will return FALSE, or a new file will be created.

Some examples of using the fopen( ) function are below:

<HTML>
<BODY>
<?PHP
//Open file hello.txt, in the case of an error exit
$f=fopen(“hello.txt”,”r”) or exit(“Cant open file”);
//if reached the end of the file
if (feof($f))
echo “End of file”;
//Loop through file 1 char at a time, echo value
while (!feof($f))
{
$x=fgetc($f);
echo $x;
}
//Close file handle when finished
fclose($f) ;
?>
</BODY>
</HTML>

This function below accepts a parameter of a filename and location and returns the file data as a variable called contents:

function fileContents($filename){
// get contents of a file into a string
$f = fopen($filename, “r”);
$contents = fread($f, filesize($filename)) ;
fclose ($f);
return $contents;
}

Functions

Functions are used in the same way that procedures are used in other programming languages, they are used to aid with the re-use of code. examples of using functions can be seen below:

<HTML>
<BODY>
<?PHP
function echoHelloWorld($name)
{
echo “Hello World my name is ” . $name;
}
//Using the created function
echoHelloworld(“Borris”)
?>
</BODY>
</HTML>

Functions can also return values as an output by the return command from within the function.

<HTML>
<BODY>
<?PHP
function addnum($num1,$num2)
{
$tot = $num1 + $num2;
return $tot;
}
//Using the function addnum
echo “1 + 2 = ” . addNum(1,2);
?>
</BODY>
</HTML>

Require

The require function works in the same way as a function, except that it is used to call another file which is inserted into the current page. This is useful when a header is being used;

<HTML>
<BODY>
<?PHP
require(“header.php”)
?>
<h3>More text here.</h3>
</BODY>
</HTML>

Email

PHP has built in email support by using the mail() function, it requires the usual email parameters;

Parameter Description
to The recipients address in the form of abc@xyz.com
subject Subject of the email
message Content of the email; use the \n command for a new line
headers An optional parameter which may contain and Cc’s of Bcc’s
parameters Additional parameters that the sendmail program accepts i.e. From

An example of the code for a mail function with error checking is shown below, to send emails to multiple recipients, a comma: , should be used as a delimiter.

<HTML>
<BODY>
<?PHP
$to = “bob@email.com”;
$subject = “Test email”;
$message = “Hello! World \n this is a test email”;
$from = “tom@email.com”;
$headers = “From: $from”;
if (mail($to,$subject,$message,$headers))
echo “Mail Sent sucessfully”;
else
echo “Failed to Send Mail”;
?>
</BODY>
</HTML>

This is very basic example of using emailing, however for a more complete guide to PHP emailing please see PHP Mail article.