Uploading multiple files in single form - php

I have a form on my site which requires users to enter data in a few basic fields, and then upload multiple image files to submit with their form.
The 'form' side of the equation seems easy enough, by simply adding multiple="multiple" to the input field.
However... after many attempts at different variations of code, I am still not understanding (or able) to get the php 'formHandler' side of the equation to actually send multiple image files.
Toying with the code got really confusing, and I made an awful mess of it.
So....
For this example, I left the 'multiple' aspect in the form input, however... to clean up my mess... I stripped back the php 'formHandler' code to where I had it before, which works fine for sending just a single image file.
Any advice as to modify the php 'formHandler' to properly send multiple images would be a life-saver and much appreciated.
Thanks in advance!
The Form:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<h1>The Form</h1>
<form action="/formHandler.php" method="post" enctype="multipart/form-data">
<input type="text" id="userName" name="userName" class="inputField" placeholder=" Enter Your
Name" required><br><br>
<input type="email" id="userEmail" name="userEmail" class="inputField" placeholder=" Enter
Your Email Address" required><br><br><br>
<!-- Start Image Upload Section -->
<a>Select Multiple Images:</a><br><br>
<input type="file" id="file" name="userImages[]" multiple="multiple" required/><br><br><br><br>
<!-- End Image Upload Section -->
<input type="submit" id="submitButton" name="submitButton" value="Submit Form">
</body>
</html>
The php 'formHandler':
<?php
////////////////////////////////////////////////////////////////////////////
$filenameee = $_FILES['userImages']['name'];
$fileName = $_FILES['userImages']['tmp_name'];
$name = $_POST['userName'];
$email = $_POST['userEmail'];
////////////////////////////////////////////////////////////////////////////
$composition =
"\r\n\n\nName: " . $name .
"\r\nEmail Address: " . $email;
////////////////////////////////////////////////////////////////////////////
//Whatever you want to subject of the email to be when you receive the form.
$subject ="Form Submission";
////////////////////////////////////////////////////////////////////////////
//User name and email will be displayed in header when form is received.
$fromname ="$name";
$fromemail = "$email";
////////////////////////////////////////////////////////////////////////////
//The email address at which you want to receive the form.
$mailto = 'receiving#email.com';
////////////////////////////////////////////////////////////////////////////
//The Content Action
$content = file_get_contents($fileName);
$content = chunk_split(base64_encode($content));
//A random hash will be necessary to send mixed content.
$separator = md5(time());
//Carriage return type (RFC)
$eol = "\r\n";
//Main header (multipart mandatory)
$headers = "From: ".$fromname." <".$fromemail.">" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $composition . $eol;
$body .= "--" . $separator . $eol;
$body .= "Content-Type: application/octet-stream; name=\"" . $filenameee . "\"" . $eol;
$body .= "Content-Transfer-Encoding: base64" . $eol;
$body .= "Content-Disposition: attachment" . $eol;
$body .= $content . $eol;
$body .= "--" . $separator . "--";
////////////////////////////////////////////////////////////////////////////
//Mail send action
#mail($mailto, $subject, $body, $headers);
////////////////////////////////////////////////////////////////////////////
//Page Re-direct after form submission
header('location: /formSent_confirmationPage.php');
?>

Change input file name to userImages[] that allows to populate an array and iterate through $_files element ($filename is now an array).
https://www.php.net/manual/en/features.file-upload.multiple.php
$filenameee = $_FILES['userImages']['name'];
$sizes = $_FILES['userImages']['size'];
$fileName = $_FILES['userImages']['tmp_name'];
foreach ($fileName as $tmpname) {
echo "<br> Tmp name: " . $tmpname;
}
foreach ($filenameee as $name) {
echo "<br> Chosen user name : " . $name;
}
foreach ($sizes as $size) {
echo "<br> File size : " . $size/1024 . " Ko";
}

Related

How do I send multiple image attachments in html form with php?

This form handles the form data and a single image nicely.
However... when I add the brackets [] to the file input name to handle multiple images, I receive no images at all in the receiving email. I just receive a blank 'alternative' that displays "Array".
Please advise me what I am missing in this code.
HTML:
<!DOCTYPE html>
<head>
<title>My Form</title>
</head>
<form action="my.php" method="post" enctype="multipart/form-data">
<input type="text" id="userName" name="userName" placeholder=" Enter
Your Full Name"><br><br>
<input type="text" id="userEmail" name="userEmail" placeholder=" Enter
Your Emal Address"><br><br><br>
<input type="file" id="file" name="userImages" multiple /><br><br><br>
<input type="submit" id="submitButton" name="submitButton" value="Submit
Form">
</form>
</html>
PHP:
<?php
$filenameee = $_FILES['userImages']['name'];
$fileName = $_FILES['userImages']['tmp_name'];
$name = $_POST['userName'];
$email = $_POST['userEmail'];
$composition =
"\r\nName: ". $name .
"\r\nEmail Address: " . $email;
$subject ="Email Subject Line";
$fromname ="$name";
$fromemail = "$email";
$mailto = 'myaddress#email.com';
$content = file_get_contents($fileName);
$content = chunk_split(base64_encode($content));
$separator = md5(time());
$eol = "\r\n";
$headers = "From: ".$fromname." <".$fromemail.">" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $composition . $eol;
$body .= "--" . $separator . $eol;
$body .= "Content-Type: application/octet-stream; name=\"" . $filenameee . "\"" . $eol;
$body .= "Content-Transfer-Encoding: base64" . $eol;
$body .= "Content-Disposition: attachment" . $eol;
$body .= $content . $eol;
$body .= "--" . $separator . "--";
if (mail($mailto, $subject, $body, $headers)) {
echo "Thank you for submitting your form."; // The message the user will see after their form
has sent
} else {
echo "mail send ... ERROR!";
print_r( error_get_last() );
}
"Array" - that is an array converted to string (e.g. .). check the php docs for files form with multiple files. the structure of the $_FILES array differs from with a single file.
Error is likely here (and then all similar places):
$filenameee = $_FILES['userImages']['name'];
$filenameee is an array if there are multiple files.
# first file
$filenameee = $_FILES['userImages']['name'][0];
# second file
$filenameee = $_FILES['userImages']['name'][1];
Compare: Uploading multiple files

Sending attachment (.docx) with PHP mail();

while sending a mail using PHP mail() without attachment working fine.
But while sending with attachment sending Failed
please help me.
Whats wrong in my code?
Thanks in advance.
My HTML code is shown below
index.html
<html>
<head>
<title>Mail</title>
</head>
<body>
<form method="POST" action="mail.php" enctype="multipart/form-data">
<input type="text" name="fromName">
<input type="email" name="fromEmail">
<input type="file" name="fileAttach">
<input type="submit" name="submit">
</form>
</body>
</html>
The following is my Mail code
mail.php
<?php
if (isset($_POST['submit'])) {
/* $mailto = $_POST["mailTo"];*/
$mailto = "to#gmail.com";
$from_mail = $_POST["fromEmail"];
$replyto = $_POST["fromEmail"];
$from_name = $_POST["fromName"];
/*$message = $_POST["message"];*/
$message="This is message part";
/*$subject = $_POST["subject"];*/
$subject ="this is subject part";
$filename = $_FILES["fileAttach"]["name"];
$content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: " . $from_name . " <" . $from_mail . ">\r\n";
$header .= "Reply-To: " . $replyto . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--" . $uid . "\r\n";
// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
$header .= "Content-type:text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
// User Message you can add HTML if You Selected HTML content
$header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";
$header .= "--" . $uid . "\r\n";
$header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; // For Attachment
$header .= $content . "\r\n\r\n";
$header .= "--" . $uid . "--";
if (mail($mailto, $subject, $message, $header)) {
echo "<script>alert('Success');</script>"; // or use booleans here
} else {
//echo mysqli_error();
echo "<script>alert('Failed');</script>";
}
}
Is there anything to add or change in the code?

php mail() function to send mail with an attachment

I have created two scripts for this HTML and a corresponding PHP.
HTML markup:
<html>
<body>
<form action="http://senindiaonline.in/admar/non-series-numbers-db.php" method="post" target="_blank" name="non_series_numbers_db" enctype="multipart/form-data">
<label for="emp-id">Employee ID: </label>
<input type="text" name="emp-id" id="emp-id" maxlength="15" style='text-transform:uppercase'/>
<br/>
<label for="no-csv">If you have a mobile number database in CSV file format upload that here: </label>
<input name="no-csv" id="no-csv" type="file" accept=".csv"/>
<br/>
<label for="no-xls">If you have a mobile number database in XLS (excel) file format upload that here: </label>
<input name="no-xls" id="no-xls" type="file" accept=".xls"/>
<br/>
<label for="no-xlsx">If you have a mobile number database in XLSX (excel) file format upload that here: </label>
<input name="no-xlsx" id="no-xlsx" type="file" accept=".xlsx"/>
<br/>
<input name="send" value="Send" type="submit" id="send"/>
</form>
</body>
</html>
PHP script:
<?php
error_reporting(0);
$email_to = 'senindiagroup#gmail.com';
$email_subject = "Non-Seriesed Mobile Number Database from Ad&Marketing Employee Panel of Sen India Online inc.";
$emp_id = $_POST['emp-id'];
$sub="Employee ID: $emp_id";
$bound_text = "jimmyPI23";
$bound = "--" .$bound_text. "\r\n";
$bound_last = "--" .$bound_text. "--\r\n";
$email_message .= "If you can see this MIME than your client doesn't accept MIME types! \r\n" .$bound;
$email_message .= "Content-Type: text/html; Charset=\"iso-8859-1\"\r\n" ."Content-Transfer-Encoding: 7bit\r\n\r\n" ."$sub\r\n" .$bound;
//getting temporary file location with name
$a=file_get_contents($_FILES['no-csv']['tmp_name']);
$b=file_get_contents($_FILES['no-xls']['tmp_name']);
$c=file_get_contents($_FILES['no-xlsx']['tmp_name']);
//getting original name of the file you uploaded
$name=$_FILES["no-csv"]["name"];
$name1=$_FILES["no-xls"]["name"];
$name2=$_FILES["no-xlsx"]["name"];
$email_message .= "Content-Type: {\"application/octet-stream\"}; \n" . "name=\"$name\ "\n" . "Content-Transfer-Encoding: base64\r\n" ."Content-Disposition: attachment; \n" . " filename=\"$name\ "\n"."\r\n" .chunk_split(base64_encode($a)).$bound;
mail($email_to, $email_subject, $email_message, $headers);
?>
The error is:
syntax error showing on line 31, attach file with mail command.
And the mail is not send. I solve this error with DreamWeaver suggestion. Then the mail is send, but the attachment is not included in the mail.
This is the example of sending multiple attachments in mail
<?php
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 message";
$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>";
}
?>
if you want simple solution use phpmailer library, that would be easy to use,easy to configure.

How to make a simple form where users can send me their e-mail [duplicate]

This question already has answers here:
How can I send an email using PHP?
(20 answers)
Closed 6 years ago.
I need someone to guide me on how to properly use Mail () function in php.
I wanted to make a simple form where users can send me their Name and e-mail so that I can send them invitation.
I wanted to code it using mail () function in php.
Note : I'm not intending to create a contact form but a form with just two field ; Just Name and e-mail.
Hope someone can help.
Here is the sample code as per your requirement
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
Your name:<br>
<input name="name" type="text" value="" size="30"/><br>
Your email:<br>
<input name="email" type="text" value="" size="30"/><br>
Your message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<?php
}
else /* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("youremail#yoursite.com", $subject, $message, $from);
echo "Email sent!";
}
}
?>
Hope this helps
You can try This way.
$to_mail="ex#domain.com";
$subject="subject";
$message = "you can put in it your Form Data";// like name and Email that you want to send
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// main header (multipart mandatory)
$headers = "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol . $eol;
$headers .= "--" . $separator . $eol;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"" . $eol;
$headers .= $message . $eol . $eol;
#mail("$to_mail","$subject","",$headers);

PHP mail with attachment not working as a Shortcode

So I've been asked to create a form that once filled in sends an email to my client with the form entry, this must include a .csv file attachment with the included data.
Initially I tested this by hardcoding it to a plain page.
<form class="main-form" method="post">
<ul>
<li><div>Email: </div><input type="email" name="email" size="20" /></li>
<br />
<input type="submit">
</ul>
</form>
<?php
$email=$_REQUEST['email'];
if ($email =="") {
//Do nothing
} else {
$to = "mail#test.co.uk";
$from = "test";
$subject = "test";
//Message Body
$text = "test";
//The Attachment
$cr = "\n";
$data = "Email"
$data .= "$email". $cr;
$fp = fopen('test.csv','a');
fwrite($fp,$data);
fclose($fp);
$attachments[] = Array(
'data' => $data,
'name' => 'diploma_apprenticeship_form_sub.csv',
'type' => 'application/vnd.ms-excel'
);
//Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//Add the headers for a file attachment
$headers = "MIME-Version: 1.0\n" .
"From: BRS\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
//Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$text . "\n\n";
//Add attachments
foreach($attachments as $attachment){
$data = chunk_split(base64_encode($attachment['data']));
$name = $attachment['name'];
$type = $attachment['type'];
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" ;
}
$message .= "--{$mime_boundary}--\n";
mail($to, $subject, $message, $headers);
}
?>
This works fine and emails the attachment exactly as I want. However they now want it as a shortcode so they can post it wherever in their wordpress build. So I've added the shortcode and posted the code into a php function which is called when wordpress detects [form]. But now it doesn't work.
function main_form() {
return <<<HTML
<form class="main-form" method="post">
<ul>
<li><div>Email: </div><input type="email" name="email" size="20" /></li>
<br />
<input type="submit">
</ul>
</form>
HTML;
// Then rest of php as it was above
}
The form outputs fine, but I no longer get an email. Initially I thought that the $_REQUEST[]; wasn't getting the data but I set $email to a fixed string and it still doesn't work.
Anyone have any ideas?
Change your HTML to something like this:
<form class="main-form" method="post" action="file.php">
You'll be redirected to "file.php" after your form will be submitted.
You can find a working example here: http://www.w3schools.com/php/php_forms.asp
Turns out I was using a return statement before the rest of the PHP hence it was printing the HTML and exiting the function. By putting the return at the end of the function it now works!

Categories