DasBeasto
DasBeasto

Reputation: 2282

Invoke AWS Lambda from PHP with params

I'm trying to create a Lambda function that will create a blank image with dimensions passed from a PHP file. Since I'm very new to AWS I started out with a test function that involved no parameters, just created a blank 200x300 image:

'use strict';


const http = require('http');
const https = require('https');
const querystring = require('querystring');

const AWS = require('aws-sdk');
const S3 = new AWS.S3({
  signatureVersion: 'v4',
});
const Sharp = require('sharp');

// set the S3 and API GW endpoints
const BUCKET = 'MY_BUCKET_ID';
exports.handler = (event, context, callback) => {
  let request = event.Records[0].cf.request;

  Sharp({
    create: {
      width: 300,
      height: 200,
      channels: 4,
      background: { r: 255, g: 0, b: 0, alpha: 128 }
    }
  })
  .png()
  .toBuffer()
  .then(buffer => {
    // save the resized object to S3 bucket with appropriate object key.
    S3.putObject({
        Body: buffer,
        Bucket: BUCKET,
        ContentType: 'image/png',
        CacheControl: 'max-age=31536000',
        Key: 'test.png',
        StorageClass: 'STANDARD'
    }).promise()
    // even if there is exception in saving the object we send back the generated
    // image back to viewer below
    .catch(() => { console.log("Exception while writing resized image to bucket")});

    // generate a binary response with resized image
    response.status = 200;
    response.body = buffer.toString('base64');
    response.bodyEncoding = 'base64';
    response.headers['content-type'] = [{ key: 'Content-Type', value: 'image/png' }];
    callback(null, response);
  })
  // get the source image file

  .catch( err => {
    console.log("Exception while reading source image :%j",err);
  });
};

I ran this using the Test functionality in the Lambda dashboard and saw my test.png show up in my S3 bucket. So the next step was calling it from PHP. I added this line to my lambda that I got from a different tutorial to grab the request in order to parse out the query string and such:

let request = event.Records[0].cf.request;

Then in my PHP I added:

require '../vendor/autoload.php';
$bucketName = 'MY_BUCKET_ID';

$IAM_KEY = 'MY_KEY';
$IAM_SECRET = 'MY_SECRET_ID';

use Aws\Lambda\LambdaClient;
$client = LambdaClient::factory(
    array(
        'credentials' => array(
            'key' => $IAM_KEY,
            'secret' => $IAM_SECRET
        ),
        'version' => 'latest',
        'region'  => 'us-east-1'
    )
);
$result = $client->invoke([
  // The name your created Lamda function
  'FunctionName' => 'placeHolder',
]);
echo json_decode((string) $result->get('Payload'));

Where "placeHolder" is the correct name of my lambda function.

The echo in the PHP returns: "Catchable fatal error: Object of class stdClass could not be converted to string"

and if I try to run the test functionality on the Lambda again I get:

TypeError: Cannot read property '0' of undefined at exports.handler (/var/task/index.js:17:30) Referring to the newly added request line.

So my question is, how do I successfully call this Lambda function from PHP and get request from the PHP request into Lambda?

EDIT: I echo'd $result as a whole instead of Payload this was the result

{
  "Payload": {

  },
  "StatusCode": 200,
  "FunctionError": "Unhandled",
  "LogResult": "",
  "ExecutedVersion": "$LATEST",
  "@metadata": {
    "statusCode": 200,
    "effectiveUri": "https:\/\/lambda.us-east-1.amazonaws.com\/2015-03-31\/functions\/placeHolder\/invocations",
    "headers": {
      "date": "Thu, 15 Mar 2018 22:01:34 GMT",
      "content-type": "application\/json",
      "content-length": "107",
      "connection": "close",
      "x-amzn-requestid": "6cbc2a0e-289c-11e8-a8a4-d91e9d73438a",
      "x-amz-function-error": "Unhandled",
      "x-amzn-remapped-content-length": "0",
      "x-amz-executed-version": "$LATEST",
      "x-amzn-trace-id": "root=1-5aaaed3d-d3088eb6e807b2cd712a5383;sampled=0"
    },
    "transferStats": {
      "http": [
        [

        ]
      ]
    }
  }
}

Upvotes: 5

Views: 7400

Answers (2)

Vi_XKI
Vi_XKI

Reputation: 1

Add Policy In Your Lambda Function : InVoke and Call another lambda Function

function Lambda($load,$lambdaName){
$client = LambdaClient::factory([
    'version' => 'latest',
    'region' => us-east-2,
        ]);
    $result = $client->invoke([
        'FunctionName' => $lambdaName,
        'InvocationType' => 'Event',
        'Payload' => json_encode($load)
    ]);
    echo 'Lambda invoking again';
    print_r($load);
    return true;
   

}

Upvotes: 0

Oleksandr
Oleksandr

Reputation: 61

You need to call the __toString() method. It works for me.

So, doing a echo json_decode($result->get('Payload')->__toString(), true); to get an array with statusCode and body.

There is another way to get data from GuzzleHttp\Psr7\Stream type. Like a $result['Payload']->getContents()

Upvotes: 6

Related Questions