我正在尝试创建一个功能,用户选择 acf 图像,创建一个 zip 文件,然后将其发送到电子邮件,但我的代码不会创建 zip 文件。我尝试检查 zip->close() ,这返回一个错误值。我也在不使用ajax的情况下尝试过,它有效!不知道为什么它作为函数使用时不起作用。请检查下面的代码。
$ret = array(
'is_error' => false,
'msg' => array(),
);
if (empty($_POST['email'])) {
$ret['is_error'] = true;
$ret['msg'][] = 'Email address is a required field';
}
if ($ret['is_error'] == false) {
unset($_POST['action']);
$images = $_POST['files'];
if( $images ){
$destination = 'wp-content/uploads/downloads/' .time() . '.zip';
if ( file_exists( $destination ) ){
$ret['msg'][] = 'zip file exists';
}
else {
// If the file doesn't already exist, create the file
$files = array();
foreach( $images as $singlefile ) {
// create an array of the image files in the gallery
$files[] = get_attached_file( $singlefile );
}
if( count( $files ) ) {
//Create a zip file in the location specified
$zip = new ZipArchive();
$zip->open( $destination, ZipArchive::CREATE );
foreach( $files as $file ) {
if ( file_exists($file) ) {
// if the file actually exists, add it to the zip file
$new_filename = substr($file,strrpos($file,'/') + 1);
$zip->addFile( $file, $new_filename );
}else{
$ret['msg'][] = $file;
$ret['msg'][] = 'Not added';
}
}
$zip->close();
readfile($destination);
$ret['msg'][] = $zip->close();
if(file_exists($destination)){
ob_clean();
ob_end_flush();
$protocols = array('https://', 'http://', 'https://www.', 'http://www.', 'www.');
$siteURL = str_replace($protocols, '', get_bloginfo('wpurl'));
$headers = 'From: '.get_bloginfo('name').' <noreply@'.$siteURL.'>';
$to = $_POST['email'];
$subject = "test";
$body = "test";
$attachments = array( $destination );
wp_mail($to, $subject, $body, $headers, $attachments );
unlink($destination);
$ret['msg'][] = 'Files sent. Please check your email';
}else{
$ret['msg'][] = 'Files does not exist';
}
} else {
// No images are found
$ret['msg'][] = 'No files found';
}
}
}
}
echo json_encode($ret);
exit();
尝试使用此代码 -
# create new zip object
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
# loop through each file
foreach ($FILES_ARRAY as $file) {
# download file
$download_file = file_get_contents($file);
#add it to the zip
$zip->addFromString(basename($file), $download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename=image-pack-' . $post_id . '.zip');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);