Generate User Avatar using PHP Tutorial

In this tutorial, you will learn how to Generate User Avatars using their name's initials in PHP. The application aims to provide IT/CS Students and new programmer with a reference that help them to enhance their programming capabilities. Here, are simple snippets that generate user avatars. A sample source code zip file is also provided and is free to download.

How to Generate User Avatar using PHP?

To Generate User Avatars using the initials of their names, we can simply use the PHP substr() method which allows us to get the first character or letter of the user's first and last name. After getting the user initials we can create an element on how we want to display the avatar.

Snippets of Generating User Avatar using PHP

The below snippets will result in a simple web application that allows the user to enter their first name and last name. The user avatar will be generated upon the user clicking the generate button or submitting the form.

Interface

The below snippet is a combined PHP and HTML script that contains the elements and code for displaying the form and the design of the page. Save the file as index.php.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>UserAvatar Generator From Name - PHP</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <link rel="stylesheet" href="style.css">
  10.  
  11. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  12. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  13. </head>
  14. <body style="background:#e1ecf7">
  15. <nav class="navbar navbar-expand-lg navbar-dark" style="background:#1597BB">
  16. <div class="container">
  17. <a class="navbar-brand" href="./">UserAvatar Generator From Name - PHP</a>
  18. <div>
  19. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  20. </div>
  21. </div>
  22. </nav>
  23. <div class="container-fluid px-5 my-3 pt-5">
  24. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  25. <h3 class="text-center">Generate User Avatar usign the Users' Name Initials</h3>
  26. <hr>
  27. <div class="card rounded-0">
  28. <div class="card-header rounded-0">
  29. <div class="card-title">List of Files</div>
  30. </div>
  31. <div class="card-body rounded-0">
  32. <div class="container-fluid">
  33. <form action="" id="generate-form" method="POST">
  34. <div class="mb-3">
  35. <label for="firstName" class="form-label">Firtname</label>
  36. <input type="text" name="firstName" id="firstName" value="<?= isset($_POST['firstName']) ? $_POST['firstName'] : "" ?>" class="form-control form-control-sm rounded-0" required>
  37. </div>
  38. <div class="mb-3">
  39. <label for="lastName" class="form-label">Lastname</label>
  40. <input type="text" name="lastName" id="lastName" value="<?= isset($_POST['lastName']) ? $_POST['lastName'] : "" ?>" class="form-control form-control-sm rounded-0" required>
  41. </div>
  42. <?php
  43. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  44. include_once("userAvatargenerator.php");
  45. ?>
  46. <div class="d-flex w-100 justify-content-center">
  47. <div class="col-auto">
  48. <?= generateAvatarFromName($_POST['firstName'], $_POST['lastName']) ?>
  49. </div>
  50. </div>
  51. <div class="text-center"><?= ucwords($_POST['firstName'] . " " . $_POST['lastName']) ?></div>
  52. <?php
  53. }
  54. ?>
  55. </form>
  56. </div>
  57. </div>
  58. <div class="card-footer py-2 text-center">
  59. <button class="btn btn-primary rounded-pill col-lg-4 col-md-6 col-sm-12 col-xs-12" form="generate-form">Generate Avatar</button>
  60. </div>
  61. </div>
  62. </div>
  63. </div>
  64. </body>
  65. </html>

PHP Function

The below snippet is a PHP file containing the functions that are needed for generating the user avatar. Save the script as userAvatargenerator.php. The file will be included on the main page after the user submitted the form. It contains also the function of generating a random color for the avatar background.

  1. <?php
  2. /**
  3.   * Avatar Background Colors
  4.   */
  5.  
  6. $colors = ["#65647C", "#7F669D", "#FF8DC7", "#7895B2", "#898AA6", "#68A7AD", "#94B49F", "#8E806A"];
  7.  
  8.  
  9. function getAvatarBG(){
  10. global $colors;
  11. $colorsCount = count($colors);
  12. $key = mt_rand(0,7);
  13. return $colors[$key];
  14. }
  15.  
  16. function avatarStyles(){
  17. $styles = [
  18. "background: ".getAvatarBG(),
  19. "color: #fff",
  20. "height: 50px",
  21. "width: 50px",
  22. "border-radius: 100%",
  23. "display:flex",
  24. "justify-content: center",
  25. "align-items: center",
  26. "font-size: 15px",
  27. ];
  28. return implode(";", $styles);
  29. }
  30.  
  31. function generateAvatarFromName($firstName="", $lastName=""){
  32. if(empty($firstName)){
  33. return "Can't Generate Avatar! Firstname must be provided.";
  34. }
  35. $nameInitial = (substr($firstName, 0,1));
  36. if(!empty($lastName))
  37. $nameInitial .= (substr($lastName, 0,1));
  38. return '<div class="generated-user-avatar" style="'.avatarStyles().'">'.$nameInitial.'</div>';
  39. }

There you go! You can now try or test the source code on your end to see if it works and achieve the objectives of this tutorial. I provided also the source code zip file that I created for this tutorial and you can download it by clicking the download button located after this article.

Snapshot

Generate User Avatars in PHP

That's it! I hope this Generate User Avatar in PHP Tutorial will help you with what you are looking for and that you'll find this useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment