How to overwrite image if it already exists – WordPress, Gravity form

These lines of code and can help you to overwrite image


        $attachment_id = get_post_thumbnail_id($post_id);
        wp_delete_attachment($attachment_id, true);

        if(isset($file) && !empty($file) ){

            $upload_overrides = array('test_form'=> false);
            $movefile = wp_handle_upload($file, $upload_overrides);

            $filename = basename( $movefile['url'] );

            $wp_filetype = wp_check_filetype($filename, null );

            $attachment = array(
                'guid' => $wp_upload_dir['url'] . "https://wordpress.stackexchange.com/" . $filename,
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
                'post_content' => '',
                'post_status' => 'inherit',

            );

            $attach_id = wp_insert_attachment( $attachment, $movefile['url'], $post_id );
            $attach_data = wp_generate_attachment_metadata( $attach_id, $movefile['url'] );
            // wp_update_attachment_metadata( $attach_id, $attach_data );
            set_post_thumbnail( $post_id, $attach_id );

            $src = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), "single-post-thumbnail")[0];
            update_post_meta($post_id, '_thumbnail_id', $attach_id);

            
            update_post_meta($post_id, '_thumbnail_id', $attach_id);