Zip a file and add as attachment

I first add support for mime type attachments

// ADD MIME TYPEs FOR ATTACHMENTS
add_filter( 'upload_mimes', 'my_myme_types', 1, 1 );
function my_myme_types( $mime_types ) {
  $mime_types['txt'] = 'text/plain';
  $mime_types['json'] = 'application/json';
  $mime_types['zip'] = 'application/zip';

  return $mime_types;
}

Now I have the way that I would add a json object to to a json file and then attach

$user_id = absint($_POST["uid"]);
$post_title = sanitize_text_field($_POST["post_title"]);
$post_object = get_page_by_title($post_title, OBJECT, 'chat');
$post_id = $post_object-ID;
$msg_array = $_POST["msg_data"];
$ext = ".json";
$path = "/wp/wp-content/uploads/";
$file = $user_id . $post_title . $ext;
$wp_upload_dir = wp_upload_dir();
echo $wp_upload_dir;
file_put_contents($wp_upload_dir['path'] .'/'. basename( $file ), $msg_array);
file_put_contents($file, $msg_array);
$attachment = array(
    'guid'= $wp_upload_dir['url'] .'/'. basename( $file ), 
    'post_mime_type' = 'application/json',
    'post_title' = $user_id . $post_title,
    'post_content' = $user_id . $post_title,
    'post_status' = 'inherit'
     );

$mid = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($mid) ){
    wp_update_attachment_metadata( $mid, wp_generate_attachment_metadata( $mid, $file ) );
}

But I want to save space and zip this json file and then add the zip as the attachment. How do I adapt this?

This being the method for zipping a file

$zip = new ZipArchive;
if ($zip-open('test_new.zip', ZipArchive::CREATE) === TRUE)
{
    // Add files to the zip file
    $zip-addFile('test.json');

    // All files are added, so close the zip file.
    $zip-close();
}

Topic ziparchive json attachments Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.