It’s not a good idea to store user’s data on a file that is publicly accessible. A better way would be to create a folder, and store your file under it. Also, it’s better to use WordPress’s filesytem class rather than directly using PHP’s built-in functions. Here’s a quick fix:
function wpse381320_after_login( $atts ) {
if ( is_user_logged_in() && WP_Filesystem() ) {
global $wp_filesystem;
// Set a path for your folder
$wp_uploads = wp_get_upload_dir();
$content_dir = trailingslashit( $wp_uploads[ 'basedir' ] ) . 'my-folder';
$text_file = trailingslashit( $content_dir ) . 'usernames.txt';
$htaccess_file = trailingslashit( $content_dir ) . '.htaccess';
// Get the current user
$current_user = wp_get_current_user();
// Create an empty directory
if ( ! $wp_filesystem->is_dir( $content_dir ) ) {
$wp_filesystem->mkdir( $content_dir, 0755 );
}
// Create the htaccess file
if ( ! $wp_filesystem->is_file( $htaccess_file ) ) {
$htaccess = $wp_filesystem->put_contents( $htaccess_file, 'deny from all', 0755 );
}
// Create the text file
if ( ! $wp_filesystem->is_file( $text_file ) ) {
$usernames = $wp_filesystem->put_contents( $text_file, '', 0755 );
}
// Add username to the file
$usernames = $wp_filesystem->put_contents( $text_file, $current_user->display_name, 0755 );
}
}
add_shortcode( 'shortcode_login', 'wpse381320_after_login' );
Please notice this is a demonstration and should not be copy-pasted. Accessing filesystem on every page load might slow your website down. You might want to divide this code into 2 different pieces to improve performance.
Also remember to always check if there’s any error while working with the filesystem, e.g. check the result of $wp_filesystem->put_content()
and so.