Web20 University

Using PHP On AWS Lambda

Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

TL;DR

You can run PHP on AWS lambda but it does require you to setup a custom runtime for the environment. We’ll take a look at how to get this up and running in this article.

Can PHP Be Used on AWS Lambda?

The short answer is yes! While AWS Lambda doesn’t natively support PHP, there are ways to run PHP applications on this serverless platform. This opens up new possibilities for PHP developers to leverage the scalability and cost-effectiveness of serverless computing.

Setting Up PHP on AWS Lambda

To run PHP on AWS Lambda, we need to use a custom runtime. Here’s a step-by-step guide to get you started:

  1. Create a Custom Runtime Layer First, we need to create a layer containing the PHP runtime:

    mkdir php-lambda && cd php-lambda
    docker run --rm -v $(pwd):/tmp amazonlinux:2 /bin/bash -c "
        yum install -y amazon-linux-extras
        amazon-linux-extras enable php7.4
        yum install -y php-cli php-mbstring
        cp /usr/bin/php /tmp/
        cp -a /usr/lib64/php /tmp/
    "
    zip -r php-layer.zip php bin
    
  2. Upload the Layer to AWS Upload the php-layer.zip file to S3 and create a new Lambda layer from it.

  3. Create a PHP Lambda Function Create a new Lambda function using a custom runtime. Here’s a basic PHP Lambda function:

    <?php
    
    function handler($event, $context) {
        return [
            'statusCode' => 200,
            'body' => json_encode(['message' => 'Hello from PHP on Lambda!'])
        ];
    }
    
  4. Configure the Lambda Function Set the runtime to “Custom runtime on Amazon Linux 2” and the handler to “index.handler”. Add the PHP layer you created earlier.

  5. Create a Bootstrap File Create a bootstrap file in your function directory:

    #!/bin/sh
    
    set -euo pipefail
    
    # Initialization - load function handler
    source $LAMBDA_TASK_ROOT/"$(echo $_HANDLER | cut -d. -f1).php"
    
    while true
    do
      # Request processing
      HEADERS="$(mktemp)"
      EVENT_DATA=$(curl -sS -LD "$HEADERS" -X GET "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next")
      REQUEST_ID=$(grep -Fi Lambda-Runtime-Aws-Request-Id "$HEADERS" | tr -d '[:space:]' | cut -d: -f2)
    
      # Execute the handler function from the script
      RESPONSE=$(php -r "require('$LAMBDA_TASK_ROOT/index.php'); echo json_encode(handler('$EVENT_DATA', null));")
    
      # Send the response
      curl -X POST "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$REQUEST_ID/response" -d "$RESPONSE"
    done
    
  6. Deploy Your Function Zip your index.php and bootstrap files together and upload them to your Lambda function.

Things to Consider When Using PHP on Lambda

While running PHP on Lambda opens up new possibilities, there are several factors to keep in mind:

  1. Cold Starts: Like other Lambda functions, PHP functions can experience cold starts. Optimize your code and dependencies to minimize this.

  2. Dependencies: If your PHP application requires additional libraries, you’ll need to include them in your deployment package or create additional layers.

  3. Database Connections: For database-driven applications, consider using AWS RDS Proxy to manage database connections efficiently.

  4. File System Limitations: Lambda’s read-only file system might require adjustments to how your PHP application handles file operations.

  5. Execution Time: Lambda functions have a maximum execution time of 15 minutes. Ensure your PHP code can complete within this limit.

  6. Stateless Design: Design your PHP applications to be stateless, as Lambda functions should not rely on maintaining state between invocations.

  7. Error Handling: Implement robust error handling in your PHP code to leverage Lambda’s built-in logging and monitoring capabilities.

Conclusion

Running PHP on AWS Lambda provides an exciting opportunity to bring serverless architecture to PHP applications. While it requires some setup and consideration, the benefits of scalability, cost-effectiveness, and reduced infrastructure management make it a compelling option for many use cases.

As you embark on your PHP-on-Lambda journey, remember to optimize your code for the serverless environment, carefully manage dependencies, and leverage AWS services that complement Lambda’s capabilities. With these considerations in mind, you can successfully deploy and run PHP applications in a serverless world.

For more information and examples, check out the AWS blog article here: https://aws.amazon.com/blogs/apn/aws-lambda-custom-runtime-for-php-a-practical-example/

Get up to 65% Off Hosting with FREE SSL & FREE Domains!