I'm looking for a very easy way to allow users to upload files (html) to my site. I've tried things like plupload and uploadify and they seem to difficult to implement/buggy. Are there any simple solutions out there?
I actually just worked on this issue recently. Ill let you use my code i wrote. What it does is as soon as a user browses for one file, another upload box pops up and so on and so on. And then, i use phpmailer to send the files as email attachments. Look up phpmailer for more details...
The javascript to add more upload fields.. (put in HEAD)
<script type="text/javascript">
function addElement()
{
var ni = document.getElementById('org_div1');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newDiv = document.createElement('div');
var divIdName = num; newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = '<input type="file" class="fileupload" size="80" name="file' + (num) + '" onchange="addElement()"/> <a class="removelink" onclick=\'removeElement(' + divIdName + ')\'>Remove This File</a>';
// add the newly created element and it's content into the DOM
ni.appendChild(newDiv);
}
function removeElement(divNum)
{
var d = document.getElementById('org_div1');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
</script>
The HTML..
<div id="org_div1" class="file_wrapper_input">
<input type="hidden" value="1" id="theValue" />
<input type="file" class="fileupload" name="file1" size=
"80" onchange="addElement()" /></div>
The process.php page. NOTE: MUST EDIT!!! Search phpmailer and download their class.phpmailer.css class. Edit the configs in the file. Create and "uploads" directory.
<?php
require("css/class.phpmailer.php");
//Variables Declaration
$name = "Purchase Form";
$email_subject = "New Purchase Ticket";
$body = "geg";
foreach ($_REQUEST as $field_name => $value){
if (!empty($value)) $body .= "$field_name = $value\n\r";
}
$Email_to = "blank#blank.com"; // the one that recieves the email
$email_from = "No reply!";
//
//==== PHP Mailer With Attachment Func ====\\
//
//
//
$mail = new PHPMailer();
$mail->IsQmail();// send via SMTP MUST EDIT!!!!!
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "the file ".basename($file['name'])." has been uploaded";
}else {
echo "there was an error";
}
$mail->AddAttachment($target_path);
}
$mail->Body = $body;
$mail->IsHTML(false);
$mail->Subject = $email_subject;
if(!$mail->Send())
{ echo "didnt work";
}
else {echo "Message has been sent";}
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
unlink($target_path);}
}
?>
Let me know if you have any questions!!
Check out the jQuery Mulitple File Upload Plugin. The Uploading multiple files page in the PHP documentation will give you an idea what the submitted result looks like and some examples for working with it.
Related
UPDATE #2 - FINAL ANSWER
I figured and you'll see in the comments below that my comparison symbol needed to be changed. So I took the code in Update #1 and simply changed this:
return filemtime($a) < filemtime($b);
to:
return filemtime($a) > filemtime($b);
And that did it!!! Thanks everyone for the dialog.
UPDATE
I've updated my code. Now I'm getting the attachment sent but again, it's not grabbing the latest one. Here's my latest code:
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php/PHPMailer2020/src/Exception.php';
require 'php/PHPMailer2020/src/PHPMailer.php';
$dir = "php/sketch-drawings/";
$pics = scandir($dir);
$files = glob($dir . "*.*");
usort($files, function($a, $b){
return filemtime($a) < filemtime($b);
});
foreach ($files as $pics) {
echo '<img src="'. $pics . '">';
}
// SEND EMAIL W/ ATTACHMENT OF LATEST IMAGE
$mail = new PHPMailer();
$mail->Sender = "hello#myemail.com";
$mail->From = "mail#myemail.com";
$mail->FromName = "My Company";
$mail->AddReplyTo( "mail#mycompany.com", "DO NOT REPLY" );
//$mail->AddAddress("info#mycompany.com");
$mail->AddAddress("myemail#gmail.com");
$mail->isHTML(true);
$mail->Subject = "Latest Sketch Image";
$mail->Body = "Latest Image Attached! \n\n Thanks - XYZ Digital.";
$mail->AddAttachment($pics);
if(!$mail->Send()) {
echo 'Email Failed To Send.';
}
else {
echo 'Email Was Successfully Sent.';
echo "</p>";
echo '<script language="javascript">';
echo 'alert("Thanks! Message Sent")';
echo '</script>';
}
$mail->ClearAddresses();
?>
This issue:
The AddAttachment($filepath) returns an attachment, but it's not the most recent one-- I need it to always return the most recent image in the directory.
Here's what I'm doing:
I've created a web application that is basically a sketch pad. When a user taps on "Save" the code snaps a pic of the element saves it to a directory and then sends an email to the pre-defined address with the snap of the canvas as an attachment... and the issue is above.
What I've done:
I've looked all over the place for a solve -- seems as though the only find is around uploading the attachments via a web form--which isn't my issue. My workflow is different and why I'm here asking now. :)
What's not working:
Everything works except for the attachment part. I'm using PHPMailer but for some reason, the attachment is never the latest one. In fact, it seems to always be the same attachment no matter what.
I tried to get the first element in the array doing this (which I echo in the bottom of the code and it returns the right image:
$mail->addAttachment($sketches[0]);
this doesn't work -- it sends the email, but nothing attached.
How in the world, can I adjust my code below to get the latest attachment? I appreciate any help as PHP is not my area of expertise.
See the code below...
<?php // NEW
// DEFINE ERRORS
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer2020/src/Exception.php';
require 'PHPMailer2020/src/PHPMailer.php';
// GET LATEST UPLOAD -- AND HAVE IT STORED IN DOM (WHEN NEEDED)
$path = ('sketch-drawings');
// Sort in descending order
$sketches = scandir($path, 1);
$latest_ctime = 1;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
// SEND EMAIL W/ ATTACHMENT OF LATEST IMAGE
$mail = new PHPMailer();
$mail->Sender = "hello#myemail.com";
$mail->From = "mail#myemail.com";
$mail->FromName = "My Company";
$mail->AddReplyTo( "mail#myemail.com", "DO NOT REPLY" );
//$mail->AddAddress("info#myemail.com");
$mail->AddAddress("myemail#gmail.com");
$mail->isHTML(true);
$mail->Subject = "Latest Sketch Image";
$mail->Body = "Latest Image Attached! \n\n Thanks - XYZ Digital.";
$mail->AddAttachment($filepath);
//$mail->addAttachment($sketches);
if(!$mail->Send()) {
echo 'Email Failed To Send.';
} else {
echo $filepath;
echo "<br><br>";
print $latest_filename;
echo "</p>";
echo "<p>";
print $sketches[0];
echo "</p>";
echo "<p>";
echo 'Email Was Successfully Sent.';
echo "</p>";
echo '<script language="javascript">';
echo 'alert("Thanks! Message Sent")';
echo '</script>';
}
$mail1->ClearAddresses();
}
?>
PHP's dir() function returns items in an indeterminate order. If you want to retrieve files ordered by date, see this answer.
I have a google apps scripts app that gets Gmail message attachments, posts it to DB using JDBC. then on the server, a PHP script gets the data and puts in into a file and attaches it to an email.
the problem is that the files are corrupt when email arrives
here is the google apps script function that gets the attachment content
function getMessageAttachmentsArray(msg){
var GmailAttachments = msg.GmailMessage.getAttachments();
var validAttachments = [];
var attachmentNames = [];
if(GmailAttachments)
{
for(i in GmailAttachments)
{
var gName = GmailAttachments[i].getName();
attachmentNames.push(gName);
var mimeType = GmailAttachments[i].getContentType();
var size = GmailAttachments[i].getSize();
var content = Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);
var push = {"content":content,"mimeType":mimeType,"fileName":gName,"size":size,"id":""};
validAttachments.push(push);
}
}
return [validAttachments, attachmentNames];
}
here is the PHP code that generated the email from the file data:
require_once 'smtpmail/classes/class.phpmailer.php';
$mail = new PHPmailer(true);
$email = $argv[1];
$messageid = $argv[2];
$fax_number = $argv[3];
$attachments = array();
//get the attachments for this email
$Sql = "select * from user_attachments where email = '$email' and messageid like '$messageid%'";
$res = mysql_query($Sql);
while($row = mysql_fetch_array($res)){
$return['filename'] = $row['name'];
$return['mime'] = $row['mime_type'];
$content = base64_decode(str_pad(strtr($row['raw_data'], '-_', '+/'), strlen($row['raw_data']) % 4, '=', STR_PAD_RIGHT));
$temp_file = tempnam(sys_get_temp_dir(), 'Fax');
file_put_contents($temp_file, $content);
$return['file'] = $temp_file;
array_push($attachments, $return);
}
try{
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SetFrom("example#example.com", "example email");
$mail->Subject = '';
$mail->Body = ' '; //put in a blank body to avoid smtp error
$mail->AddAddress($email);
foreach($attachments as $file){
$mail->AddAttachment($file['file'], $file['filename'], 'base64' ,mime_content_type($file['file']));
}
if($mail->send()){
echo "email to $email sent successfully\n";
}else{
echo "error sending email to $email\n";
}
}catch(phpmailerException $e){
echo $e->errorMessage();
}catch(Exception $e){
echo $e->getMessage();
}
When the message is received it shows the attachments but when downloaded I can not open them and there is a message that the file is corrupt or the file extension does not match the file format
what am I doing wrong?
Thanks in advance.
EDIT:
I tried emailing the attachment without posting to the DB, by posting to the server with UrlFetchApp() and the results are the same. clearly, I am doing something wrong with Base64_encode / decode...
maybe the google apps scripts :
Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);
creates a different base64 format than PHP base64_decode expects?
p.s.
I tried also with and without 'str_pad' and I still got the same results.
I changed:
Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);
to:
Utilities.base64Encode(GmailAttachments[i].getBytes());
and it works
I am stucked while giving file upload path, i have a html file input name uploadfile and i am using phpmailer() to send attachement. Please help me i need php developers support. here is my code tell me why i am getting Could not access file error. and my email is not having attachment only message is coming.
<div class="field">
<label for="Browse">File to upload: <span class="required">*</span></label>
<div class="inputs">
<input name="uploadedfile" id="uploadedfile" type="file" style=" height: 37px;" name="MAX_FILE_SIZE" value="100000" />
</div>
</div>
//Form Fields
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$verify = isset($_POST["verify"]) ? $_POST["verify"] : "";
$path = $_FILES["uploadedfile"]["name"];
echo $path;
$encoding = 'base64';
$type = 'application/octet-stream';
$objmail->From = $email;
$objmail->FromName = $name;
$objmail->AddAddress($toAddress, $toName);
$objmail->AddReplyTo($email, $name);
$objmail->Subject = $email_subject;
$objmail->MsgHTML($email_body);
$objmail->AddAttachment($path,$encoding,$type);
if(!$objmail->Send()) {
$error = "Message sending error: ".$objmail->ErrorInfo;
}
}
Two problems:
First:
$path = $_FILES["uploadedfile"]["name"];
$objmail->AddAttachment($path,$encoding,$type);
$path is going to be the name of the file as it was on the CLIENT machine. That has absolutely nothing to do with the temporary file that PHP stores it in, which is listed in ['tmp_name'].
Second:
You don't validate that an upload occurred at all, and are simply assuming it succeeded. At minimum, you need to have
if ($_FILES['uploadedfile']['error'] === UPLOAD_ERR_OK) {
$objmail->AddAttachment(
$_FILES['uploadedfile']['tmp_name'], // temp location on server
$_FILES['uploadedfile']['name'], // name that appears in email
'base64',
$_FILES['uploadedfile']['type'] // mime type provided by uploader
);
}
I have a file upload page that works but I'm trying to do some error alerts to choose if you want to replace or not.
This is my php file that does the upload
<?php
require ("connect.php");
$filename = "docs/".$_FILES['datafile']['name']."";
$d=explode(".",$_FILES['datafile']['name']);
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
} else {
$target_path = "docs/";
$target_path = $target_path . basename( $_FILES['datafile']['name']);
if(move_uploaded_file($_FILES['datafile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['datafile']['name'])." has been uploaded";
$error = 0;
}
else
{
echo "There was an error uploading the file, please try again!";
$error = 1;
}
}
if ($error != 1)
{
$r1 = mysql_query("insert into full_dump (file_name) values ('".$_FILES['datafile']['name']."')")or die(mysql_error());
$file1 = "docs/".$_FILES['datafile']['name']."";
$lines = file($file1);
$count = count($lines);
$fp = fopen("docs/".$_FILES['datafile']['name']."","r");
$data=fread($fp,filesize("docs/".$_FILES['datafile']['name'].""));
$tmp=explode ("\n", $data);
for ($i=0; $i<$count; $i++)
{
$a=$tmp[$i];
$b=$i+1;
$r2 = mysql_query("update full_dump set field_".$b."='".$a."' where file_name='".$_FILES['datafile']['name']."'")or die(mysql_error());
}
echo"</br>";
echo "Uploading Complete</br>";
echo "Uploaded File Info:</br>";
echo "Sent file: ".$_FILES['datafile']['name']."</br>";
echo "File size: ".$_FILES['datafile']['size']." bytes</br>";
echo "File type: ".$_FILES['datafile']['type']."</br>";
}
?>
What I want to have is instead of
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
}
to have an alert if I would like to replace the file or not. If it's yes it would replace the file, delete the old record in the db and insert the new record. I it's no don't do nothing...or show a message "canceled by user". Could I have $error to be assigned a value for YES or NO on user choosing or not to replace?
UPDATE
This is the form page for upload.
<html>
<head>
<script language="Javascript">
function fileUpload(form, action_url, div_id) {
// Create the iframe...
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "upload_iframe");
iframe.setAttribute("name", "upload_iframe");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("style", "width: 0; height: 0; border: none;");
// Add to document...
form.parentNode.appendChild(iframe);
window.frames['upload_iframe'].name = "upload_iframe";
iframeId = document.getElementById("upload_iframe");
// Add event...
var eventHandler = function () {
if (iframeId.detachEvent) iframeId.detachEvent("onload", eventHandler);
else iframeId.removeEventListener("load", eventHandler, false);
// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
}
else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
}
else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
document.getElementById(div_id).innerHTML = content;
// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
}
if (iframeId.addEventListener) iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent) iframeId.attachEvent("onload", eventHandler);
// Set properties of form...
form.setAttribute("target", "upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");
// Submit the form...
form.submit();
document.getElementById(div_id).innerHTML = "Uploading...";}
</script>
</head>
<body>
<form enctype=\"multipart/form-data\" method=\"POST\">
<input type="file" name="datafile" />
<input type="button" value="upload" onClick="fileUpload(this.form,'file_upload.php','upload'); return false;" >
<div id="upload"></div>
</form>
<?php
require("connect.php");
$result = mysql_query("SELECT * FROM full_dump")or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "Job number: ".$row['file_name']."</br>";
}
?>
you should do this with ajax... when you will send ajax request you will check if file exist or not .. if yes return eg -1 and ask user for relapsing ...
Enjoy :)
instead of using upload code on same page. do one thing, upload file by using ajax request. then check on backend site file is aleady exist or not and according to that show message as you like
I am new to PHP and I am trying to create a PHP form field and I have four "Check Boxes" named Output1, Output2, Output3, and Output4 but when I select all four Check Boxes it only send me one and not all four values.
NOTE I have other fields on this from as well but I just wanted to provide you the HTML form info for Output.
Here is the HTML:
<form id="surveyForm" class="form" action="mailsurvey.php" method="post" name="surveyForm" enctype="multipart/form-data" onsubmit="return ValidateContactForm2();">
<input id="Output1" type="checkbox" name="Output1" value="Isolated" />
<input id="Output2" type="checkbox" name="Output2" value="Isolated" />
<input id="Output3" type="checkbox" name="Output3" value="Isolated" />
<input id="Output4" type="checkbox" name="Output4" value="Isolated" />
</form>
PHP Code:
<?php
require("includes/class.phpmailer.php");
require("includes/class.smtp.php");
require("includes/class.pop3.php");
if($_FILES['headshot']['name']!="")
{
$imgtype=explode('.',$_FILES['headshot']['name']);
$len=sizeof($imgtype);
$image_file=uniqid().'.'.$imgtype[$len-1];
$tmppath='uploads/';
move_uploaded_file($_FILES['headshot']['tmp_name'],$tmppath.$image_file);
$file_path=$tmppath.$image_file;
}
else
{
$file_path="";
}
if($_FILES['bodyshot']['name']!="")
{
$imgtype=explode('.',$_FILES['bodyshot']['name']);
$len=sizeof($imgtype);
$image_file=uniqid().'.'.$imgtype[$len-1];
$tmppath='uploads2/';
move_uploaded_file($_FILES['bodyshot']['tmp_name'],$tmppath.$image_file);
$file_path2=$tmppath.$image_file;
}
else
{
$file_path2="";
}
$mail = new PHPMailer();
$mail->Host = "localhost";
$mail->Mailer = "smtp";
$name = $_POST['name'];
$company = $_POST['company'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['Comments'];
$totalpower = $_POST['Total_Power']." ".$_POST['Total_Power2']." ".$_POST['Total_Power3']." ".$_POST['Total_Power4']." ".$_POST['Total_Power5'];
$input = $_POST['Input']." ".$_POST['Input2']." ".$_POST['Input3']." ".$_POST['Input4'];
$strings = $_POST['Strings4']." ".$_POST['Strings3']." ".$_POST['Strings2']." ".$_POST['Strings'];
$output = $_POST['Output1']." ".$_POST['Output2']." ".$_POST['Output3']." ".$_POST['Output4'];
$dimming = $_POST['Dimming4']." ".$_POST['Dimming3']." ".$_POST['Dimming2']." ".$_POST['Dimming'];
$packaging = $_POST['Packaging4']." ".$_POST['Packaging3']." ".$_POST['Packaging2']." ".$_POST['Packaging'];
$subject = "New Product Inquiry / Survey";
$body = "Name: " .$name. "<br> ".
"Company: " .$company. "<br>".
"Phone: " .$phone."<br>".
"Email: " .$email."<br><br><hr>".
"Total Power: " .$totalpower."<br>".
"Input: " .$input."<br>".
"Strings: " .$strings."<br>".
"Output: " .$output."<br>".
"Dimming: " .$dimming."<br>".
"Packaging: " .$packaging."<br>".
"Comments: " .$comments."<br>"
;
$mail->IsSMTP();
$mail->From = 'support#domain.com';
$mail->FromName = 'support#domain.com';
$mail->Subject = "New Product Inquiry";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
if($file_path!="")
{
$mail->AddAttachment($file_path);
}
if($file_path2!="")
{
$mail->AddAttachment($file_path2);
}
$mail->MsgHTML($body);
$mail->AddAddress('email#domain.com');
if(!$mail->Send())
{
$msg = "Unable to send email";
}
else
{
$msg = header("location: thank-you2.php");
}
?>
Can someone please tell me why this form will not send ALL Output Fields if a user selects all four boxes. If you have any questions please let me know.
Thanks,
Frank
I figured out what my problem was and the reason why I wanted to post this answer for others to be aware of.
My problem was I was working on the wrong PHP file. I have two of the same PHP files in my site one was burred under a couple folders and one was at the root of the site. The one burred was the one I should have been working on making changes to because that was the LIVE file. While I was uploading a file that wasn't working because it was the wrong one. I figured that out by double check the path in the form element of the form page.
<form id="surveyForm" class="form" **action="subfolder/formmailer_scripts/mailsurvey.php"** method="post" name="surveyForm" enctype="multipart/form-data" onsubmit="return ValidateContactForm2();">
So the morel of the story is pay attention and make sure you don't over look the simple things. I wasted about an hour on this reuploading a file that wasn't were it need to be. Hope this helps others!