Amazon AWS putBucketLogging parameters in PHP - php

I am writing script that connects to amazon S3 storage. The script is supposed to create 2 buckets:
Bucket is for data
Bucket is for logs
I successfully created both buckets but I can't set up logging. Below is shown code I use for enabling bucket logging
$result = $client->putBucketLogging(array(
'Bucket' => $bucket,
'LoggingEnabled' => array(
'TargetBucket' => $bucket . '-LOG',
'TargetGrants'=>array(
'Grantee'=>array(
'DisplayName'=>'user.name',
'Type'=>'CanonicalUser'
),
),
'TargetPrefix' => 'LOG-',
),
));
In amazon AWS API for PHP version 2 is written that Bucket, LoggingEnabled and Type are mandatory. But the documentation does not say how to exactly implement there parameters.
Could you please help me with structure of config array for putBucketLogging method?

You can also use the service's API documents as a reference, which sometimes contain more details about how to specifically structure some of the data types for requests. The S3 API docs for PUT Bucket Logging have more details about how to specify the grantee.
Also, you should not use capital letters in bucket names (See Rules for Bucket Naming).

After searching in manuals the php array for method putBucketLogging is
$result = $client->putBucketLogging(array(
'Bucket' => $bucket,
'LoggingEnabled' => array(
'TargetBucket' => $bucket . '-log',
'TargetGrants' => array(
'Grant' => array(
'Grantee' => array(
'Type' => 'AmazonCustomerByEmail',
'EmailAddress' => 'email#email.com',
),
'Permission' => 'FULL_CONTROL',
),
),
'TargetPrefix' => 'log-',
),
));
However enabling logging fails with exception that tells me I have to set permissions on log bucket...

Related

SQS SendMessage & $_POST Issue

If I put $author='Steven King'; it works without issue, however it does not work with a post variable.
To be "clear" if I hard code the the author in the JSON it will in fact post the message to the SQS queue. This is the expected result, however if I pass the string from the Post Variable e.g. $author=$_POST['author], the message is never delivered.
$message = array(
// Associative array of custom 'String' key names
'Author' => array(
'StringValue' =>$author,
'DataType' => 'String'
),
);
Any thoughts or help on this I would be grateful.
<?php
$author =$_POST["author"];
require 'vendor/autoload.php';
use Aws\Common\Aws;
use Aws\Sqs\SqsClient;
use Aws\Exception\AwsException;
// Get the client from the builder by namespace
$client = SqsClient::factory(array(
'profile' => 'default',
'region' => 'us-west-2',
'version' => '2012-11-05'
));
$queueUrl ='https://sqs.us-west-2.amazonaws.com/blahblahblah';
$message = array(
// Associative array of custom 'String' key names
'Author' => array(
'StringValue' =>$author,
'DataType' => 'String'
),
);
var_dump($message);
$result = $client->sendMessage(array(
'QueueUrl' => $queueUrl,
'MessageBody' => 'An awesome message!',
'MessageAttributes' =>$message,
));
So the issue was caused by the credential provider, which is why it worked in the cli e.g. php posts.php and not in the browser. Because in the CLI it has the correct environment and permissions.
Note: However on AWS SDK example does not include the credential provider only a reference to 'profile' => 'default' which would be thought to grab your default credentials, however that is not the case.
Thank you apache logs!
The fix was to set the right permissions on the /.aws/credentials and ensure
that your $HOME path is set correctly.
On to the next piece. Thanks community.

Realtime voice call with 2 person using nexmo/vonage

is it possible to do realtime voice call using nexmo/vonage with PHP or Javascript via web browser?
i used library called nexmo/laravel.
This sample code that i used:
$nexmo = Nexmo::calls()->create([
'to' => [[
'type' => 'phone',
'number' => '855969818674'
]],
'from' => [
'type' => 'phone',
'number' => '63282711511'
],
'answer_url' => ['https://gist.githubusercontent.com/jazz7381/d245a8f54ed318ac2cb68152929ec118/raw/6a63a20d7b1b288a84830800ab1813ebb7bac70c/ncco.json'],
'event_url' => [backpack_url('call/event')]
]);
with that code i can send text-to-speech, but how can i do realtime voice conversation person to person?
From the code you shared above, it looks like you might not have instantiated a client instance of the Nexmo PHP SDK, which is necessary to do so. You make an outbound call with an instantiated and authenticated client.
For example, first instantiate a client with the following, supplying the file path to your private key file, your application ID, your API key and your API secret. You can obtain all of those from the Dashboard
$basic = new \Nexmo\Client\Credentials\Basic('key', 'secret');
$keypair = new \Nexmo\Client\Credentials\Keypair(
file_get_contents((NEXMO_APPLICATION_PRIVATE_KEY_PATH),
NEXMO_APPLICATION_ID
);
$client = new \Nexmo\Client(new \Nexmo\Client\Credentials\Container($basic, $keypair));
Then, once you have a credentialed client, you can then invoke the $client->calls() methods on it. For example:
$client->calls()->create([
'to' => [[
'type' => 'phone',
'number' => '14843331234'
]],
'from' => [
'type' => 'phone',
'number' => '14843335555'
],
'answer_url' => ['https://example.com/answer'],
'event_url' => ['https://example.com/event'],
]);
You can find more information on using the PHP SDK on GitHub. You can also find code snippets, tutorials, and more instructions on our developer portal.

Get EC2 Bandwidth Usage By Instance ID

How do I get the instance bandwidth usage for NetworkIn and NetworkOut for an EC2 instance based on the instance ID using the PHP SDK.
So far what I have is...
<?php
require_once("../aws/Sdk.php");
use Aws\CloudWatch\CloudWatchClient;
$client = CloudWatchClient::factory(array(
'profile' => 'default',
'region' => 'ap-southeast-2'
));
$dimensions = array(
array('Name' => 'Prefix', 'Value' => ""),
);
$result = $client->getMetricStatistics(array(
'Namespace' => 'AWSSDKPHP',
'MetricName' => 'NetworkIn',
'Dimensions' => $dimensions,
'StartTime' => strtotime('-1 hour'),
'EndTime' => strtotime('now'),
'Period' => 3000,
'Statistics' => array('Maximum', 'Minimum'),
));
I have a PHP cron job running every hour and I need to be able to get the bandwidth in and out for a specific EC2 instance to record in an internal database.
What I have above I have been able to piece together from the SDK documentation but from here I am kinda stumped.
I believe what I need is cloudwatch so would rather it be able to be done through this. I know that I can install a small program onto each server to report the bandwidth usage to a file on the server that I then SFTP into to download to our database but would rather it be done externally of any settings within the instance itself so that an instance admin can't cause issues with the bandwidth reporting.
Managed to get it working with...
<?php
require '../../aws.phar';
use Aws\CloudWatch\CloudWatchClient;
$cw = CloudWatchClient::factory(array(
'key' => 'your-key-here',
'secret' => 'your-secret-here',
'region' => 'your-region-here',
'version' => 'latest'
));
$metrics = $cw->listMetrics(array('Namespace' => 'AWS/EC2'));
//print_r($metrics);
$statsyo = $cw->getMetricStatistics(array(
'Namespace' => 'AWS/EC2',
'MetricName' => 'NetworkIn',
'Dimensions' => array(array('Name' => 'InstanceId', 'Value' => 'your-instance-id-here')),
'StartTime' => strtotime("2017-01-23 00:00:00"),
'EndTime' => strtotime("2017-01-23 23:59:59"),
'Period' => 86400,
'Statistics' => array('Average'),
'Unit' => 'Bytes'
));
echo($statsyo);
If you're trying to calculate your bandwidth charge the same way AWS would, a better and more conclusive way would be to use VPC Flow Logs. You can subscribe your ENI to VPC flow logs (should be pretty cheap, they only charge for CloudWatch Logs costs, flow logs is free) then use the AWS SDK to pull from CloudWatch with GetLogEvents, and then sum up the bytes total.

Is it possible to add a subdomain to Route53 using the AWS PHP SDK?

I am working on a project where we will be creating both subdomains as well as domains in Route53. We are hoping that there is a way to do this programmatically. The SDK for PHP documentation seems a little light, but it appears that createHostedZone can be used to create a domain or subdomain record and that changeResourceRecordSets can be used to create the DNS records necessary. Does anyone have examples of how to actually accomplish this?
Yes, this is possible using the changeResourceRecordSets call, as you already indicated. But it is a bit clumsy since you have to structure it like a batch even if you're changing/creating only one record, and even creations are changes. Here is a full example, without a credentials method:
<?php
// Include the SDK using the Composer autoloader
require 'vendor/autoload.php';
use Aws\Route53\Route53Client;
use Aws\Common\Credentials\Credentials;
$client = Route53Client::factory(array(
'credentials' => $credentials
));
$result = $client->changeResourceRecordSets(array(
// HostedZoneId is required
'HostedZoneId' => 'Z2ABCD1234EFGH',
// ChangeBatch is required
'ChangeBatch' => array(
'Comment' => 'string',
// Changes is required
'Changes' => array(
array(
// Action is required
'Action' => 'CREATE',
// ResourceRecordSet is required
'ResourceRecordSet' => array(
// Name is required
'Name' => 'myserver.mydomain.com.',
// Type is required
'Type' => 'A',
'TTL' => 600,
'ResourceRecords' => array(
array(
// Value is required
'Value' => '12.34.56.78',
),
),
),
),
),
),
));
The documentation of this method can be found here. You'll want to take very careful note of the required fields as well as the possible values for others. For instance, the name field must be a FQDN ending with a dot (.).
Also worth noting: You get no response back from the API after this call by default, i.e. there is no confirmation or transaction id. (Though it definitely gives errors back if something is wrong.) So that means that if you want your code to be bulletproof, you should write a Guzzle response handler AND you may want to wait a few seconds and then run a check that the new/changed record indeed exists.
Hope this helps!
Yes, I done using changeResourceRecordSets method.
<?php
require 'vendor/autoload.php';
use Aws\Route53\Route53Client;
use Aws\Exception\CredentialsException;
use Aws\Route53\Exception\Route53Exception;
//To build connection
try {
$client = Route53Client::factory(array(
'region' => 'string', //eg . us-east-1
'version' => 'date', // eg. latest or 2013-04-01
'credentials' => [
'key' => 'XXXXXXXXXXXXXXXXXXX', // eg. VSDFAJH6KXE7TXXXXXXXXXX
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXX', //eg. XYZrnl/ejPEKyiME4dff45Pds54dfgr5XXXXXX
]
));
} catch (Exception $e) {
echo $e->getMessage();
}
/* Create sub domain */
try {
$dns = 'yourdomainname.com';
$HostedZoneId = 'XXXXXXXXXXXX'; // eg. A4Z9SD7DRE84I ( like 13 digit )
$name = 'test.yourdomainname.com.'; //eg. subdomain name you want to create
$ip = 'XX.XXXX.XX.XXX'; // aws domain Server ip address
$ttl = 300;
$recordType = 'CNAME';
$ResourceRecordsValue = array('Value' => $ip);
$client->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
"ResourceRecordSet" => [
'Name' => $name,
'Type' => $recordType,
'TTL' => $ttl,
'ResourceRecords' => [
$ResourceRecordsValue
]
]
]
]
],
'HostedZoneId' => $HostedZoneId
]);
}
If you get any error please check into server error.log file. If you get error from SDK library then there is might PHP version not supported.
if you run this code from your local machine then you might get "SignatureDoesNotMatch" error then Make sure run this code into same (AWS)server environment.

Laravel return array value from app/config/package folder

Hi I am using a laravel package https://github.com/greggilbert/recaptcha and I have published the config files where I need to store my public and private keys for my recaptcha. I want to call this elsewhere in my app in an attempt to process this via AJAX . I've tried to call this as
dd(Config::get('packages.greggilbert.recaptcha')['public_key']);
however this returns as null. The array is kept in the following folder:
app/config/packages/greggilbert/recaptcha/config.php
the array is built as so:
<?php
return array(
'public_key' => 'publickey',
'private_key' => 'privatekey',
'template' => '',
'driver' => 'curl',
'options' => array(
'curl_timeout' => 1,
),
'version' => 2,
);
Any ideas how I can retrieve the public_key value??
Retrieving configs from a package works a bit different. You use a so-called namespace:
Config::get('recaptcha::public_key');

Categories