I am using php mailer to send emails with attachments. I want files to be attached within the same page. my form,
<form method="POST" action="#" enctype="multipart/form-data">
<label>Files to upload:</label>
<input type="file" name="files[]" multiple/>
<button type="submit" name="btnSend" value="Send">Send</button>
</form>
And my php code snippet is,
if (isset($_POST['btnSend'])) {
$mail = new mymailer();
include DOC_ROOT . 'include/contact-email-template.php';
$mailArray = array("my-email-address");
$subject = "Contact Form";
$from = $email;
$mail->sendMail($from, $mailArray, $subject, $admin_template);
$emailsent = 1;
$mod_email = "Success";
/* redirect to home after success */
if ($emailsent == 1) {
unset($_POST['firstname']);
unset($_POST['lastname']);
unset($_POST['email']);
unset($_POST['phone']);
unset($_POST['message']);
$mod_email = "Show";
}
}
How can I attach the file(s) I chose from input type="file"
Please help.
PS: Emails are sending fine with this code even when I set the action to external file and save chosen image in the disk and attach them. I just want to know how to attach files within the same page.
You can you $_FILES and attach the chosen file into mail body on the same page
if(!empty($_FILES)){
$i = 0;
foreach($_FILES['files']['tmp_name'] as $file){
echo $mail->AddAttachment($_FILES['files']['tmp_name'][$i], $_FILES['files']['name'][$i]);
$i++;
}
}
Related
I'm using Form-Submit(website for sent message to gmail without back-end) and File upload. is it possible to upload multiple attachment at a time in form-submit
Please help me i am using html form....And I want to know...It's working or not if yes ...How can I upload or send multiple attachment through form-submit cause single file already working....And I am also use the files attribute in file attribute place....But it's only select the multiple times file not sent in my mail ...Only sent one attachment at a time....Hlp me
The following code is a very basic mechanism of uploading files. Nowadays there are more advanced libraries that you have to search for.
<?php
if(isset($_POST['upload'])){
$numberOfFiles = sizeof($_FILES["song"]["name"]);
echo "<br>Number of selected files: ".$numberOfFiles.'<br>';
for($i=0; $i<$numberOfFiles; $i++){
$tempName = $_FILES['song']['tmp_name'][$i];
$desPath = realpath(dirname(__FILE__))."/" . $_FILES['song']['name'][$i];
if (file_exists(realpath(dirname(__FILE__))."/" . $_FILES['song']['name'][$i]))
{
echo $_FILES['file']['name'] . " already exists. ";
}
if(!move_uploaded_file($tempName, $desPath))
{
echo "File can't be uploaded";
}
}
}
?>
<form method="post" action="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>" enctype="multipart/form-data">
<input type="file" multiple="multiple" name="song[]" accept="audio/mpeg3"><br></br>
<div class="uploadbtn" align="center">
<input type="submit" name="upload" value="Upload"></div>
</form>
I hope it helps.
I have a problem that made me lose my temper really I have the following code
OK ?
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
$finalpath =realpath(dirname(__FILE__)."/Uploads/".$path);
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
$type = $_FILES["vedio"]['type'];
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
The first problem is supposed to be the process of uploading the file to file uploads
The file is not even uploaded to the same file as the page
Second, the goal is to write the name of the file uploaded within the text, but what is happening in reverse exactly that
So how to make the upload process successful
Inside the uploads / value received from the form section
And the new name of the received value of the form
<form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
<div id="inputs">
<label class="labels" for="name">Vedio Name: </label>
<input id="name" type="text" name="vedionamet" value="vedio"> </br>
<label class="labels" for="selectsection">Select Section :</label>
<select name="selectsection" id="section" >
<?php
foreach($sections as $pathat){
echo "<option value='$pathat'>" . "$pathat" . "</option>";
};
?>
</select></br>
<label class="labels" for="upup">Select Vedio : </label>
<input id="upload" type="file" name="vedio"></br>
<input id="subb" type="submit" name="uploadsub" value="Upload">
</
For the HTML part, you may change the action to "#" if you want to use a same page to handle the upload request.
For the PHP part, you may try the following codes, it works on my computer. Please also make sure that you have already established these sub video folders in Uploads folder
<?php
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
//add one condition to avoid warning when the page first loads
if(isset($_POST["selectsection"])){
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
//Use this to get the path
$finalpath = realpath(dirname(getcwd())) . '\\Uploads\\' . $path. '\\';
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
//Use this to get the extension of file name
$type = pathinfo($vedname, PATHINFO_EXTENSION);
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname.".".$type);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
}
?>
I have a problem with sending emails with attachment by the phpmailer script. I have a working code if I want to add a single file to the mail. But when it comes to multiple files, it looks like they are not even uploaded.
My code for a single file:
if (isset($_FILES['file']) &&
$_FILES['file']['error'] == UPLOAD_ERR_OK)
{
$mail->AddAttachment($_FILES['file']['tmp_name'],
$_FILES['file']['name']);
if(!$mail->Send())
{
header("Location: " . $returnErrorPage);
}
else
{
header("Location: " . $returnHomePage);
}
}
I tried a few codes that should loop through all files in $_FILES without success. Then I tested the following code:
$count = count($_FILES['file']['tmp_name']);
echo $count;
it returns 0. I know that $_FILES is empty, but I dont know the reason for that. Do I need to buffer the files or something like that?
EDIT:
here is my html code which sent the files and other data to the script:
<form id="form_907007" class="appnitro" method="post" action="server/phpmailer.php"
enctype="multipart/form-data">
<p>Choose data (txt, html etc.):<br>
<input name="file" type="file" size="50" maxlength="100000" multiple>
</p>
</form>
The solution of my problem is based on the idea from Synchro, upload the files first and then send the email.
In my html code I had to change this line:
<input name="file" type="file" size="50" maxlength="100000" multiple>
<input name="file[]" type="file" size="50" maxlength="100000" multiple>
it is important to do this little step to reach each file you want to upload later in php.
The second step is to loop through all files an store them on your server. This is the way I did that:
foreach ($_FILES["file"]["error"] as $key => $error){
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$name = $_FILES["file"]["name"][$key];
move_uploaded_file($tmp_name," server/data/$name"}
In the next step I check if the files are uploaded successful, if return = TRUE I add them as attachement to the mail:
if(move_uploaded_file($tmp_name,"server/data/$name" ))
{
$mail->AddAttachment("server/data/$name");
}
If everything went well I can delete the files after I have send the mail:
if($mail->Send()){
foreach ($_FILES["file"]["error"] as $key => $error)
{
$name = $_FILES["file"]["name"][$key];
unlink("$name");
}
header("Location: " . $returnPage);
exit;}
Thank you for all your help!
I am using the following loop to send/attach multiple attachments to my email message.
foreach(array_keys($_FILES['attachment']['name']) as $key) {
$source = $_FILES['attachment']['tmp_name'][$key];
$filename = $_FILES['attachment']['name'][$key]; // original filename from the client
$mail->AddAttachment($source, $filename);
}
But only the first attachment i made is sended.
The form code is
<form method="POST" action="<?php $PHP_SELF ?>" enctype="multipart/form-data">
<input type="file" name="attachment[]" id="attachment" size="30"
onchange="document.getElementById('moreUploadsLink').style.display = 'block';" />
<div id="moreUploads"></div>
<div id="moreUploadsLink" style="display:none;">
Attach another File</div>
<input name="submit" type="submit" value="submit" />
</form>
When one click on Attach another file, another File Upload button is shown, through a JavaScript function:
<script type="text/javascript">
var upload_number = 1;
var attachmentlimit = 5;
function addFileInput() {
var d = document.createElement("div");
var file = document.createElement("input");
file.setAttribute("type", "file");
file.setAttribute("name", "attachment"+upload_number);
d.appendChild(file);
document.getElementById("moreUploads").appendChild(d);
upload_number++;
if(upload_number == attachmentlimit) {
document.getElementById('moreUploadsLink').style.display='none';
}
}
</script>
Only the file attached through the first FileUpload Button is attached and sended, not the others.
Help.
The problem is that you are setting the name attribute of your new input element to attachment1, attachment2, etc. You should be setting this name to attachment[], just like the original input you created.
If you still don't get all your attachments, you can try a var_dump($_FILES) in your PHP script to ensure that you are getting all the files the way you expect them.
How do you use the email->attach function?
I can't figure what is happen, cos when i put the code for email->attach the mesage came in blank(the mail body) and there is no attach.
If i remove that code line, everything come back to normal..
thank you
my controller (sendmail.php)
<?php
class Sendmail extends Controller {
function __construct() {
parent::Controller();
$this->load->library('email');
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('validation');
}
function index() {
$info = array (
'nome' => $this->input->post('nome'),
'mail' => $this->input->post('email'),
'motivo' => $this->input->post('motivo'),
'mensagem' => $this->input->post('mensagem'),
'anexo' => $this->input->post('upload'),
);
$this->load->library('email');
$this->email->set_newline('\r\n');
$this->email->clear();
$this->email->from($info['mail'], $info['nome']);
$this->email->to('example#mai.com');
/* $this->email->cc(''); # não é preciso */
$this->email->subject($info['motivo']);
$this->email->message($info['mensagem']);
$this->email->attach($info['anexo']);
if ($this->email->send() ) {
echo 'sent';
}
else {
$this->load->view('formulario');
# show_error( $this->email->print_debugger() );
}
}
}
?>
my view (formulario.php)
<?php
echo form_open_multipart('davidslv/index.php/sendmail');
?>
<label for="nome">nome</label>
<input type="text" name="nome" id="nome" required />
<label for="email">email</label>
<input type="text" name="email" id="email" required />
<label for="assunto">assunto</label>
<select name="motivo">
<option value="motivo1">motivo1</option>
<option value="motivo2">motivo2</option>
<option value="motivo3">motivo3</option>
</select>
<p> <label for="mensagem">mensagem</label>
<textarea name="mensagem" id="mensagem" rows="8" cols="30" required></textarea>
</p>
<label for="upload">documento</label>
<input type="file" id="upload" name="upload" size="18"/>
<input type="submit" id="enviar" name="enviar" value="Enviar!" />
</form>
You can not directly attach a file from the upload field of your form to an email. You can only attach files to your email from your server, so you need to upload the file from the form with CIs upload library: $this->upload->do_upload() to your server into some directory. the upload library needs to be configured, which file types are allowed etc. if the upload was successful, the do_upload function returns extensive data about where the file is stored. you can use the 'full_path' index from the array to attach this file to the email. then send the mail. after that you may delete the file from your server. Here are some code fragments that might help.
$this->load->library('upload');
if($_FILES['upload']['size'] > 0) { // upload is the name of the file field in the form
$aConfig['upload_path'] = '/someUploadDir/';
$aConfig['allowed_types'] = 'doc|docx|pdf|jpg|png';
$aConfig['max_size'] = '3000';
$aConfig['max_width'] = '1280';
$aConfig['max_height'] = '1024';
$this->upload->initialize($aConfig);
if($this->upload->do_upload('upload'))
{
$ret = $this->upload->data();
} else {
...
}
$pathToUploadedFile = $ret['full_path'];
$this->email->attach($pathToUploadedFile);
...
$this->email->send();
...
}
...
Hope this helped...
$this->email->attach()
Enables you to send an attachment. Put
the file path/name in the first
parameter. Note: Use a file path, not
a URL. For multiple attachments use
the function multiple times. For
example:
$this->email->attach('/path/to/photo1.jpg');
$this->email->attach('/path/to/photo2.jpg');
$this->email->attach('/path/to/photo3.jpg');
$this->email->send();
Codeigniter Email Class
This is Absolutely right code Please Try
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|jpeg|png|txt|php|pdf';
$config['max_size'] = '9000';
$config['encrypt_name'] = true;
$image_data = $this->upload->data();
$fname=$image_data[file_name];
$fpath=$image_data[file_path].$fname;
$this->email->attach($fpath);
step 1:You can not directly attach a file from the upload field of your form to an email. You can only attach files to your email from your server, so you need to upload the file from the form with CIs upload library:
$this->upload->do_upload() to your server into some directory.
step 2:
$file=upload file;
$file_path='uploaded directory on your server(eg:uploads/career)'.$file;
step 3:just include
$this->email->attach($file_path);
$this->email->send();
This is a late update, but it might be useful.
It was said twice
"You can not directly attach a file from the upload field of your form
to an email"
. However, this works fine in Codeigniter 3.0
foreach ($_FILES as $key => $file)
{
if ($file['error'] == 0)
{
$this->email->attach($file['tmp_name'], '', $file['name']);
}
}
(Though, the email is not sent and no errors are shown, if there are two files with the same name)