Last.fm Info with PHP


Update for 15 June 2006: Frederik M.J. Vestre has reworked my code to be able to use the XML feeds from last.fm. Kudos to him! If you want to give it a try, check out his Audioscrobbler XML data mining page. (as noted below, this page has changed location to the currently-linked folk.ntnu.no domain — 08 August 2007)

Update for 29 October 2005: I’ve modified things to no longer use cURL, so this should work for a wider range of users. I’ve also added the ability to display any of audioscrobbler’s text-based lists, including top albums and top artists. You can also put text before and after each list entry, which will allow you to turn these lists into proper HTML lists. Comments are welcome below. :)

If you have a last.fm account, you can use this PHP code to display your most recently-played songs on any webpage. Just download the last.fm info PHP file, rename it to “lastfm_info.php” (without the quotes), and stick it in the directory on your webserver that has the file you want your songs displayed on. WordPress users, put it in the same directory as your wp-config.php file.

Once you’ve got that done, add the following line to the file that you want your songs displayed in:
<?php include('lastfm_info.php'); ?>

Then, in that same file, put the following line where you want your songs displayed:
<?php display_lastfm_info( username, number_of_items, list, prefix, suffix, stats ); ?>

The only mandatory argument is your username. The other arguments are:

  1. number_of_items – the number of items you wish to be displayed, up to a maximum of ten. If you do not define this, then five items will be displayed.
  2. list – which list of items to display. This can be “topartists” (displays your Top Artists list), “topalbums” (displays your Top Albums list), “toptracks” (displays your Top Tracks list), “tags” (displays the tags you use most often to tag songs), “friends” (displays your friends), “neighbours” (displays your neighbours), or “recenttracks” (displays the tracks you recently listened to). If you do not define this, then your recent tracks will be displayed. This argument is case-insensitive.
  3. prefix & suffix – strings to display before and after each item. This can be used to present your list as an HTML list by setting prefix to <li> and suffix to </li>. If these are not defined, then nothing will be pre- or appended.
  4. stats – whether or not to display stats along with each item, where applicable. This applies to the “topartists”, “topalbums”, “toptracks”, and “tags”, by appending the number of each item after the item, in parentheses. For the “neighbours” list, it appends the percentage of commonality that you share with that neighbour. For example, if I have listened to Underworld 183 times, then with “stats” set to 1, this function will print “Underworld (183)”. If you wish stats to be displayed, set this to 1. If you do not define anything, then no stats will be displayed.

So, for basic functionality, if you just want to display your five most-recently played songs, you would call the function as:
display_lastfm_info( ’CanSpice’ );

If you want to display your ten most-listened to artists in an HTML list, with the number of listens after each artist, you would call the function as:
display_lastfm_info( ’CanSpice’, 10, ’topartists’, ’<li>’, ’</li>’, 1 );

Notes:

  1. The directory containing this code must be writable by the user under which the webserver runs. For example, on UNIX-based computers, this is typically the nobody user. You could set the directory to be owned by the nobody group, then set group write privileges by doing chmod g+w <dir> in a shell or over FTP. If you have difficulties doing this, please contact your hosting provider.
  2. This code caches the results from last.fm in order to comply with their requirements that the webservices not be accessed more than once every second for a given user. It downloads the results to a local file, and only requests an update from last.fm if that file is more than 30 seconds old.
  3. This code uses the plaintext file made available on audioscrobbler. Future plans include using the XML file for better artist and track name differentiation, along with linking back to last.fm automatically.
  4. The single quotes surrounding the various parameters are right single quotes, which are generated by (on standard North American English keyboards) the key just to the right of the Enter key. They’re not backticks.

This software is licensed under the GNU GPL, and is Copyright © 2005 Brad Cavanagh. All Rights Reserved.

  1. #1 by duran on 05 October 2005 - 7:50 am

    slick shit, I’ve wanted something like this for a while now. I’ll try to get it working.

  2. #2 by brad on 05 October 2005 - 9:03 am

    Awesome. Let me know how it goes. If you can get it running, then anybody can. =P

  3. #3 by duran on 05 October 2005 - 9:17 am

    zing

  4. #4 by Paul on 05 October 2005 - 10:28 am

  5. #5 by brad on 05 October 2005 - 11:08 am

    Whoops. Fixed. Thanks for pointing that out.

  6. #6 by Paul on 07 October 2005 - 3:04 am

    No problem. Fancy doing something like this for the other plain text files such as top 50 artists? ;)

  7. #7 by brad on 07 October 2005 - 8:31 am

    It would be pretty trivial to do that, yeah. Lemme come up with something that’ll use the same file for every text file last.fm makes available. :)

  8. #8 by WiRED on 07 October 2005 - 4:05 pm

    hi,

    i get the following message:
    Fatal error: Call to undefined function: display_scrobble_txt() in /home/rustedco/public_html/index.php on line 119

    Line 119 refers to the command line:

    i’ve replaced my username and number of songs. Any suggestions?

  9. #9 by duran on 09 October 2005 - 8:01 am

    fyi, it took me an embarassing extra 2 seconds to realize then it should have, but copy&pasting from your blog and the curly quotes around things didn’t go over well with my installation of PHP. just a ponter to those who are wondering.

  10. #10 by duran on 09 October 2005 - 8:24 am

    Alright, where is this function supposed to be coming from? –> “curl_init( $url );”

    I’m not intimate with wordpress, so did I miss something?

    thanks.

  11. #11 by duran on 09 October 2005 - 8:28 am

    erm, ok… somethings wrong with zend on my server… ignore my petty questions

  12. #12 by brad on 09 October 2005 - 9:01 pm

    WiRED: Did you put the line<?php include (’asnp_txt.php’); ?> at or near the top of your index.php file? From what it looks like, you’ve missed that line.

    Duran: You’ll need PHP compiled with CURL for downloading functionality. There’s a bunch of information here. I realize that this might put you (and others) dead in the water, so I’ll try to replace the code that downloads your recently-played list with something more generic.

  13. #13 by duran on 10 October 2005 - 5:13 pm

    You’re the man.
    thanks for looking in to the XML version.

  14. #14 by Stephane on 13 October 2005 - 8:23 am

    It’s working great for me. I hope you implement some more functions. It would be nice to set before/after parameters in order to generate a list for example.

  15. #15 by Cosine on 24 October 2005 - 8:40 am

    Hmmm… I did what you said but absolutely nothing happens… am i missing something?

  16. #16 by parrymason on 27 October 2005 - 3:49 am

    Doesn`t work for me.
    Why?

  17. #17 by brad on 27 October 2005 - 8:55 am

    Cosine: If you load your page’s source from your browser, is there any HTML code or text in the source where the output from the plugin should be?

    parrymason: Sorry, but I’m going to need more information than that. :) Does it display any error messages?

    All: I’m trying to find some time to improve the code, along with adding more functionality (like being able to pick any of last.fm’s feeds for display, or Stephane’s suggestion for easier integration with HTML lists). Hopefully I’ll be able to get to it Friday night. I’ve been working on a site redesign that’s chewing up my free time… :)

  18. #18 by Mark Traphagen on 02 November 2005 - 4:20 pm

    I have a WordPress blog.

    You said to put the lastfm_info.php file in the directory of the webserver where the file I want to display on is located. I put it in the theme folder for the theme I’m using, since that’s where the pages are. I put the include statement at the beginning of the index file and the display statement in my sidebar file. I get the following message at the top of my main page:

    Warning: main(’lastfm_infophp’): failed to open stream: No such file or directory in /home/rmfoblog/public_html/rumorsage/wp-content/themes/rumorsagev7/index.php on line 5

    Warning: main(): Failed opening ‘’lastfm_infophp’’ for inclusion (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/rmfoblog/public_html/rumorsage/wp-content/themes/rumorsagev7/index.php on line 5

    And this message at the top of the sidebar:

    Parse error: parse error, unexpected ‘

  19. #19 by brad on 02 November 2005 - 4:30 pm

    Er, good point on the WP case. Put it in your base WordPress directory, not your themes directory. It should go in the same directory as your wp-config.php file, if that helps narrow things down.

  20. #20 by Mark Traphagen on 02 November 2005 - 4:39 pm

    OK, did that. That eliminated the error message at the top of the main page. Now I get

    Parse error: parse error, unexpected ‘

  21. #21 by brad on 02 November 2005 - 4:50 pm

    By any chance did you copy and paste from here? It looks like WordPress does crazy things with quotation marks, translating single quotes into smart quotes. All of the quote marks are single quotes generated by (on standard North American keyboards) they key to the right of the Enter key.

  22. #22 by Mark Traphagen on 02 November 2005 - 6:09 pm

    OK, resolved the quotes problem. (BTW, it isn’t clear in your directions above that single quotes need to be around each of the parameters in the display statement.)

    Now I get this error where the songs should be displaying:

    Warning: fopen(as_recenttracks.txt): failed to open stream: Permission denied in /home/rmfoblog/public_html/rumorsage/lastfm_info.php on line 86
    Unable to open cache file for writing

  23. #23 by brad on 03 November 2005 - 11:58 am

    Mark: Make sure that the user that your web server runs under has write permissions to that directory. To do this, you’d want to set your rumorsage/ directory to be (as bad as this sounds) world-writable. This can be done through a shell (by going ‘chmod +w rumorsage’ when you’re in your public_html directory) or through FTP (I believe the command depends on your FTP client, but ‘chmod +w rumorsage’ could work). If this all seems like gibberish, I’d suggest asking your hosting provider how you’d go about changing this directory to world-writable. :-)

  24. #24 by Geof F. Morris on 03 November 2005 - 7:08 pm

    Yeah, well, his hosting provider sucks … which you should know from experience, Brad, as you use the same clown. ;)

    Anyhow, I created an empty as_recenttracks.txt in /home/rmfoblog/public_html/rumorsage/, chmod’d it 777, and … maybe it’ll work now.

    Your move, Mark. ;)

  25. #25 by brad on 03 November 2005 - 8:32 pm

    I was going to say something like “go ask that Geof character to get his act together” but thought that’d be rude. :)

  26. #26 by Geof F. Morris on 04 November 2005 - 6:14 am

    Awwwwww. You’re just being nice to me because you know that the Bruins’ crappy play is leaving me cranky. ;)

  27. #27 by Tony on 21 November 2005 - 9:21 pm

    Unable to open cache file for writingUnable to open audioscrobbler cachefile as_recenttracks.txt for reading

    ?

  28. #28 by Brad on 22 November 2005 - 8:59 am

    Tony: Have you set up your directory to be world-writable as I described above?

  29. #29 by JW on 26 November 2005 - 7:46 pm

    I’m with Cosine, absolutely nothing is happening on my site when I put in your code.

    As to your reply to Cosine, what exactly do you mean by source?

    I should mention this is my first experience with PHP. But I have write permission to the directory, I uploaded the php file, I put both bits of code (with the unsmart single quotes) into my page, but nothing’s happening.

  30. #30 by Brad on 27 November 2005 - 9:24 am

    JW: It depends on which browser you use, but generally if you right-click on your browser when you have your site loaded, you should get an option to “View Source”. This allows you to view the raw HTML from the server. If you go to the part of the source that should have the song listing in it and it’s not there, then something’s wrong. If you see the PHP code in that source code, then I think it’s the case that your web server doesn’t support PHP. Oh, it might also be the case that your webpage doesn’t end in .php, it ends in something else (like .html or .htm). If you end the webpage name in .php (like on this page, there’s the “index.php” thing) that tells the webserver to put it through PHP before sending it to the person requesting the page, which will cause the PHP last.fm code to be executed.

    If you want, you can email me the page that you actually edited and uploaded to your server to make sure all the bits are in the right place. My email address is brad.cavanagh@gmail.com.

  31. #31 by JW on 27 November 2005 - 4:49 pm

    Oh, view source. Duh.

    I didn’t rename the file to .php, but my server guy also had to change something to be writeable. Working now, thanks for the help.

  32. #32 by thomas on 06 December 2005 - 11:10 am

    hey. thanks for this great script. got it working after some checking in this guestbook. works great!

  33. #33 by Brad on 06 December 2005 - 2:01 pm

    thomas: You’re very welcome!

  34. #34 by Berit on 08 December 2005 - 1:05 am

    Found a workaround for everyone out there who gets “fopen(): URL file-access is disabled in the server configuration” and such. I use a simple 644 for my php file, and that’s about it. Works just like the original script, only without accessing the audioscrobbler data feed directly. Or something; I don’t know too much php, to be honest, I just know if it’s working or not..

    http://www.stud.ntnu.no/~beritrep/lastfm_info_mod.php.txt

  35. #35 by Emiliano on 10 December 2005 - 11:30 am

    I did exactly what you said and keep getting this:

    Warning: main(lastfm_infophp) [function.main]: failed to open stream: No such file or directory in /www/thecolorifix.com/web/listening.htm on line 1

    Warning: main() [function.include]: Failed opening ‘lastfm_infophp’ for inclusion (include_path=’.:/usr/local/share/pear:/www/thecolorifix.com/php’) in /www/thecolorifix.com/web/listening.htm on line 1

    Fatal error: Call to undefined function display_lastfm_info() in /www/thecolorifix.com/web/listening.htm on line 9

  36. #36 by TommeN on 28 December 2005 - 1:23 am

    Hello, why do i get this message when i try it on my wordpress homepage:

    Warning: fopen(as_recenttracks.txt): failed to open stream: Permission denied in /home/tommen/public_html/tommen/lastfm/lastfm_info.php on line 86
    Unable to open cache file for writing
    Warning: fopen(as_recenttracks.txt): failed to open stream: No such file or directory in /home/tommen/public_html/tommen/lastfm/lastfm_info.php on line 112
    Unable to open audioscrobbler cachefile as_recenttracks.txt for reading

    br
    TommeN

  37. #37 by Cory on 30 December 2005 - 3:52 am

    I fixed the “fopen(): URL file-access is disabled in the server configuration” on my gentoo server by enabling “allow_url_open” in the php configuration.
    Locate php.ini, on gentoo it is “fopen(): URL file-access is disabled in the server configuration”
    In that file locate the line “allow_url_fopen = Off” and change it to “On”

  38. #38 by marijn on 01 January 2006 - 11:21 pm

    hey there
    tnx for this great script!

    it occured to me that, when the last.fm sever is down, the script displays an error. i fixed something so a “last.fm server not reachable message is displayed.

    i replaced line 84 with:

    if (!($fp = @fopen( $url, "r" ))) {
    return false;
    }

    and then i call the script with

    ", "")) === false){
    print "last.fm info currently not available.";
    }
    ?>

    just a hint :-)

  39. #39 by jason on 04 January 2006 - 6:37 am

    any way to make this work without using fopen? My web host (Dreamhost) has disabled fopen use by its customers. I’d LOVE to use this script but alas I can’t because of that.

  40. #40 by Dan on 12 January 2006 - 8:50 pm

    where in the file, do you put this:

  41. #41 by stashuk on 31 January 2006 - 6:52 am

    Great plugin, its the best I have found this far to display my top 10 artists on my wordpress blog. I saw on the last.fm forum you were teasing about v2.0. Any chance we’ll see that soon with XML for the artists? Can’t wait till they link back to last.fm.

  42. #42 by Brad on 01 February 2006 - 9:18 am

    Hi stashuk! Thanks for the comment. I haven’t put any recent thought into properly parsing the XML yet, but that may come with time.

  43. #43 by ady on 04 February 2006 - 9:57 am

    Hi Brad. Currently I have the php file in my root folder so the “recent tracks” appear on my main homepage. How do I also display “recent tracks” on my other web pages? As it is curently, for an individual post/category archives/monthly archives, I get the following error…

    Fatal error: Call to undefined function: display_lastfm_info() in http://www.mediasushi.com/inc/recent_tracks.inc on line 7

  44. #44 by Brad on 04 February 2006 - 10:34 am

    Hi ady,

    To do this you’ll have to give the full directory path to your php file. You probably have a line that reads “include(‘lastfm_info.php’);” in your file that displays your main homepage. What you’ll need to do is figure out what directory it’s in (if it’s not at all apparent to you, ask your webhost) and prepend that to the “last_fm_info.php” in the “include” line.

    Or, if that “include” line is always going to be called from your /inc/recent_tracks.inc file, copy the lastfm_info.php file into your inc/ directory.

    Or you could even change the “include” line in your recent_tracks.inc file to read “include(‘../lastfm_info.php’);”. What this will do is cause it to look one directory up, which is your root folder.

    I’d suggest trying the second option first, then the third, then the first. :)

  45. #45 by ady on 05 February 2006 - 4:44 am

    Hi Brad… thanks. I tried both methods one and two but they both didn’t work. The third option worked for me. So… thank you very much. :-)

  46. #46 by 3stripe on 05 February 2006 - 1:28 pm

    Spent ages looking for a decent lastfm plugin and this one is the best one by far… but…

    I can’t get it to work yet in my WP2.01 install. I’ve added the snippet into my sidebar, put the pp file in my root directory, and chmodded it to 777, but still getting:

    Fatal error: Call to undefined function: display_lastfm_info() in /home/blahblahblahblah/blahblah/3stripe.net/wp-content/themes/3stripe/sidebar.php on line 48

    Can anyone help?

  47. #47 by 3stripe on 05 February 2006 - 1:30 pm

    Sorry my bad, now I’m onto the “URL file-access is disabled” error message. Hopefully will get this sorted tho :-)

  48. #48 by 3stripe on 05 February 2006 - 1:44 pm

    %^&*ing Dreamhost!

    Apparantly I need to use CURL instead (http://wiki.dreamhost.com/index.php/CURL)… can anyone advise on this?

    Cheers!

  49. #49 by Brad on 05 February 2006 - 5:25 pm

    3stripe: I’ll try to come up with a CURL version for you tomorrow. I had one before, but removed that functionality because it appeared that hosts that allow behaviour were more common. Clearly I need to have both available. :-)

  50. #50 by hypotheken on 07 February 2006 - 7:30 pm

    Hi, I think you are totally right. Great! – :) Susan.

(will not be published)