简体   繁体   中英

How to connect your local php function to AWS lambda?

I am very new to this. I only know about S3 and also created my functionality. But, now I want to use Lambda in my php project. I am using AWS PHP SDK for this. I created a lambda function on AWS in which I am passing file name.

The lambda function searches the file from S3 and gives me the data inside the file, but now what I want to do is that I pass a file name inside my php function which then passes that filename to my Lambda function and searches the file from S3 then returns the data inside the file.

This is my lambda function on S3

import boto3

bucket = 'get-file-lambda-function'
filename = 'myfilename.json'
    
def lambda_handler(event, context):
    s3 = boto3.client('s3')
    file = s3.get_object(Bucket=bucket, Key=filename)
    body = file.get()['Body'].read()
    
return body

This is my php function which gets the data from lambda function. Now, I want to pass a file name inside my php function. And lambda search only that file from S3.

public function get_file_data() 
{
    $client = LambdaClient::factory(AWS configrations);

    $filename = /*selected by me*/

    $fileData = $client->invoke([
        // Lambda function name
        'FunctionName' => 'get-file-lambda-function',
    ]);

    return $fileData;
}

i am a beginner so I do not know about this right now. Would anyone please guide me that how can I achieve this?

This is actually quite simple for your requirement.

In your PHP app you would make use of the Payload argument when you call invoke. An example is below

public function get_file_data($file_name) 
{
    $client = LambdaClient::factory(AWS configuration);

    $filename = /*selected by me*/

    $fileData = $client->invoke([
        // Lambda function name
        'FunctionName' => 'get-file-lambda-function',
        'Payload' => json_encode(['bucket' => 'get-file-lambda-function', 'key' => $file_name])
    ]);

    return $fileData;
}

Then in your Lambda function you would access this data by using the event parameter. An example of this below

import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
    bucket = event['bucket']
    filename = event['key']
    file = s3.get_object(Bucket=bucket, Key=filename)
    body = file.get()['Body'].read()

    return body

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM