Sending Email with PHP Networking - Code Examined (
Page 4 of 5 )
Let's take a look at the code. First we check to see if the form was submitted:
<?
//is form submitted
if(isset($_POST['key'])){
Then we collect the form data and store it in shorter variables:
//collect the information
$from=$email;
$cc=$_POST['cc'];
$bcc=$_POST['bcc'];
The next step is to filter the data and set the error message for each of the required fields:
if(empty($_POST['tos'])){
$error=true;
}else{
$to=$_POST['tos'];
}
if(empty($_POST['sub'])){
$error=true;
}else{
$subject=$_POST['sub'];
}
if(empty($_POST['msg'])){
$error=true;
}else{
$msg=$_POST['msg'];
}
Finally we test to see if the user wants to send an attachment. The attachment is sent through the $_FILES[''] array. If the file is loaded, we set the headers for the mail function. Notice that the content-disposition and content-transfer-encoding has also been set:
//check if the an attachment is present
if(isset($_FILES['userfile']['name'])){
$attachment = $_FILES['userfile']['tmp_name'], $_FILES['userfile']['name'];
$headers ="Content-disposition: attachment;
$filename=.$attachment."n";
$headers=.Content-Transfer-Encoding: base64n";
}
If there are no errors, the code continues to send the email message with or without the headers:
if(!$error){
if($headers <> ""){
$res=mail($to,$subject,$msg,$headers);
}else{
$res=mail($to,$subject,$msg);
}
}
Finally, an error check is made to inform the user if any errors occurred.
if(!$res){
echo "Mail error occurred";
}
}
?>