I think this is the line that got you:
$temp_name = $_FILES['attachment']['temp_name'];
should be:
$temp_name = $_FILES['attachment']['tmp_name'];
and
$header .= "Content-Disposition: attachment; filename=\"". $file_name."\"r\n\r\n";
Should be
$header .= "Content-Disposition: attachment; filename=\"". $file_name."\"\r\n\r\n";
I tested your script, made a few changes in my test environment, and here is what I ended up with. I have tested it all the way up until the point of sending the email
Code: Select all
<?php
# Enable Error Reporting
error_reporting(E_ALL - (E_NOTICE + E_WARNING));
# If there is post
if( $_SERVER["REQUEST_METHOD"] == "POST" ) {
# Imports
//require_once "Mail.php";
# Constants
$from = "name@domain_name";
$to = "name@domain_name";
$username = "name@domain_name";
$password = "password";
$host = "smtp.domain_name";
# Handle File Attachments
if( !empty( $_FILES['attachment'] ) ) {
//store some varibles
$file_name = $_FILES['attachment']['name'];
$temp_name = $_FILES['attachment']['tmp_name'];
$file_type = $_FILES['attachment']['type'];
//get the extention of the file
$extension = pathinfo( $file_name, PATHINFO_EXTENSION );
//only these files types wil be allowed
$allowed_extensions = array("doc","docx","zip", "png", "jpg");
//check that this file type is allowed
if( in_array( $extension, $allowed_extensions ) ) {
//mail essentials
$subject = "Testing mail attachment";
$message = "From the office of the Guru";
//things you need
$file = $temp_name;
$content = chunk_split( base64_encode( file_get_contents( $temp_name ) ) );
$uid = md5(uniqid(time()));
// standards mail headers
$header = "From: ".$from. "\r\n";
$header .= "Reply-To: ".$replyto. "\r\n";
$header .= "MIME-Version: 1.0\r\n";
// declaring we have multiple kinds of mails (plain text and attachment
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
//plain text part
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding:7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
//file attachment
$header .= "--".$uid."\r\n";
$header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"". $file_name."\"\r\n\r\n";
$header .= $content . "\r\n\r\n";
//send the mail
if (mail($to, $subject, $message, $header)) {
echo "success";
} else {
echo "fail";
}
} else {
echo "file type not allowed";
}
} else {
echo "no file posted";
}
}
?>
<html>
<head>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="attachment" type="file" /><br />
<input type="submit" value="Send files" />
</body>
</html>