Spotify Embeddables

Last year, I faced an unexpected challenge when exploring a forum that allowed customizable pages. It allowed HTML/CSS but absolutely no scripting. This was mostly done to prevent Cross-Site Scripting (XSS) attacks where users could inject potentially malicious code. I wanted to personalize my page by displaying the current track I’m listening to on Spotify; I tried showing it through an iFrame, but the site didn’t allow that. Also, since I couldn’t use JS or jQuery to display the live track info, I decided to look for alternative ways to go about doing this. I learned that the site only allowed embedding images within HTML tags. But if we go through the documentation of browsers such as Firefox and Chrome, we see they allow images of the “.php” extension. This was an exciting discovery for me, and I set out to look at what this meant.

(Current Implementation is down, will upload soon!)

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