Spotify Embeddables

Last year, I stumbled into this super cool forum where I could customize my own pages. It let me use HTML and CSS, but here’s the catch: no scripting allowed, at all.

They did this to stop Cross-Site Scripting (XSS) attacks, where people could sneak in some shady code. I really wanted to decorate my page by showing the current track I was listening to on Spotify. I thought about using an iFrame for that, but nope, the site totally blocked it.

Since I was stuck without JavaScript or jQuery to pull up the live track info, I started hunting for other ways to get it done. I found out the site only let me embed images with HTML tags. But then I dug into the documentation for browsers like Firefox and Chrome and discovered that they actually allow images with a “.php” extension. That was such a game changer and I was pumped to see where this little revelation would lead me.

(This implementation has been down for a while :( , I may revisit this project in the future, meanwhile you can check out the code here: SpotifyEmbed)

So PHP allows setting content-type when you create a new PHP file. One of these types happens to be images, i.e. if the script on execution gives an image as an output, it can be parsed as an image by the browser. This got me super excited as what I proposed was, after all, possible. I immediately got to work and implemented what would be the heart of this challenge, using my Spotify App token generated through the developer portal, and used to capture JSON data generated from each API call and filter out only the data that we will need, the track name and current playing status.

Once I got the required data, I could go ahead and build our ‘image’ part of the app. Since we will create a PHP image, we can’t put API call code into this file, as multiple operations, such as JSON data processing, are impossible on an image.

Hence, we proceed to create a session and reference it in our 2nd image PHP file. Using the PHP-GD images library, we can pull the filtered text from the 1st PHP doc and customize font, colour and spacing before embedding it onto an image of our choice.

We then add invoking of 1st PHP file on the load of the PHP image. This updates the track information that’s to be embedded on every page load.

We can further adopt this into a serverless solution using Google CloudFunctions or AWS Lambda.

And that’s how I created an image embeddable using purely PHP! Pretty cool, don’t you think? :)

Written on June 12, 2022