Could you please help realize the procedure of sending attached files in php. If it is possible, please, provide me with ready code examples. Thanks in advance!
3DProf4online 0 Light Poster
Will Gresham 81 Master Poster
There are multiple resources online which deal with this issue, a quick search comes up with exactly what you are looking for, please research and dont ask other people to do all the work.
Post an example of what you have if it isnt working and we can assist you.
R0bb0b 344 Posting Shark
phpmailer is an amazing class and there are ready examples in the download, just do a search for phpmailer download.
Shanti C 106 Posting Virtuoso
mexabet 49 Good Learner
See if this helps. To use this script, you need to create a folder named uploads where the uploaded files would be stored.
<?php
$maxsize=28480; // Set the maximum upload size in bytes
if (!$_POST['submit']) {
//print_r($_FILES);
$error=" ";
// This will cause the rest of the process to be skipped
//and the upload form displays
}
if (!is_uploaded_file($_FILES['upload_file']['tmp_name']) AND
!isset($error)) {
$error = "<b>You must upload a file!</b><br /><br />";
unlink($_FILES['upload_file']['tmp_name']);
}
if ($_FILES['upload_file']['size'] > $maxsize AND !isset($error)) {
$error = "<b>Error, file must be less than $maxsize bytes.</b><br /><br />";
unlink($_FILES['upload_file']['tmp_name']);
}
if($_FILES['upload_file']['type'] != "image/gif" AND
$_FILES['upload_file']['type'] != "image/pjpeg" AND
$_FILES['upload_file']['type'] !="image/jpeg" AND !isset($error)) {
$error = "<b>You may only upload .gif or .jpeg files.<b><br /><br />";
unlink($_FILES['upload_file']['tmp_name']);
}
if (!isset($error)) {
move_uploaded_file($_FILES['upload_file']['tmp_name'],
"uploads/".$_FILES['upload_file']['name']);
print "Thank you for your upload.";
exit;
}
else
{
echo ("$error");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP File Upload Script</title>
</head>
<body>
<form action="<?php echo(htmlspecialchars($_SERVER['PHP_SELF']))?>" method="post"
enctype="multipart/form-data">
Choose a file to upload:<br />
<input type="file" name="upload_file" size="50" />
<br />
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="Reset" value="Reset" />
</form>
</body>
</html>
This bit of code moves the uploaded file from a temporary directory into the uploads directory:
move_uploaded_file($_FILES['upload_file']['tmp_name'],
"uploads/".$_FILES['upload_file']['name']);
The MIME types included here are: .gif, .pjpeg and .jpeg but you may like to add more file formats.
This first line of the code defines the maximum file size:
$maxsize=28480; // Set the maximum upload size in bytes
You can edit the size to suit your needs.
Shanti C commented: Good Work Friend!!!! +2
helpless_101 0 Newbie Poster
See if this helps. To use this script, you need to create a folder named uploads where the uploaded files would be stored.
<?php $maxsize=28480; // Set the maximum upload size in bytes if (!$_POST['submit']) { //print_r($_FILES); $error=" "; // This will cause the rest of the process to be skipped //and the upload form displays } if (!is_uploaded_file($_FILES['upload_file']['tmp_name']) AND !isset($error)) { $error = "<b>You must upload a file!</b><br /><br />"; unlink($_FILES['upload_file']['tmp_name']); } if ($_FILES['upload_file']['size'] > $maxsize AND !isset($error)) { $error = "<b>Error, file must be less than $maxsize bytes.</b><br /><br />"; unlink($_FILES['upload_file']['tmp_name']); } if($_FILES['upload_file']['type'] != "image/gif" AND $_FILES['upload_file']['type'] != "image/pjpeg" AND $_FILES['upload_file']['type'] !="image/jpeg" AND !isset($error)) { $error = "<b>You may only upload .gif or .jpeg files.<b><br /><br />"; unlink($_FILES['upload_file']['tmp_name']); } if (!isset($error)) { move_uploaded_file($_FILES['upload_file']['tmp_name'], "uploads/".$_FILES['upload_file']['name']); print "Thank you for your upload."; exit; } else { echo ("$error"); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP File Upload Script</title> </head> <body> <form action="<?php echo(htmlspecialchars($_SERVER['PHP_SELF']))?>" method="post" enctype="multipart/form-data"> Choose a file to upload:<br /> <input type="file" name="upload_file" size="50" /> <br /> <input type="submit" name="submit" value="Submit" /> <input type="reset" name="Reset" value="Reset" /> </form> </body> </html>
This bit of code moves the uploaded file from a temporary directory into the uploads directory:
move_uploaded_file($_FILES['upload_file']['tmp_name'], "uploads/".$_FILES['upload_file']['name']);
The MIME types included here are: .gif, .pjpeg and .jpeg but you may like to add more file formats.
This first line of the code defines the maximum file size:$maxsize=28480; // Set the maximum upload size in bytes
You can edit the size to suit your needs.
hi.. does this code displays the uploaded picture? tnx..
3DProf4online 0 Light Poster
Thanks, mexabet, your post seems to be the most helpful for me! :)
R0bb0b 344 Posting Shark
See if this helps. To use this script, you need to create a folder named uploads where the uploaded files would be stored.
<?php $maxsize=28480; // Set the maximum upload size in bytes if (!$_POST['submit']) { //print_r($_FILES); $error=" "; // This will cause the rest of the process to be skipped //and the upload form displays } if (!is_uploaded_file($_FILES['upload_file']['tmp_name']) AND !isset($error)) { $error = "<b>You must upload a file!</b><br /><br />"; unlink($_FILES['upload_file']['tmp_name']); } if ($_FILES['upload_file']['size'] > $maxsize AND !isset($error)) { $error = "<b>Error, file must be less than $maxsize bytes.</b><br /><br />"; unlink($_FILES['upload_file']['tmp_name']); } if($_FILES['upload_file']['type'] != "image/gif" AND $_FILES['upload_file']['type'] != "image/pjpeg" AND $_FILES['upload_file']['type'] !="image/jpeg" AND !isset($error)) { $error = "<b>You may only upload .gif or .jpeg files.<b><br /><br />"; unlink($_FILES['upload_file']['tmp_name']); } if (!isset($error)) { move_uploaded_file($_FILES['upload_file']['tmp_name'], "uploads/".$_FILES['upload_file']['name']); print "Thank you for your upload."; exit; } else { echo ("$error"); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP File Upload Script</title> </head> <body> <form action="<?php echo(htmlspecialchars($_SERVER['PHP_SELF']))?>" method="post" enctype="multipart/form-data"> Choose a file to upload:<br /> <input type="file" name="upload_file" size="50" /> <br /> <input type="submit" name="submit" value="Submit" /> <input type="reset" name="Reset" value="Reset" /> </form> </body> </html>
This bit of code moves the uploaded file from a temporary directory into the uploads directory:
move_uploaded_file($_FILES['upload_file']['tmp_name'], "uploads/".$_FILES['upload_file']['name']);
The MIME types included here are: .gif, .pjpeg and .jpeg but you may like to add more file formats.
This first line of the code defines the maximum file size:$maxsize=28480; // Set the maximum upload size in bytes
You can edit the size to suit your needs.
Thanks, mexabet, your post seems to be the most helpful for me! :)
Sorry to rain on your parade, but you should never go by $_FILES as a security check since this is just a line in the header and can easily be reproduced manually. The browser doesn't even have to provide this info to php so sometimes you won't even be given this info. I could very easily send a php file with the header of "image/gif" or if this is a mail script I could send a virus or what ever I wanted to. You should always parse $_FILES and check the extension that way. This is how I would go about verifying the extension of the filename.
<?php
function returnFileName($file)
{
$dot = strrpos($file, '.');
if($dot === false)//file has no dot
{
return false;
}
$fileinfo = array();
$fileinfo['base'] = substr($file, 0, $dot);
$fileinfo['ext'] = strtolower(substr($file, $dot + 1));
return $fileinfo;
}
$allowedext = array("jpg", "gif");
$filearray = returnFileName(basename($_FILES['upload_file']['name']));
if($filearray == false || !isset($filearray['ext']) || !in_array($filearray['ext'], $allowedext))
{
$error .= "invalid file type";
}
?>
mexabet 49 Good Learner
R0bb0b,
No offenses taken! Instead, we are working together to get a good working script for our fellow community member.
R0bb0b commented: indeed :) +2
R0bb0b 344 Posting Shark
R0bb0b,
No offenses taken! Instead, we are working together to get a good working script for our fellow community member.
And the opportunity to bring into the open and alert countless others of a security misconception that apparently often goes unnoticed.
3DProf4online 0 Light Poster
Thanks guys for all your advices! I will invite one guy today, he is a good programmer. He knows PHP language better than I do :) I will show him this post and we will consider all your tips and code examples in detail! Thanks for your help!
somedude3488 228 Nearly a Posting Virtuoso
Since you seem to have things figured out for the most part this may not be of use to you. I needed a good email class for my projects, so I made one. Its attached.
All you have to do to add uploaded attachments, is use a form with input file fields. the script will load them automatically. you don't have to transfer them to the server first.
you can also use files on the server.
An example how to use it:
<?php
require_once( 'class.email.php' );
$email = new emailHandler();
$email->uploadedFiles = true; //Set to false if you do not want uploaded files and only want to send files already on the server.
//if uploaded files is true then make sure you set the allowed file extensions and the maxsize
$email->allowedFiles = array( 'php','doc','ect...' );
$email->maxSize = 121354; //whatever you want.
$email->from( 'YourWebsite.com','info@yourwebsite.com' ); //set who the email is from.
$email->to( 'test@test.com' ); //you can have as many to's as you want
$email->to( 'someone@somewhere.net' );
$email->cc( 'asdf@asdf.com' ); //you can use carbon copies
$email->bcc( 'asdfadsf@asdkfj.com' ); //you can also use bind carbon copies
$email->subject( 'testing' ); //sets the subject
$type = 'text'; // can be set to 'html' if you want to send html emails.
//to add attachments from server, use:
$email->addAttachment( 'path/to/file.ext' );
$message = "Hello,\n\nWelcome to our site!";
$email->message( $message,$type );
$email->sendMail(); //sends the email(s)
?>
It works fine for me. It could use a little improvement, but that will come when I have some more time to mess with it.
<?php
//Email Handler Class - created by Kyle Keith kkeith@heritagewebdesign.com
class emailHandler {
var $to;
var $from;
var $Cc;
var $Bcc;
var $attachments;
var $message;
var $subject;
var $headers;
var $boundary;
var $uploadFiles;
var $allowedFiles;
var $maxSize;
var $type;
function emailHandler() {
$this->__construct();
}
function __construct() {
$this->to = array();
$this->from = '';
$this->Cc = array();
$this->Bcc = array();
$this->attachments = array();
$this->message = '';
$this->subject = '';
$this->headers = '';
$this->boundary = $this->setBoundary();
$this->uploadedFiles = true;
$this->allowedFiles = array( 'doc','docx','xls','tiff','jpg','jpeg','gif','png','bmp','html','php','js','css','sql' );
$this->maxSize = 500000;
$this->type = 'text';
}
function setBoundary() {
return "==Multipart_Boundary_x" . md5( mt_rand() ) . "x";
}
function validateEmail( $email ) {
if( !preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9\.\\+=_-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$email ) ) {
return false;
}
return true;
}
function buildHeader( $type ) {
$array = $this->$type;
if ( !is_array( $array ) ) {
if ( $this->validateEmail( $array ) ) {
$email = $array;
}
}
elseif ( count( $array ) > 0 ) {
$array = array_filter( $array,array( &$this,'validateEmail' ) );
$email = implode( ',',$array );
}
return "{$type}: $email\r\n";
}
function headers() {
$headers = "From: {$this->from}\r\n";
$head = array( 'Cc','Bcc' );
foreach( $head as $val ) {
$headers .= $this->buildHeader( $val );
}
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed;\r\n";
$headers .= " boundary=\"{$this->boundary}\"";
return $headers;
}
function getFileData( $file ) {
if ( file_exists( $file ) && is_readable( $file ) ) {
$open = fopen( $file,'rb' );
$data = chunk_split( base64_encode( fread( $open,filesize( $file ) ) ) );
fclose( $open );
return $data;
}
die('File not found');
}
function returnMIMEType($filename) {
preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);
switch( strtolower( $fileSuffix[1] ) ) {
case "js" :
return "application/x-javascript";
case "json" :
return "application/json";
case "jpg" :
case "jpeg" :
case "jpe" :
return "image/jpg";
case "png" :
case "gif" :
case "bmp" :
case "tiff" :
return "image/".strtolower($fileSuffix[1]);
case "css" :
return "text/css";
case "xml" :
return "application/xml";
case "doc" :
case "docx" :
return "application/msword";
case "xls" :
case "xlt" :
case "xlm" :
case "xld" :
case "xla" :
case "xlc" :
case "xlw" :
case "xll" :
return "application/vnd.ms-excel";
case "ppt" :
case "pps" :
return "application/vnd.ms-powerpoint";
case "rtf" :
return "application/rtf";
case "pdf" :
return "application/pdf";
case "html" :
case "htm" :
case "php" :
return "text/html";
case "txt" :
return "text/plain";
case "mpeg" :
case "mpg" :
case "mpe" :
return "video/mpeg";
case "mp3" :
return "audio/mpeg3";
case "wav" :
return "audio/wav";
case "aiff" :
case "aif" :
return "audio/aiff";
case "avi" :
return "video/msvideo";
case "wmv" :
return "video/x-ms-wmv";
case "mov" :
return "video/quicktime";
case "zip" :
return "application/zip";
case "tar" :
return "application/x-tar";
case "swf" :
return "application/x-shockwave-flash";
case "sql" :
return "text/plain";
break;
default:
if( function_exists( "mime_content_type" ) ) {
$fileSuffix = mime_content_type($filename);
}
return "unknown/" . trim( $fileSuffix[0],"." );
break;
}
}
function addAttachment( $file,$temp="" ) {
$fileType = $this->returnMIMEType( ($temp !== '' ? $temp : $file) );
$fileData = pathinfo( $file );
$fileName = $fileData['basename'];
$message = "--{$this->boundary}\n";
$message .= "Content-Type: {$fileType};\n";
$message .= " name=\"{$fileName}\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"{$fileName}\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $this->getFileData( ($temp !== '' ? $temp : $file) ) . "\n\n";
$this->attachments[] = $message;
}
function getExtension( $file ) {
$i = strrpos( $file,'.' );
if ( !$i ) {
return "";
}
$l = strlen( $file ) - $i;
$ext = substr( $file,$i + 1,$l );
return $ext;
}
function getAttachments() {
if ( count( $_FILES ) > 0 && $this->uploadedFiles == true ) {
foreach( $_FILES as $name => $array ) {
$tempName = $array['tmp_name'];
$fileName = $array['name'];
if ( file_exists( $tempName ) ) {
if ( is_uploaded_file( $tempName ) ) {
$exten = $this->getExtension( $fileName );
if ( in_array( $exten,$this->allowedFiles ) ) {
$size = filesize( $tempName );
if ( $size <= $this->maxSize ) {
$this->addAttachment( $fileName,$tempName );
}
}
}
}
}
}
}
function getType() {
switch( $this->type ) {
case "text":
$type = 'text/plain';
break;
case "html":
$type = 'text/html';
break;
}
return $type;
}
function to( $email ) {
if ( $this->validateEmail( $email ) ) {
$this->to[] = $email;
}
}
function cc( $email ) {
$this->Cc[] = $email;
}
function bcc( $email ) {
$this->Bcc[] = $email;
}
function from( $name,$email ) {
$this->from = "{$name}<{$email}>";
}
function subject( $text ) {
$this->subject = $text;
}
function message( $message,$type ) {
$this->message = $message;
$this->type = $type;
}
function getMessage() {
$type = $this->getType();
$message = "This is a multi-part message in MIME format.\n\n";
$message .= "--{$this->boundary}\n";
$message .= "Content-Type: {$type}; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: 7bit\n\n" . $this->message . "\n\n";
$this->getAttachments();
$message .= implode( '',$this->attachments );
$message .= "--{$this->boundary}--\n";
return $message;
}
function sendMail() {
$error = 0;
$message = $this->getMessage();
$headers = $this->headers();
foreach( $this->to as $email ) {
if ( !mail( $email,$this->subject,$message,$headers ) ) {
$error++;
}
}
if ( $error > 0 ) {
return false;
}
return true;
}
}
?>
viksan 0 Newbie Poster
This is possible but I think you have to pay!
somedude3488 commented: People shouldn't have to pay to get help on this site. It defeats the main purpose of the w \ebsite. +0
viksan 0 Newbie Poster
I know how can help you ,but maybe have to pay for help.
e-mail : [email removed]
AyuBan 0 Newbie Poster
This message is for KKeith29
Hi thr, I looked at your php script but I didnt understand some code. I am looking for a code that can send online form with attachment (ONLY ONE zip file) by email. I read your thread and it seems your code works. But thr is some line of code that I think I dont need thm. If you could please help solve my problem. I can send the form by email but i only need the attachment part. Thanks
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.