Every new starter at Twilio has to build an application using one of our products, then demo it to receive their fabled Track Jacket. For my application, because WiFi is always a pain at conferences, I wrote a PHP script that sends you the next talks for a given event.

Writing this so it worked locally was relatively straightforward with PHP’s inbuilt web server and ngrok, but when I got up to demo this in front of my peers, I didn’t want to be relying on my laptop to be open, awake and responding to the proxied HTTP requests. This code needs to be sitting somewhere on the internet so that it can respond to messages any time of the day or night, and not just when my laptop was open and connected to the wifi.

Serverless functions are great for this; they allow you to run code on someone else’s computers without having to deploy any infrastructure. Publishing your code can be as simple as running a CLI command, and you only pay for what you use with a generous free tier. Lambda is AWS’s offering in the serverless function space, but sadly it doesn’t support PHP out of the box.

So how can we run PHP applications on AWS Lambda?

Tooling

The Bref PHP open source project makes it relatively painless to deploy our PHP code as a Lambda serverless function. In late 2018, Amazon opened the door to custom runtimes and layers for Lambdas, and Bref takes advantage of this to allow PHP projects to be seamlessly deployed to Lambda. Currently, it uses the AWS SAM CLI library to do this, but integrations with the popular Serverless Framework are coming soon.

Let’s assume we've configured a phone number in the Twilio console to respond to a webhook that we are proxying to our local development environment using ngrok. Our webhook will use the Twilio PHP library to generate some dynamic TwiML that lets us know what time and date an appointment is.