Last.fm Info with PHP
- Tue Oct 4 2005
- digg this page
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:
- 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.
- 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.
- 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.
- 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:
- 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.
- 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.
- 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.
- 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.

87 Responses to “Last.fm Info with PHP”
Wed Oct 5 2005
7:50 am
slick shit, I’ve wanted something like this for a while now. I’ll try to get it working.
Wed Oct 5 2005
9:03 am
Awesome. Let me know how it goes. If you can get it running, then anybody can. =P
Wed Oct 5 2005
9:17 am
zing
Wed Oct 5 2005
10:28 am
Your link:
http://www.canspice.org/index.php/lastfm-recently-played-php-code/asnp_txt.php.txt
Doesn’t seem to work.
Wed Oct 5 2005
11:08 am
Whoops. Fixed. Thanks for pointing that out.
Fri Oct 7 2005
3:04 am
No problem. Fancy doing something like this for the other plain text files such as top 50 artists? ;)
Fri Oct 7 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. :)
Fri Oct 7 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?
Sun Oct 9 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.
Sun Oct 9 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.
Sun Oct 9 2005
8:28 am
erm, ok… somethings wrong with zend on my server… ignore my petty questions
Sun Oct 9 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.
Mon Oct 10 2005
5:13 pm
You’re the man.
thanks for looking in to the XML version.
Thu Oct 13 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.
Mon Oct 24 2005
8:40 am
Hmmm… I did what you said but absolutely nothing happens… am i missing something?
Thu Oct 27 2005
3:49 am
Doesn`t work for me.
Why?
Thu Oct 27 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… :)
Wed Nov 2 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 ‘
Wed Nov 2 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.
Wed Nov 2 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 ‘
Wed Nov 2 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.
Wed Nov 2 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
Thu Nov 3 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. :-)
Thu Nov 3 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. ;)
Thu Nov 3 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. :)
Fri Nov 4 2005
6:14 am
Awwwwww. You’re just being nice to me because you know that the Bruins’ crappy play is leaving me cranky. ;)
Mon Nov 21 2005
9:21 pm
Unable to open cache file for writingUnable to open audioscrobbler cachefile as_recenttracks.txt for reading
?
Tue Nov 22 2005
8:59 am
Tony: Have you set up your directory to be world-writable as I described above?
Sat Nov 26 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.
Sun Nov 27 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.
Sun Nov 27 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.
Tue Dec 6 2005
11:10 am
hey. thanks for this great script. got it working after some checking in this guestbook. works great!
Tue Dec 6 2005
2:01 pm
thomas: You’re very welcome!
Thu Dec 8 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
Sat Dec 10 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
Wed Dec 28 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
Fri Dec 30 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”
Sun Jan 1 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 :-)
Wed Jan 4 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.
Thu Jan 12 2006
8:50 pm
where in the file, do you put this:
Tue Jan 31 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.
Wed Feb 1 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.
Sat Feb 4 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
Sat Feb 4 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. :)
Sun Feb 5 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. :-)
Sun Feb 5 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?
Sun Feb 5 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 :-)
Sun Feb 5 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!
Sun Feb 5 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. :-)
Tue Feb 7 2006
7:30 pm
Hi, I think you are totally right. Great! - :) Susan.
Thu Feb 9 2006
4:49 am
Hi Brad,
Thanks for making this cool stuff available for everyone! It does take me some time tweaking here and there to make it work but it’s working now (thanks to Geof too for his input!). Awesome stuff, you guys rock! \m/
Wed Feb 15 2006
1:51 am
Hey, got it working on my own :-)
http://www.3stripe.net/
Thanks again for this.
Wed Feb 15 2006
11:54 am
Got it workin’ on ExpressionEngine with a little experimentation. I had to place a blank as_recenttracks.txt (replace with whatever list you’re trying to download)in the root folder of the domain (where path.php is) and change its permission to 666. Works like a charm. Thanks for the script.
Wed Feb 15 2006
7:07 pm
Hey there Vrad, nice code, is there anyway to edit the layout of this? Instead of it being linear?
Thu Feb 16 2006
9:55 am
Linear? I’m not sure what you mean.
You can change the tags that appear before and after each item in the list, if you want. You could surround them by div tags, for example, to put any kind of markup you want on them. This would be for the prefix and suffix options.
Fri Feb 17 2006
6:12 am
Thank you very much. It works now on : sassen.org
Fri Feb 17 2006
6:55 am
Is there a way to force the length of the string ?
Fri Feb 17 2006
2:07 pm
What do you mean by “length of the string”? Which string?
Sat Mar 11 2006
8:31 pm
Copied last_fm_info.php to my root folder.
Added in index.php
Added display_lastfm_info( ’username’, 10, ’topartists’, ’’, ’’, 1 );
Getting :
Warning: main(’lastfm_infophp’): failed to open stream: No such file or directory in /home/sleepwor/public_html/index.php on line 88
Warning: main(’lastfm_infophp’): failed to open stream: No such file or directory in /home/sleepwor/public_html/index.php on line 88
Warning: main(): Failed opening ‘’lastfm_infophp’’ for inclusion (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/sleepwor/public_html/index.php on line 88
Sat Mar 11 2006
11:38 pm
When I put the code into my sidebar.php file the entire sidebar disappears from my site.
Mon Mar 13 2006
1:55 pm
George: It looks like you’ve misspelled the “include” line. Make sure that the file you’re including is “lastfm_info.php”, not “lastfm_infophp”. Note the period between “info” and “php”.
Cosine2: It could be that you’ve forgotten to close your PHP tags. Make sure you’ve done so.
Wed Mar 15 2006
11:19 pm
CAN YOU USE THIS CODE ON MYSPACE ???
Thu Mar 16 2006
6:39 am
ANTONIOS: If MySpace runs PHP, then yes. Otherwise, no.
Fri Mar 17 2006
6:50 am
Hey there,
thanks for the neat script, i was getting tired of using predefined gif - images. I let it display my recent tracks. Is there a chance to have artists styled seperately? I want them bold, but just the singer, not the song.. :-)
Thu Apr 6 2006
6:52 pm
Here’s another question… how do I get the script to display unusual characters - like certain letters in foreign songs?
Thu Apr 20 2006
2:44 am
Ady: I’ve got the same problem, it won’t display the german Ü in Rammstein’s song “Küss mich”. But I think it has something to do with the encoding of your site. If you run iso-8859-1, try UTF-8 instead.
Sat Apr 29 2006
6:55 pm
Alec: I could have sworn that I coded up something that would let you get what you’ve requested, but I can’t find it! I think I must’ve written that code before I had a massive hard drive failure, and it got lost in a backup shuffle. Argh.
Fri May 5 2006
3:32 am
hello there,
could you give me some tips on getting this cool little script to display my weekly top artists as opposed to my overall top artists?
Fri May 5 2006
9:10 am
Matthew:
This code only supports the text-based feeds. Unfortunately last.fm does not supply the weekly top artists in a text-based feed, only an XML feed.
If last.fm were to supply the weekly top artists in a text-based feed, then this code would work. I suggest posting on last.fm’s forums, asking them to supply this feed.
Mon May 8 2006
1:14 am
ok thanks
Sat Jul 22 2006
10:05 pm
Brad.
Firstly great code, I wasn’t looking forward to having to write something like this by myself.
I was having a problem though, for some reason \n wasn’t creating a new line after each band name entry. I replaced it with a as I would in any normal html, and the problem was fixed.
The thing is I can’t seem to find and reason why it wasn’t doing this in the first place, and thought maybe you would like to know.
Once again, great code, thankyou.
Mon Oct 9 2006
6:48 am
Has anyone have an up-date of this script?As it no longer works ;(
Cheers
Chris
Mon Oct 9 2006
9:00 am
Chris: It still works, as you can see on my front page. If you tell me how it doesn’t work for you, including error messages, then I can help you get it working.
Sat Oct 21 2006
3:07 am
I’d love to add this to my website, but I’m wondering if making the directory world-writable is a security risk. Doesn’t this mean anyone can create and delete files there?
Thanks,
Simon
Sat Oct 21 2006
7:59 am
It is, yes. However, if you’re running a WordPress website, you’ve already done this to other directories in your webspace.
Fri Dec 15 2006
7:30 am
Great script! But on my page the artist and title is presented as: Firefox AK – City To City bu i woult like it to look like: Firefox AK - City To City. Is it possible?
Mon Dec 18 2006
9:45 am
Solved my problem above!
Mon Dec 25 2006
6:54 pm
Ok not sure if I will get any response anymore but I’ve been trying to find a cript to get my most recent tracks played listed on my site. But this is the only one that so far has given me anything back even if it is just errors. Anyway the errors are:
fopen(): URL file-access is disabled in the server configuration in /usr/home/admin/public_html/five/scripts/lastfm_info.php on line 84
fopen(http://ws.audioscrobbler.com/1.0/user/fivesevennine/recenttracks.txt): failed to open stream: no suitable wrapper could be found in /usr/home/admin/public_html/five/scripts/lastfm_info.php on line 84
I set the folders CHMOD to 777 (using an FTP program) is that enough or do I need to do something more?
Mon Dec 25 2006
7:10 pm
Nevermind I got it to work. Had to use the function that used the CURL lib instead.
Basically if you are getting this error, comment the fopen code block (put the code inbetween /* {CODE} */) and remove the other /* */ in the code.
Mon Dec 25 2006
8:08 pm
Ok wow 3 consecutive posts in less than an hour, sorry. But I have the same problem as Mikael did, where the – apears instead of the -. So how do you fix this?
I inserted:
$cache = str_replace( ‘–’, ‘-’, $cache );
into multiple places in the code and still no change, I also used $cachefile instead of $cache, but still not working. Thanks for any help, and sorry about the 3 posts =/.
Fri Jan 5 2007
8:18 am
Solved my problem by adding into my page, and after that it works fine.
Fri Jan 5 2007
8:18 am
meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″
Tue Feb 13 2007
7:59 pm
I’m in the same boat as a few people, my host doesn’t allow me access to fopen. I tried the comment about from Five but still no luck. Perhaps I’m commenting out the wrong part. If anyone can post the code for the full libcurl version that would be great. Thanks.
Thu Feb 22 2007
12:26 pm
i’ve fudged with this for a while now and all i get is a blank page. if i view source i see the html code. i’ve tried making the page i load a .hml file and a .php file. i’ve messed with permissions on my server even granting everyone r/w/x just to see if it worked… it didn’t.
test
‘ ); ?>
any ideas? thanks!
would love to get this working
Thu Feb 22 2007
12:27 pm
[CODE]
test
[/CODE]
Thu Feb 22 2007
12:28 pm
trying to get my html to show up. sorry. you can delete that last post… and this one. :)
Wed Aug 8 2007
1:01 am
XML version moved to http://folk.ntnu.no/frederv/asxmldm/
Leave a Reply