How to Setup a PHP-based AWS Lambda function

Nwosu Onyedikachi
2 min readMay 5, 2022

In this post, I am going to create an AWS lambda function that runs on a PHP runtime. The process is simplified using Bref. Bref is an open-source project that brings full support for PHP and its frameworks to AWS Lambda.

Prerequisites: Install composer locally, and generate your AWS access keys.

The steps are:

  1. Install and configure the Serverless Framework
npm i -g serverlessserverless config credentials — provider aws — key <key> — secret <secret>

2. Composer install Bref

mdkir serverless-php-lambdacd serverless-php-lambda
composer require bref/bref

3. Initialize the Bref project

vendor/bin/bref initSelect Event-driven function belowWhat kind of lambda do you want to create? (you will be able to add more functions later by editing `serverless.yml`) [Web application]:
[0] Web application
[1] Event-driven function

A serverless.yml file is created at this point as shown below.

The serverless yml above indicates that I am deploying a lambda function named php-lambda running on PHP 7.3 to an Amazon Linux 2 machine(provided.al2) on AWS Lambda.

Note that Lambda function name, PHP versions and AWS region can be updated before deployment. For more supported PHP versions, visit bref-runtimes for details.

Also, an index.php was created on initialization. Modify the index.php file to handle your specific use case.

4. Deploy To AWS and Test

serverless deploy

The image below shows the sample PHP code running in AWS Lambda.

5. Add PHP Extensions(Optional)

For this example we will add the Imagick PHP extension in the following sub-steps;

RUN composer require bref/extra-php-extensionsUPDATE plugins in serverless.yml file and add — ./vendor/bref/extra-php-extensionsUPDATE layers in serverless.yml file and add ${bref-extra:imagick-php-73}save and redeploy and retest

The new serverless.yml is as shown below.

Bref supports other PHP extensions. Check here for more details.

Congratulations on having gotten thus far. If you have followed through on the steps, you should have an AWS lambda function that runs on a PHP runtime.

Thank you for reading! If you found this helpful, I would love some constructive feedback in the comments section.

--

--