Send files with phpmailer before uploading them? - php

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!

Related

I'm using FormSubmit and File upload. is it possible to upload multiple attachment at a time in formsubmit

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.

How to attach file(s) in php mailer within same php page?

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++;
}
}

How to upload multiple files one by one

I need to upload a lot of images at once (e.g. 200 small images) through the browser. I have this code:
<?php
if(isset($_POST['Upload_files']) and $_SERVER['REQUEST_METHOD'] == "POST"){
echo count($_FILES['files']['name']); // Even if I upload more than 20 files, it still displays 20.
$target_directory = "upload/";
foreach ($_FILES['files']['name'] as $file_number => $file_name) {
$file = $_FILES["files"]["tmp_name"][$file_number];
if (mime_content_type($file) != 'image/png' && mime_content_type($file) != 'image/jpeg')
{ $error[] = 'File '.$file_name.' is not in JPG / PNG format!'; continue; }
else
{ if(move_uploaded_file($file, $target_directory.$file_name)) {$count_of_upload_file++;}}
}
}
// If files were uploaded
if($count_of_upload_file != 0){echo 'Your files ('.$count_of_upload_file.' ) were successfully uploaded.';}
// If there was an error
if (isset($error)) {foreach ($error as $display_error) {echo '- '.$display_error.'<br />';}}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="submit" name="Upload_files" value="Upload files">
</form>
And it works. However my provider set the 'max_file_uploads' to 20 (and I'm not able to change it). (The Uploadify extension is working for more than 20 files, but I'd like to have my own small solution.) So I presume I need to add here something, which instead of 200 files at once uploads 200 files one by one (or twenty by twenty). But I don't know how to do it. (To use AJAX? -- I never used it, so I really don't know.) Thank you!
If you don't want to use ajax, you need a loop to receive files
for($i = 0; $i < count($_FILES['files']['tmp_name']); $i++){
$tmp = $_FILES['files']['tmp_name'][$i];
$name = md5(microtime());
if(move_uploaded_file($tmp, "dir/$name.jpg")){
echo "Uploaded successfully";
}else{
echo "failed";
}
}
In your form you must name all your input fields as files[], example:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="submit" name="Upload_files" value="Upload files">
</form>
Or if you want to use ajax here is an example:
Upload multiple image using AJAX, PHP and jQuery

Image upload failing in PHP

So I'm trying to set up an image upload from a form via php on my localhost and after running the code and connecting to the database okay, I'm getting the error for the upload. Since all of the other parts of the form are working after a section by section check, I'll just add the html for the upload input and its relevant php script.
<input type="file" name="image" id="image-select" />
And the portion of the php that has to deal with the image upload and verification after upload:
$image = $_FILES ['image']['name'];
$type = #getimagesize ($_FILES ['image']['tmp_name']);
//Never assume image will upload okay
if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['image']['error']);
}
//Where the file will be placed
$target_path = "uploads/";
// Add the original filename to target path
$path= $target_path . basename($image);
// Check if the image is invalid before continuing
if($type === FALSE || !($type[2] === IMAGETYPE_TIFF || $type[2] === IMAGETYPE_JPEG || $type[2] === IMAGETYPE_PNG)) {
echo '<script "text/javascript">alert("This is not a valid image file!")</script>';
die("This is not a valid image file!");
} else {
move_uploaded_file($_FILES['image']['tmp_name'], $path);
}
So error appears once the code hits the upload process. I was attempting to upload a small PNG file The relevant code I added is also in their respective orders when they appear in the script.
can you please put error here. If error means that after submit page file is not being upload. then please check your form enctype. see below an example
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image-select" />
<input type="submit" value="Submit">
</form>
Just a wild stab in the dark here as you haven't provided your form tag but you have remembered the enctype attribute haven't you?
Sorry I don't have 50 reputation otherwise I would ask this as a comment.
<form enctype='multipart/form-data' action=''>
<input type="file" name="image" id="image-select" />
</form>
Also you should check if the file uploaded OK before calling getimagesize() (not that this would be the source of your issue)
if you are using PHP5 and Imagick, then you can try to use something like the following:
$image->readImageFile($f);

uploading file to folder on website via PHP

I would like to have the user upload a pdf to a folder on my website. (note:this is for learning purposes, so security is not necessary) The code I have below does not do echo a response when submitted. The folder I would like to have the pdf uploaded to is in the same directory as the php script, is it possible I'm incorrectly referencing that folder? I appreciate it.
<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
Email:<br /> <input type = "text" name="email" value=""/><br />
Resume:<br /><input type = "file" name="resume" value=""/><br />
<p><input type="submit" name ="submit" value="Submit Resume" /></p>
</form>
if(isset($_POST['submit']))
{
define ("FILEREPOSITORY","./resume/");
if (is_uploaded_file($_FILES['resume']['tmp_name'])) {
if ($_FILES['resume']['type'] != "application/pdf") {
echo "<p>Resume must be in PDF Format.</p>";
}
}else {
$name = $_POST['email'];
$result = move_uploaded_file($_FILES['resume']['tmp_name'], FILEREPOSITORY."/$name.pdf");
if ($result == 1) {
echo "<p>File successfully uploaded.</p>";
}
else {
echo "<p>There was a problem uploading the file.</p>";
}
}
}
You have a logical error. Your else statement should be part of the inner if statement -- not the outer one.
would suggest you check the permissions for the upload folder and the max size for file uploading in your php.ini... its happened to me many times uploading a file exceeding the limits and not getting an error message.. also the logic of your if else doesn't match as suggested by your previous post..
IT would be of great help to give the error you receive.
move_uploaded_file()
only works if you have the rights to write to the destination folder.

Categories