php - 如何使用 cURL 附加文件?
问题描述
我正在创建一个需要附加到电子邮件的 zip 文件夹。附加 zip 文件夹不起作用。
我在下面包含了三个一起工作的文件:
SEND 文件是 ajax 将文件发送到的位置。然后是一个fileUpload.php文件,它上传单个文件并$filename
为所有上传的文件生成变量数组。这是创建 zip 文件夹的地方,也是我尝试将其附加到$message
.
COMMUNICATION CLASS 用于发送电子邮件。最初,zip 文件夹是在此处创建/附加的。出于某种原因,我无法弄清楚如何让这两个文件一起工作,除了它已经做了什么。
TEMPLATE 文件是包含电子邮件 html 和 css 的位置。{变量}也是如此。这是文件名和消息变量所在的位置。不过,文件名应该是所有必需的。
正在创建 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);
然后是交流课。最初,邮政编码在这里(现在仍然是)。我不知道如何让这两个文件按应有的方式一起工作。
沟通类
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);
}
}
然后是模板,这是一封发送文件链接或附件的电子邮件(尽管附件不发送):
模板
<tr>
<td> {filename} </td>
</tr>
<tr>
<td><i>{message}</i></td>
</tr>
解决方案
推荐阅读
- php - localhost/magento 访问错误(找不到对象)
- php - 通过特定 ID 在列中获取 4 个产品
- python - Tweepy Cursor 从用户名中包含特定字符串的用户那里获取推文
- java - spring boot REST POST方法不起作用
- javascript - 已选择时禁用选择选项
- reactjs - 在地图 React 中发送 socket.emit() 时,socket.on 状态没有改变
- excel - 如何从excel中的单元格中提取图案
- jss - 功能悬停+功能正常的jss问题
- calculated-columns - 当“列”不在视野或隐藏时,Ag-grid valueGetter 不会触发
- r - 在 R 中执行 FOR 循环时如何避免多个条目