Php 如何使用cURL附加文件?
我正在创建一个zip文件夹,需要将其附加到电子邮件。附加zip文件夹不起作用 我在下面列出了三个共同工作的文件: 发送文件是ajax将文件发送到的位置。然后是一个fileUpload.php文件,它上载单个文件,并为所有上载的文件生成Php 如何使用cURL附加文件?,php,file,curl,zip,email-attachments,Php,File,Curl,Zip,Email Attachments,我正在创建一个zip文件夹,需要将其附加到电子邮件。附加zip文件夹不起作用 我在下面列出了三个共同工作的文件: 发送文件是ajax将文件发送到的位置。然后是一个fileUpload.php文件,它上载单个文件,并为所有上载的文件生成$filename变量数组。这是创建zip文件夹的地方,我尝试用$message将其附加到这里 通信类用于发送电子邮件。最初,zip文件夹是在此处创建/附加的。出于某种原因,我不知道如何让这两个文件一起工作,除了它已经做了什么 模板文件是包含电子邮件html和css
$filename
变量数组。这是创建zip文件夹的地方,我尝试用$message
将其附加到这里
通信类用于发送电子邮件。最初,zip文件夹是在此处创建/附加的。出于某种原因,我不知道如何让这两个文件一起工作,除了它已经做了什么
模板文件是包含电子邮件html和css的地方。还有{variables}。这是文件名和消息变量所在的位置。不过,文件名应该是所有必需的
正在创建zip文件夹。它只是没有连接
有人知道为什么在创建zip时它没有附加到电子邮件上吗?具体地说,代码的这一部分正是我试图做到这一点的地方:
$message["attachment[0]"] = curl_file_create($target_dir . $filename[0] . ".zip",
pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
$filename[0] . ".zip");
发送文件
ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'classes/Communication.php';
require 'fileUpload.php';
$first_name = trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
$last_name = trim(htmlspecialchars($_POST['last_name'], ENT_QUOTES));
$email = trim(htmlspecialchars($_POST['email']));
$phone = trim(htmlspecialchars($_POST['phone']));
$zip = trim(htmlspecialchars($_POST['zip']));
$company = trim(htmlspecialchars($_POST['company'], ENT_QUOTES));
$details = trim(htmlspecialchars($_POST['description'], ENT_QUOTES));
$file = null;
require_once '../config.php';
/************************ Start to Company ******************************/
$placeholders = ['{first_name}',
'{last_name}',
'{phone}',
'{zip}',
'{company}',
'{description}',
'{interest}',
'{email}',
'{lead_owner}',
'{lead_assign}'
];
$values = [
htmlentities($_POST['first_name']),
htmlentities($_POST['last_name']),
htmlentities($_POST['phone']),
htmlentities($_POST['zip']),
htmlentities($_POST['company']),
nl2br(htmlentities($_POST['description'])),
htmlentities($_POST['interest']),
htmlentities($_POST['email']),
$lead_owner = htmlentities($_POST['leadOwner']),
$lead_assign = htmlentities($_POST['leadAssign']),
];
$template = str_replace($placeholders, $values, file_get_contents("templates/quote_to_domain.html"));
$files = null;
if (!empty($_FILES["uploadedFile"]["name"])) {
if ($_FILES['uploadedFile']['error'] == 1) {
$error = "The file {$_POST['first_name']} attempted to upload is too large. Contact them for an alternate way to send this file.";
$template = str_replace("{filename}", "$error", $template);
}
$date = new DateTime();
$fu = new fileUpload();
$filename = $fu->upload();
$uploadedFileTypes = $fu->getImageFileTypes();
$extensions = ['pdf','jpg', 'jpeg', 'png', 'gif'];
//file_put_contents('file_type_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r($uploadedFileTypes, true), FILE_APPEND);
$target_dir = "uploads/";
$differentExtensions = array_diff($uploadedFileTypes, $extensions);
if (count($differentExtensions) > 0) {
//file_put_contents('file_norm_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r('There were other types of files uploaded', true), FILE_APPEND);
$f = new ZipArchive();
$zip = $f->open($target_dir . $filename[0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($zip) {
for ($index = 0; $index < count($filename); $index++) {
$f->addFile($target_dir . basename($_FILES["uploadedFile"]["name"][$index]), basename($_FILES["uploadedFile"]["name"][$index]));
}
$f->close();
$message["attachment[0]"] = curl_file_create($target_dir . $filename[0] . ".zip",
pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
$filename[0] . ".zip");
//$template = str_replace("{filename}", $message, $template);
} else {
throw new Exception("Could not zip the files.");
$msg = "Could not zip the files.";
echo json_encode(['status_code' => 500,
'message' => $msg]);
}
} else {
$out = (count($filename) > 1 ? 'Multiple files were' : 'A file was'). ' uploaded. You can download ' . (count($filename) > 1 ? 'them' : 'the file'). ' from:</ul>';
foreach ($filename as $indFile) {
//print_r($template);
$out .= "<li><a href='/php/uploads/{$indFile}'>{$indFile}</a></li>";
}
$out .= '</ul>';
$template = str_replace("{filename}", $out, $template);
}
foreach ($_FILES as $file) {
foreach($file['name'] as $key => $value) {
if (empty($value)) {
//echo "name is empty!";
$template = str_replace("{filename}", '', $template);
}
if ($file['error'][$key] != 4) {
//echo "error code is 4";
}
}
}
clearstatcache();
}
$to_company = Communication::mail_api($_POST, $filename, $template, 0);
ini\u集('display\u errors',1);
错误报告(E_全部);
需要“classes/Communication.php”;
需要“fileUpload.php”;
$first\u name=trim(htmlspecialchars($\u POST['first\u name',ENT\u引号));
$last_name=trim(htmlspecialchars($_POST['last_name'],ENT_引号));
$email=trim(htmlspecialchars($_POST['email']);
$phone=trim(htmlspecialchars($_POST['phone']);
$zip=trim(htmlspecialchars($_POST['zip']);
$company=trim(htmlspecialchars($_POST['company'],ENT_QUOTES));
$details=trim(htmlspecialchars($_POST['description'],ENT_引号));
$file=null;
需要_once'../config.php';
/************************开始结伴******************************/
$placeholders=[{first_name}',
“{last_name}”,
“{phone}”,
“{zip}”,
“{company}”,
“{description}”,
“{interest}”,
“{email}”,
“{lead_owner}”,
“{lead_assign}”
];
$values=[
htmlentities($\u POST['first\u name']),
htmlentities($\u POST['last\u name']),
htmlentities($_POST['phone']),
htmlentities($_POST['zip']),
htmlentities($_POST[“公司]),
nl2br(htmlentities($_POST['description']),
htmlentities($_POST['interest']),
htmlentities($_POST['email']),
$lead\u owner=htmlentities($\u POST['leadOwner']),
$lead\u assign=htmlentities($\u POST['leadsassign']),
];
$template=str_replace($placeholders,$values,file_get_contents(“templates/quote_to_domain.html”);
$files=null;
如果(!空($_文件[“uploadedFile”][“name”])){
如果($_文件['uploadedFile']['error']==1){
$error=“试图上载的文件{$\u POST['first\u name']}太大。请与他们联系,以获取发送此文件的其他方法。”;
$template=str_replace(“{filename}”,“$error”,“$template”);
}
$date=新的日期时间();
$fu=新文件上传();
$filename=$fu->upload();
$uploadedFileTypes=$fu->getImageFileTypes();
$extensions=['pdf'、'jpg'、'jpeg'、'png'、'gif'];
//文件内容(“文件类型日志”,“\n[{$date->format('Y-m-dh:i:s')}]”。打印($uploadedFileTypes,true),文件附加);
$target_dir=“uploads/”;
$differencetensions=array_diff($uploadedFileTypes,$extensions);
如果(计数($differentitextensions)>0){
//文件内容('file\u norm\u log',“\n[{$date->format('Y-m-dh:i:s')}]”。打印(有其他类型的文件上传,true),文件附加);
$f=新的ZipArchive();
$zip=$f->open($target_dir.$filename[0]。“.zip”,ZipArchive::CREATE | ZipArchive::OVERWRITE);
如果($zip){
对于($index=0;$indexaddFile($目标目录basename($目标目录basename($目标目录basename[“uploadedFile”][“名称”][$index]),basename($目标目录basename($目标目录basename[“名称”][$index]);
}
$f->close();
$message[“附件[0]”]=curl\u file\u create($target\u dir.$filename[0]。.zip),
pathinfo(“uploads/{$filename[0]}.zip”,pathinfo_扩展名),
$filename[0]。“.zip”);
//$template=str_replace(“{filename}”,$message,$template);
}否则{
抛出新异常(“无法压缩文件”);
$msg=“无法压缩文件。”;
echo json_encode(['status_code'=>500,
'消息'=>$msg]);
}
}否则{
$out=(count($filename)>1?'was多个文件':'was一个文件')。已上载。您可以下载。'(count($filename)>1?'this':'the file')。'from:';
foreach($indFile形式的文件名){
//打印(模板);
$out.=“”;
}
$out.='';
$template=str_replace(“{filename},$out$template”);
}
foreach($\u文件为$file){
foreach($file['name']作为$key=>$value){
if(空($value)){
//echo“名称为空!”;
$template=str_replace(“{filename}”,“”,$template);
}
如果($file['error'][$key]!=4){
//echo“错误代码为4”;
}
}
}
clearstatcache();
}
$to_company=Communication::mail_api($\u POST,$filename,$template,0);
这是沟通课。最初,邮政编码在这里(现在仍然是)。我不知道如何让这两个文件按照它们应有的方式一起工作
通信类
class Communication
{
public static function mail_api(Array $msg, Array $filename = null, $template = null, $recipient = false, $attachment = null)
{
$date = new DateTime();
$config = array();
$message = array();
$message['to'] = !$recipient ? $email_to_send_to : $msg['email'];
$message['h:Reply-To'] = !$recipient ? $msg['email'] : '';
$message['subject'] = isset($msg['subject']) ? $msg['subject'] : '';
if ($attachment) {
try {
if (!file_exists($attachment)) {
throw new Exception("File $attachment not found!");
}
$parts = explode('/', $attachment);
$filenames = end($parts);
$message['attachment[0]'] = curl_file_create($attachment,
pathinfo($attachment, PATHINFO_EXTENSION),
$filenames);
file_put_contents('log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Attachment added: \n", FILE_APPEND); //here
} catch (Exception $e) {
file_put_contents('error_log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
}
}
$message['html'] = $template;
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $config['api_url']);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'o:tracking-clicks: false'
));
curl_setopt($ch, CURLOPT_USERPWD, "api:{$config['api_key']}");
$self = new Communication();
if (!empty($file) && !$recipient && count($filename) > 1) {
$f = new ZipArchive();
$zip = $f->open('uploads/' . $filename[0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($zip) {
for ($index = 0; $index < count($_FILES['uploadedFile']['name']); $index++) {
// echo $file['uploadedFile']['name'][$index] . "\n";
//$f->addFile($_FILES['uploadedFile']['tmp_name'][$index], $file['uploadedFile']['name'][$index]);
$f->addFile($target_dir . basename($_FILES["uploadedFile"]["name"][$index]), basename($_FILES["uploadedFile"]["name"][$index]));
}
$f->close();
$message["attachment[0]"] = curl_file_create("uploads/{$filename[0]}.zip",
pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
$filename[0] . ".zip");
} else {
throw new Exception("Could not zip the files.");
}
// $message['html'] = str_replace("{filename}", "A file was uploaded. You can download the file from: <a href='/php/uploads/{$file['uploadedFile']['name']}.zip'>{$file['uploadedFile']['name']}</a>", $message['html']);
} elseif (count($filename) == 1) {
$message["attachment[0]"] = curl_file_create("uploads/{$filename}",
pathinfo("uploads/{$filename}", PATHINFO_EXTENSION),
$filename);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
$result = curl_exec($ch);
curl_close($ch);
$resp = json_decode($result);
file_put_contents('communication_log', "\n[{$date->format('Y-m-d H:i:s')}] " . "Log for {$message['to']}: \n" . print_r(json_encode($resp) . "\n\n" . print_r($message,1), 1), FILE_APPEND);
// print_r($resp);
if (isset($resp->id))
return true;
return false;
} catch (Exception $e) {
file_put_contents('error_log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error for {$message['to']}: \n" . print_r($e, 1), FILE_APPEND);
}
}
类通信
{
公共静态函数mail_api(数组$msg,数组$filename=null,$template=null,$recipient=false,$attachment=null)
{
$date=ne
<tr>
<td> {filename} </td>
</tr>
<tr>
<td><i>{message}</i></td>
</tr>