by August 4, 2005 0 comments



Any installation of Web server-side languages such as ASP, ASP.NET, JSP, Servlets and PHP come with out-of-the-box 
capabilities to do minimal things such as file uploading and e-mailing. But these out-of-box ways to handle file uploading and 
e-mailing require mundane and careful coding, and may even  require thorough understanding of HTTP and SMTP. That’s where libraries, modules and classes come handy. These encapsulate the nitty gritties, and present a set of clean, readable and readily usable functions to achieve the needful. 

Direct
Hit!

Applies to: Web and PHP developers

USP: Use PHPMailer and fileupload to speed up coding times

Primary link: http://dave.imarc.net/php/#fileupload
http://phpmailer.sourceforge.net/ 

Google keywords: php+class+mail+attachment, php+class+file+upload

PHP provides out-of-box functions to handle file uploads and e-mailing. But detecting the MIME type of file uploads, validating the dimensions of an uploaded image, sending HTML e-mail and e-mail attachments requires understanding the protocols. Two classes fileupload and PHPMailer do this for us.

This article uses the code examples we’ve used in PCQLinux 2005 running Apache Web server with
PHP. 

File uploader
This class does almost everything needed of file uploads. 

Download it from http://dave.imarc.net/downloads/fileupload. tar.gz. Extract the archive, which will produce a directory named ‘fileupload’. In this directory, you will find the file named fileupload-class.php which needs to be included in your PHP 
scripts. Here’s an example script, which will present an upload form to the user and save the uploaded file to a directory named uploads.

<?php
include("fileupload-class.php");
if(isset($_POST["submit"]))
{
$uploaderobj = new uploader(); 
$uploaderobj->max_filesize(1000000);
$uploaderobj->upload(“uploadfield”, “”, “”);
$uploaderobj->save_file(“uploads/”, 1);
if ($uploaderobj->error) 
$msg = “File Upload Error: ” . $uploaderobj->error;
else
$msg = “File Upload Successful”;
}
?>
<html>
<body>
<?php print($msg) ?>
<br>
<form enctype=”multipart/form-data” method=”post” action=”upload.php” >
Upload: <input name=”uploadfield” size=”20″ class=”textfield” type=”file”>
<br>
<input type=”submit” name=”submit” value=”Upload File”>
</form>
</body>
</html> 

Save the above file as upload.php in the directory /var/www/ html. Also copy the file fileupload-class.php in this directory. Create a directory named uploads in /var/www/html and give it all (global, 777) permissions. Now, let’s parse through the code in the file upload.php. Notice the attribute enctype=”multipart/form-data” in the form tag. We also have an input field with type=file which will present a text field with a Browse button to choose the file to upload. Coming to the actual PHP code, the first statement creates an uploader object. The next statement sets the maximum allowed size of the upload file, specified in bytes (1 MB in this case). The statements

$uploaderobj->upload("uploadfield", “”, “”);

$uploaderobj->save_file("uploads/", 1);

upload the file and save them into the uploads directory respectively. The upload function takes the name of <input type=“file”> field as one of its parameters. To accept only certain file types, say, only GIF, you can pass the MIME type as the second parameter. You can 
specify more than one MIME type separated by commas. For  example, to accept JPEG files along with GIF files: 

$uploaderobj->upload("uploadfield",
"image/gif,image/jpeg", “”);

You can specify a default extension for such files as the third parameter to the upload function. For example,

$uploaderobj->upload("uploadfield", “”, “.bin”);

Next, with save_file function you can specify the directory where to save the uploaded file and a mode (1 in this case). You can specify the following modes.

1 = overwrite existing file
2 = rename if filename already exists (file.txt becomes 
file_copy0.txt)
3 = do nothing if a file exists

To save the uploaded file as ‘myfilename’, add the following statement before the save function.

$uploaderobj->file[‘name’]= “myfilename”;

While uploading images, you may like to allow to upload images of a specified width and height. Suppose you want to allow upload of images of width 100 and height 80, add the following statement before the call to max_filesize( ) function.

$uploaderobj->max_image_size(100,80);

This intelligently imposes the width and height constraints to only image files. Also, $uploaderobj->error gives you an explanatory error message upon failure of the upload, quite useful for debugging. 

PHPMailer
PHP’s mail( ) function is sufficient to send no-frills e-mail. But the moment you want to send HTML e-mail, add CC and BCC addresses, you will have to start setting the mail headers. Moreover sending attachments is a nightmare using this function wherein you will have to construct a multipart MIME header and encode the attachment data in base64 and so on. With PHPMailer it is as simple as using the function addAttachment() with the path to the file (to be sent as attachment) as the parameter. Let’s see how to use it. 

Download PHPMailer from phpmailer.sourceforge.net. Extract the archive, which will produce a directory named phpmailer-<version>. You will find files named class.phpmailer.php and class.smtp.php, which we will be using in our PHP code. Copy these two files to /var/www/html. Save the contents below in a file named mail.php in the HTML directory.

<?php
include(“class.phpmailer.php”);
$mail = new PHPMailer();
$mail->IsMail();
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->From = “from@foo.com”;
$mail->FromName = “Sender”;
$mail->AddAddress(“to@foo.com”);
$mail->AddCC(“cc@foo.com”);
$mail->AddBCC(“bcc@foo.com”);
$mail->Subject = “Hi”;
$mail->Body = “<b>This is a mail sent using PHPMailer</b>”;
if($mail->Send())
$msg=”Mail Sent”;
else
$msg=”Error : ” . $mail->ErrorInfo;
print($msg);
?>

The code is self-explanatory. One of the noteworthy statements is $mail->IsMail( ). With the statement the mail is sent using PHP mail( ) function. Other options are sending it through a SMTP server, sendmail or qmail. To send a mail using a remote SMTP server, you need to add substitute $mail->IsMail() with $mail->IsSMTP( ) and specify the IP or hostname of the mail server as:

$mail->Host = “mail.foo.com”; 

To top it all, PHPMailer also support SMTP authentication, wherein you can specify the user name and password required for SMTP authentication as:

$mail->SMTPAuth = true;
$mail->Username=”foo”;
$mail->Password=”secret”;

You must set the variable SMTPAuth to true (as in the first  statement) for authentication to occur. Sending attachments with PHPMailer is easy. For example, consider

$mail->AddAttachment("files/file1.zip");

The above statement will attach a file named file1.zip found in a directory named files, which is in the same directory as mail.php (/var/www/html in our case). You can also specify an absolute path to the file as:

$mail->AddAttachment("/var/www/html/files/file1.zip");

To add more than one file, repeat the AddAttachment( ) 

statement with the path to the files. So now on you will zip through the file uploads and e-mailing modules in your PHP projects.

Shekhar Govindarajan, IT4Enterprise

No Comments so far

Jump into a conversation

No Comments Yet!

You can be the one to start a conversation.

<