Creating a Secure WordPress User-based File Upload System (using ACF)

I am working on implementing a user-based file upload system in WordPress, and I want to ensure that the process is secure for users. Currently, I am using Advanced Custom Fields (ACF) to handle file uploads. When a user uploads a file, I aim to create a custom folder structure with their user_nicename and user_id to organize the files efficiently.

My idea is to create a folder for each user and then check if the folder matches the current user. If it does, the user should be able to see their uploaded files; otherwise, access should be restricted. How can I implement this check effectively and is this safe?

(I use woocommerce for creating accounts.)

What I am trying to do:

  • Upload a file to a custom directory with the user name
  • make the directory only accesible for admins and the loggedin user.

The code that currently handles the uploading of the files.

add_filter('acf/upload_prefilter/key=field_65a6a42f132d2', 'prefilter_avatar_upload');

                        function prefilter_avatar_upload($errors) {
                            add_filter('wp_handle_upload_prefilter', 'avatar_upload_rename');
                            add_filter('upload_dir', 'modify_avatar_upload_dir');
                            return $errors;
                        }
    
                        // Function to modify the upload directory
                        function modify_avatar_upload_dir($uploads_avatars) {
                            $user_id = get_current_user_id();
                            $user_info = get_userdata($user_id);
                            $username = $user_info->user_nicename;
    
                            $uploads_avatars['path'] = $uploads_avatars['basedir'] . '/useruploads/' . $username . $user_id;
                            $uploads_avatars['url']  = $uploads_avatars['baseurl'] . '/useruploads/' . $username . $user_id;
    
                            return $uploads_avatars;
                        }
    
                        function avatar_upload_rename($file) {
                            return $file;
                        }
    
    
    
    
    
    
                    acf_form_head();
                    $options = array(
                        'post_id' => 'user_'.$current_user->ID,
                        'field_groups' => array('group_65a656c14a386'),
                        'form' => true, 
                        'return' => add_query_arg( 'updated', 'true', get_permalink() ), 
                        'html_before_fields' => '',
                        'html_after_fields' => '',
                        'submit_value' => 'Update' 
                    );
                    acf_form( $options );`

I appreciate any guidance or code examples that can help me achieve a secure and user-friendly file upload system in WordPress. Thank you!