Get URL for user profile image

Public

Three people in three days asked for this code on IRC and directly, so here it is :-p This code borrows heavily from the function template_preprocess_user_picture in the user.module file.

</> CopyGet raw version
php
  1. // Check to see if user pictures are enabled (admin/config/people/accounts,
  2. // make sure "Enable user pictures" is checked.
  3. if (variable_get('user_pictures', 0)) {
  4.  
  5. // Choose one of the following based on your use case, and remove the rest:
  6. // Load the currently logged in user
  7. $account = $GLOBALS['user'];
  8. // Load the user account by ID
  9. $account = user_load($uid);
  10. // Load the user account from the current user page
  11. $account = user_load(arg(1));
  12. // Load the user account by username
  13. $account = user_load_by_name($username);
  14.  
  15. if (!empty($account->picture)) {
  16. // Load user picture if only a file ID is passed, see TODO in
  17. // template_preprocess_user_picture for details
  18. if (is_numeric($account->picture)) {
  19. $account->picture = file_load($account->picture);
  20. }
  21. // Get filepath from the loaded file object
  22. if (!empty($account->picture->uri)) {
  23. $filepath = $account->picture->uri;
  24. }
  25. } elseif (variable_get('user_picture_default', '')) {
  26. // Use default user profile picture if the user hasn't provided one
  27. $filepath = variable_get('user_picture_default', '');
  28. }
  29. if (isset($filepath)) {
  30. $profile_url = file_create_url($filepath);
  31. }
  32. }
  33.  
  34. // Make sure an image has been loaded, and output the URL
  35. if (isset($profile_url)) {
  36. print $profile_url;
  37. }

Comments

varvashenia's picture

To improve performance move user_load() into if (variable_get('user_pictures', 0)) {}

Steve's picture

How would you go about printing the user profile image of the commenter and have it use the site-wide default user image if the commenter doesn't have a profile picture?

thirdender's picture

@Steve, the code already does that. Simply load the comment user into the $account variable using one of the lines in the code. The default user image will be loaded by the line:
$filepath = variable_get('user_picture_default', '');