Uploaded file doesnt get saved in the server in php - php

I am trying to upload a file and save the file in the server as well as attac and send the file through email.. Attachiing and sending the file through email works fine where has the file doesnt get saved in uploads folders in the server.. How can I save the file in the server has well has send as attachment through email.. Here is the code
<form method="post" action="email-script.php" enctype="multipart/form-data" id="emailForm">
<div class="form-group">
<input type="text" name="name" id="name" class="form-control" placeholder="Name" >
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control" placeholder="Email address" >
</div>
<div class="form-group">
<input type="text" name="subject" id="subject" class="form-control" placeholder="Subject" >
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control" placeholder="Write your message here"></textarea>
</div>
<div class="form-group">
<input type="file" name="attachment" id="attachment" class="form-control">
<div id="attachmentError" style="color: red;font-size: 14px;display: none">attachmentError</div>
</div>
<div class="submit">
<input type="submit" name="submit" onclick="return validateEmailSendForm();" class="btn btn-success" value="SUBMIT">
</div>
</form>
email-script.php
<?php
if(isset($_POST['submit'])){
// Get the submitted form data
$postData = $_POST;
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "uploads/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = $email;
// Sender
$from = 'sender#codingbirdsonline.com';
$fromName = 'CodexWorld';
// Subject
$emailSubject = 'Email attachment request Submitted by '.$name;
// Message
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$name.'</p>
<p><b>Email:</b> '.$email.'</p>
<p><b>Subject:</b> '.$subject.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
}
}
echo '<script>alert("'.$statusMsg.'");window.location.href="./";</script>';
}
?>

Are you getting any error/warning while uploading the attachment ?
Please try to debug the code after this statement : if(!empty($_FILES["attachment"]["name"])){ , like weather you are getting the attachment data in $_FILES.
Check permission of the upload directory weather it's 777(read,write,executable) or not, if not then you should give permission to the directory.
One more thing to check is : max_execution_time and upload_max_filesize in you php.ini file, increase it's value

The unlink function is used to delete files on the server, you can do well to remove or comment out that section.

Related

unable to see status message after sending an email from contact page in html using php

I am trying to send an email from a contact page. the functionality is working fine, I am able to send mails from the html page but the only issue that I am facing is I am unable to see the Status div(success or failed).
Initially the page was redirecting to php file without any status message. I have added page redirect to the actual mailsend.html using header() in php. Now I want to have a status after the send operation whether mail has sent or not.
Below is the code snippet. Please help. Thanks in advance.
mailSend.html code:
<?php if(!empty($statusMsg)){ ?>
<p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>
<form action="example.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="name" class="form-control" value="" placeholder="Name" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="email" name="email" class="form-control" value="" placeholder="Email address" required="">
</div>
<div class="form-group">
<input style = "padding-left:2%; width: 97%;" type="text" name="subject" class="form-control" value="" placeholder="Subject" required="">
</div>
<div class="form-group">
<textarea name="message" class="form-control" placeholder="Write your message here" required="" style = 'border :0.5px solid '></textarea>
</div>
<div class="form-group">
<input type="file" name="attachment" class="form-control" style = 'border :0.5px solid; height: auto;'>
</div>
<div class="submit">
<input type="submit" name="submit" class="btn" value="SUBMIT" style= 'float : right;'>
</div>
</form>
example.php code:
<?php
//first we leave this input field blank
$recipient = "";
//if user click the send button
if(isset($_POST['submit'])){
//access user entered data
$recipient = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$sender = "From: xyz#gmail.com";
//if user leave empty field among one of them
if(empty($recipient) || empty($subject) || empty($message)){
?>
<!-- display an alert message if one of them field is empty -->
<div class="alert alert-danger text-center">
<?php echo "All inputs are required!" ?>
</div>
<?php
}else{
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "uploads/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = 'abc#gmail.com';
// Sender
$from = 'xyz#gmail.com';
$fromName = 'example';
// Subject
$emailSubject = 'Contact Request Submitted by '.$recipient;
// Message
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$recipient.'</p>
<p><b>Email:</b> '.$sender.'</p>
<p><b>Subject:</b> '.$subject.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $recipient;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'succdiv';
?>
<!-- display a success message if once mail sent sucessfully -->
<div class="alert alert-success text-center">
<!--<?php echo "Your mail successfully sent to $recipient"?>-->
<!--readfile('submitResume.html');-->
<?php
header('Location: mailSend.html') ;
echo "Your mail successfully sent to $recipient"
?>
</div>
<?php
$recipient = "";
$postData = '';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
?>
<!-- display an alert message if somehow mail can't be sent -->
<div class="alert alert-danger text-center">
<?php echo "Failed while sending your mail!" ?>
</div>
<?php
}
}
}
}
?>
You are sending to a .html page, which does not process PHP code by default, the server just serves it unless specifically configured on the server. Rename the page from mailSend.html to mailSend.php and it should resolve it. Make sure to change your code to send to .php page.
For further reading see here
You would need to pass the message itself or a way for the script to know which message to show. The easiest way would be to pass it via $_GET, by attaching it to the end of the URL you are trying to redirect. Like so:
$target_url = mailSend.php;
$get_data = '?statusMsg=' . urlencode($statusMsg) . '&$msgClass=' . urlencode($msgClass);
header( 'Location: ' . $target_url . $get_data );
Which you can then recover on mailSend.php via the global $_GET variable. Such as:
$statusMsg = urldecode($_GET['statusMsg']);
$msgClass= urldecode($_GET['msgClass']);
There are other ways to get the data from one page to another but that I will leave it up to you to do research. As it is out of scope for a simple answer.

Email attachment using php, file can't open in email

This is my code, in this case, the code works perfectly and I got the attachment in the mail but the attached file can't be opened. Then I downloaded the file and tried to open it, it shows an error "either not a supported file type or file has been damaged(For example, it was send as an email attachment and wasn't correctly decoded)"
<form action="#" method="POST" enctype="multipart/form-data" >
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="submit" name="upload" value="Upload" />
<br/>
</form>
<?php
if($_POST) {
for($i=0; $i < count($_FILES['csv_file']['name']); $i++){
$ftype[] = $_FILES['csv_file']['type'][$i];
$fname[] = $_FILES['csv_file']['name'][$i];
}
// array with filenames to be sent as attachment
$files = $fname;
// email fields: to, from, subject, and so on
$to = "example#gmail.com";
$from = "example#gmail.com";
$subject ="My subject";
$message = "My message1";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n $data \n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>E-mail with Attachment</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){
// we'll begin by assigning the To address and message subject
$to="example#gmail.com";
$subject="E-mail with attachment";
// get the sender's name and email address
// we'll just plug them a variable to be used later
$from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
$message="This is an example";
$message .= "Name:".$_POST["fromname"]."Message Posted:".$_POST["modlist"];
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// now we'll process our uploaded files
foreach($_FILES as $userfile){
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
// if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content.
// NOTE: we don't set another boundary to indicate that the end of the
// file has been reached here. we only want one boundary between each file
// we'll add the final one after the loop finishes.
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
// here's our closing mime boundary that indicates the last of the message
$message.="--{$mime_boundary}--\n";
// now we just send the message
if (#mail($to, $subject, $message, $headers))
echo "Message Sent";
else
echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="form1">
<p>Your name: <input type="text" name="fromname"></p>
<p>Your e-mail: <input type="text" name="fromemail"></p>
<p>Mod List: <textarea name="question" maxlength="1000" cols="25" rows="6" name="modlist"></textarea>
<p>File: <input type="file" name="file1"></p>
<p>File: <input type="file" name="file2"></p>
<p>File: <input type="file" name="file3"></p>
<p>File: <input type="file" name="file4"></p>
<p>File: <input type="file" name="file5"></p>
<p>File: <input type="file" name="file6"></p>
<p>File: <input type="file" name="file7"></p>
<p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>
</body>
</html>

PHP mail failed to send when included header

So I am trying to mail a form with attachment but when I include $header in my mail it fails to send: mail("mohd.gadiwala#techmatters.com", $subject, $message, $headers)
and when I remove $header from my code mail is being sent but the image attachment being send is text data and not the actual attachment image png form.Everything is crammed up w/o boundary I tried code from this website: Click Me
What am I doing wrong in my code below?:
<?php
if(isset($_POST['submit']) && $_POST['submit']=='Submit')
{
$to="siva.garre#livait.net";
$subject="File sent by ".$_POST['name'];
// get the sender's name and email address
// we'll just plug them a variable to be used later
$from = stripslashes($_POST['name'])."<".stripslashes($_POST['email']).">";
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['comment'];
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
if($_FILES['filename']['tmp_name'] != ''){
// store the file information to variables for easier access
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
}
// here we'll hard code a text message
// again, in reality, you'll normally get this from the form submission
if($tmp_name != ''){
$message = "nn Name: $name nn Email: $email_address nnMessage: nn $message nnHere is your file: $file_name";
}
else{
$message = "nn Name: $name nn Email: $email_address nnMessage: nn $message.";
}
// if the upload succeded, the file will exist
if($tmp_name != ''){
if (file_exists($tmp_name)){
// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
}
}
// now we'll build the message headers
$headers = "From: $fromrn";
if( $tmp_name != '' ){
$headers .= "MIME-Version: 1.0rn" .
"Content-Type: multipart/mixed;rn" ;
// next, we'll build the message body
// note that we insert two dashes in front of the
// MIME boundary when we use it
$message = "This is a multi-part message in MIME format.nn" .
"Content-Type:text/plain;charset=iso-8859-1" .
"Content-Transfer-Encoding: 7bitnn" .
$message . "nn";
// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content and set another boundary to
// indicate that the end of the file has been reached
$message .=
"Content-Type: ".$type."" .
" name=".$file_name."n" .
//"Content-Disposition: attachment;n" .
//" filename="{$fileatt_name}"n" .
"Content-Transfer-Encoding: base64nn" .
$data . "nn" ;
}
// now we just send the message
if (mail("mohd.gadiwala#techmatters.com", $subject, $message, $headers))
echo "<div class='msg msg-ok'><p><strong>Message Sent</strong></p></div><br><br>";
else
echo "<div class='msg msg-ok'><p><strong>Message sending failed</strong></p></div><br><br>";
}
?>
<html>
<body>
<form id="comment" action="atta.php" method="post" enctype="multipart/form-data">
<label>Name <span></span></label>
<input type="text" name="name" id="name">
<label>Email <span></span></label>
<input type="text" name="email" id="email">
<label>Comment <span></span></label>
<input type="text" name="comment" id="email">
<label>Upload file <span></span></label>
<input type="file" name="filename" id="file">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
$headers .= "MIME-Version: 1.0\r\n"; //use \r\n
Hope it helps :)

File not being attached for mailing

I have been trying to create a html form for users to send a mail with an attachment using the php mail function. The mail gets sent successfully but without the attachment. When i tried to check the file being uploaded I don't seem to be getting the file selected by the user. Below is my html code
<form name="message" id="message" method="post" action="mail.php" enctype="multipart/form-data">
<input type="text" class ="text-class" id="name" name="name" placeholder="Name*" required/>
<input type="email" class ="text-class" placeholder="Email*" name="Email" id ="Email" required/>
<textarea class ="text-class" placeholder="Message*" name="Message" id="Message" required></textarea>
<div class="captcha">
<div class="row">
<div class="4u">
<input class ="text-class" type="text" value="2 + 3 is ?" name="question" readonly/>
</div>
<div class="8u">
<input class ="text-class" type="text" placeholder="Answer*" name="captcha" id="captcha" required/>
</div>
</div>
</div>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="attachment" id="attachment"/>
<input type="submit" name="Submit" value="Send" class="submit"/>
</form>
mail.php
<?php
if(isset($_POST['Submit']) && ($_POST['Submit']) == 'Send' )
{
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["Email"]==""||$_POST["Message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['Email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$message = $_POST['Message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
if((empty($_POST['attachment'])) || (empty($_FILES['attachment']))){
echo "No attachement!";
}
else{
//file is attached, process it and send via mail
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
mail("mail#test.com", "Mail from my website", $message, $headers);
echo "Your message has been received by us ! Thank you for contacting us";
echo "<script>
alert('Your message has been sent!');
</script>";
}
exit;
}
}
}else{
echo "Not submitted";
}
?>
I get "No attachment" messaged echoed since I don't seem to be getting the selected file from the html form. Please can someone tell me where I'm going wrong?

Website form - Multiple file upload [duplicate]

This question already has answers here:
Multiple file upload in php
(14 answers)
Closed 8 years ago.
So I have searched through a lot of questions similar to this but cannot seem to find a solution.
I have a contact form and I want it to be able to send multiple images. The code I have now has three input fields for pictures but right now I have only figured out how to get one of the pictures to upload and send. I am pretty sure I need some kind of loop or array but that is not a strong point of mine.
HTML
<form action="test.php" method="post" autocomplete="on" enctype="multipart/form-data" accept-charset='UTF-8'>
<fieldset><label for="Name">Name <sup>*</sup></label>
<input name="name" placeholder="full name" id="Name" required="" autofocus><br>
<label for="email">E-mail <sup>*</sup></label>
<input type="email" name="email" placeholder="youremail#domain.com" id="email" required=""><br>
<label for="phoneNumber">Phone # <sup>*</sup></label>
<input type="tel" name="phone" placeholder="XXX-XXX-XXXX" id="phoneNumber" required=""><br>
</fieldset>
<fieldset>
<label for="year">Year <sup>*</sup></label>
<input type="text" name="year" placeholder="year of car" id="year" required=""><br>
<label for="make">Make <sup>*</sup></label>
<input type="text" name="make" placeholder="make of car" id="make" required=""><br>
<label for="model">Model <sup>*</sup></label>
<input type="text" name="model" placeholder="model of car" id="model" required=""><br>
</fieldset>
<label for="State" class="state">State <sup>*</sup></label><br>
<input type="text" class="state" name="state" id="state" placeholder="Do not enter if you are human">
<fieldset>
<legend>Add Photos <sup>*</sup></legend>
<input type="file" name="attachment" required=""><br>
<input type="file" name="attachment"><br>
<input type="file" name="attachment"><br>
</fieldset>
<label for="comments">Comments</label><br>
<textarea style="float: left;" rows="4" name="comment" id="comments" placeholder="additional comments"></textarea>
<br>
<input class="button" type="submit" name="submit" value="Send" class="button">
<p class="required"><sup>*</sup> denotes a required field.</p>
</form>
PHP
<?php
$to = '';
$name = $_POST['name'];
$email = $_POST ['email'];
$phone = $_POST['phone'];
$year = $_POST['year'];
$make = $_POST['make'];
$model = $_POST['model'];
$comment = $_POST['comment'];
$state = $_POST['state'];
$message = "
Name: $name
E-mail: $email
Phone: $phone
Year: $year
Make: $make
Model: $model
Message: $comment
";
if($_POST['state'] != ''){
echo "It appears you are a bot!";
exit();
}
else{
//process the rest of the form
}
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Start of headers */
$headers = "From: $name $email";
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent. We will get back to you as soon as
possible.";
}
else{
echo "Error in Email sending";
}
?>
All three of your fields are named "attachment". Give them unique names like "attachment1", "attachment2", etc.
Then use this on your upload:
for ($x = 1; $x <= $numberOfFiles; ++$x) {
$tmpName = $_FILES['attachment'.$x]['tmp_name'];
$fileType = $_FILES['attachment'.$x]['type'];
$fileName = $_FILES['attachment'.$x]['name'];
// do your upload here
}
You could even do it in a loop like this, which would allow you to add more file fields (maybe with JavaScript) without changing the backend code, as long as you kept the naming pattern consistent.
$x = 1;
while (isset($_FILES['attachment'.$x])) {
$tmpName = $_FILES['attachment'.$x]['tmp_name'];
$fileType = $_FILES['attachment'.$x]['type'];
$fileName = $_FILES['attachment'.$x]['name'];
// do your upload here
++$x;
}
That just increments x on each cycle, and checks to see if a file was sent with that name.
You should probably also include some checking on the size and type of files, before someone fills your inbox with huge files and/or cyber-nasties.
UPDATE: This should be a mostly-complete solution for you. I'm not able to test it for you at the moment so it may not work straight out of the box, but it should at least point you in the right direction. In this code snippet it sets up the initial part of the email first, then loops through and adds each file one at a time.
<?php
$to = '';
$name = $_POST['name'];
$email = $_POST ['email'];
$phone = $_POST['phone'];
$year = $_POST['year'];
$make = $_POST['make'];
$model = $_POST['model'];
$comment = $_POST['comment'];
$state = $_POST['state'];
$message = "Name: $name
E-mail: $email
Phone: $phone
Year: $year
Make: $make
Model: $model
Message: $comment";
if($_POST['state'] != ''){
echo "It appears you are a bot!";
exit();
}
/* Start of headers */
$headers = "From: $name $email";
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Loop through files */
$x = 1;
while (isset($_FILES['attachment'.$x])) {
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Skip invalid files */
if (!file($tmpName)) {
++$x;
continue;
}
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
++$x;
}
/* Close the message */
$message .= "--{$mimeBoundary}--\n";
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent. We will get back to you as soon as possible.";
} else {
echo "Error in Email sending";
}
?>

Categories