The default image is used as a profile picture when a user signs up on the website. This default image is displayed as a profile picture until the user changes their profile picture. Generally, the same image is used as a default profile picture for all users. If you want to separate the default image for each user, it needs to be changed dynamically.
In this code snippet, we will show you how to create a default profile image dynamically from the first and last names in PHP. Since the first letter of first and last name is used in the image, the profile picture will be different for each user and relevant to their name.
Get first letters from first and last name using PHP:
First, we need to split the full name into first name and last name and generate short characters from the user’s name.
<?php
// Full name of the user
$user_full_name = 'Demo User';
$full_name_arr = explode(" ", $user_full_name);
$full_name_arr_end = end($full_name_arr);
$firstWord = !empty($full_name_arr[0])?$full_name_arr[0]:'';
$lastWord = !empty($full_name_arr_end[0])?$full_name_arr_end[0]:'';
$charF = !empty(mb_substr($firstWord, 0, 1))?mb_substr($firstWord, 0, 1):'';
$charL = !empty(mb_substr($lastWord, 0, 1))?mb_substr($lastWord, 0, 1):'';
$shortChar = $charF.$charL;
?>
Create an HTML element with the first letters of first and last name:
Print short characters of the default image in HTML.
<div class="profile-image">
<?php echo trim($shortChar); ?>
</div>
Define CSS to display default profile image:
Apply CSS to the selector of the HTML element (profile-image
) to make it look like an image.
.profile-image {
width: 120px;
height: 120px;
border-radius: 50%;
background: #512DA8;
font-size: 35px;
color: #fff;
text-align: center;
line-height: 120px;
margin: 20px 0;
}