expiration object s3 through php sdk - php

I want to set an expiration date for an object on s3 I create the object like this:
$this->s3->putObject(array(
'Bucket' => BUCKET,
'Key'=> "path",
'SourceFile' => $fileTmp,
'Expires' => time()+2*60,
'ACL' => 'private'
));
But when I check file on aws S3 Console the object keeps:
Expiry Date: None
Expiration Rule: N/A
How can I set object expiration?

Use the putBucketLifecycle method like that:
$result = $client->putBucketLifecycleConfiguration([
'Bucket' => '<string>', // REQUIRED
'LifecycleConfiguration' => [
'Rules' => [ // REQUIRED
[
'Expiration' => [
'Date' => <integer || string || DateTime>,
'Days' => <integer>,
'ExpiredObjectDeleteMarker' => true || false,
],
'ID' => '<string>',
'Prefix' => '<string>',
'Status' => 'Enabled|Disabled', // REQUIRED
],
// ...
],
],
]);
Note
This method will replace all the existing rules. So if you need
to append a new rule I recommend you to use
getBucketLifecycleConfiguration before and merge the previous
rules with the new one.
You can only set a Lifecycle rule on a prefix (or tag), not an object.
'prefix' is your path, excluding the file name, with a trailing slash.
Resources
https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putbucketlifecycleconfiguration

Lifecycle policies are set per bucket, not per file.
Here's how to set a Lifecycle policy for a bucket:
In AWS S3 console (the web version), click on the bucket
Choose Properties; expand Lifecycle
Add Rule appears. Click it.
Complete the wizard using your own set of rules

Related

"Amazon Personalize" PutItems, PutEvents, PutUsers using aws/aws-sdk-php

I am building an integration between my Laravel application and Amazon Personalize using:
aws/aws-sdk-php
Everything goes ok, but when I look on how to update the datasets with new Users, interactions and items, I couldn't find the right method/approach to do this, or if it is even possible.
I have created the Event Tracker but I can't find how to replicate this Python code into PHP:
# Configure Properties:
event = {
"itemId": str(ITEM_ID),
}
event_json = json.dumps(event)
# Make Call
personalize_events.put_events(
trackingId = TRACKING_ID,
userId= USER_ID,
sessionId = session_ID,
eventList = [{
'sentAt': int(time.time()),
'eventType': 'EVENT_TYPE',
'properties': event_json
}]
The code above is a portion extracted from here https://github.com/aws-samples/amazon-personalize-samples/blob/master/getting_started/notebooks/1.Building_Your_First_Campaign.ipynb
That would be for tracking new events:
https://docs.aws.amazon.com/personalize/latest/dg/API_UBS_PutEvents.html
If there is a chance to avoid executing an extra Python script better, if not I will go for that option.
Thanks in advance!
I found that I need to use the PersonalizeEventsClient instead of PersonalizeClient for this purpose, as stated here:
https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-personalize-events-2018-03-22.html#putevents
The link is part of the AWS Personalize documentation, I missed that previously, there they explain how to PutEvents, Items and Users using the AWS SDK PHP, for example:
$client = AWS::createClient('personalizeevents');
$result = $client->putEvents([
'eventList' => [ // REQUIRED
[
'eventId' => '<string>',
'eventType' => '<string>', // REQUIRED
'eventValue' => <float>,
'impression' => ['<string>', ...],
'itemId' => '<string>',
'properties' => '<string>',
'recommendationId' => '<string>',
'sentAt' => <integer || string || DateTime>, // REQUIRED
],
// ...
],
'sessionId' => '<string>', // REQUIRED
'trackingId' => '<string>', // REQUIRED
'userId' => '<string>',
]);
I am also using this service provider for Laravel:
https://github.com/aws/aws-sdk-php-laravel

Need to clear Google OAuth cache?

I set up the Google OAuth with Hybridauth and it works from my development folder e.g. http://example.com/dev and callback is located at http://example.com/dev/callback.php
Now I want to move the dev folder to the production folder e.g. http:/example.com/backend and callback is changed to http://example.com/backend/callback.php
I changed the Authorized redirect URIs from Google console, but Google keeps the old callback link when I do log in.
Is it necessary to clear cache from Google or wait for an amount of time to let Google update the changes?
$config = [ 'callback' => 'example.com/backedn/callback.php',
'providers' => [ 'Google' => [ 'enabled' => true,
'keys' => [ 'id' => 'xxxxx.apps.googleusercontent.com',
'secret' => 'xxxxxxx', ],
'scope' => 'email', ], ], ];
Sorry for my careless mistake as I call the old script from the popup
function auth_popup( provider ){
// replace 'path/to/hybridauth' with the real path to this script
var authWindow = window.open('http://example.com//dev/callback.php?provider='+provider, 'authWindow', 'width=600,height=400,scrollbars=yes');
return false;
}

The "access_key" option must be provided to use fixer.io

For the currency conversion i am using "florianv/laravel-swap": "^1.1" library. Florianv/Laravel-swap.
As Fixer.io has changed its implementation, it is necessary to pass the access_key with the request, and because of that i am getting this error: "InvalidArgumentException: The "access_key" option must be provided to use fixer.io in /var/www/project/project-files/vendor/florianv/exchanger/src/Service/Fixer.php:51".
I registered and got the access_key.
I updated the library using composer and now i can see three constants in the vendor/florianv/exchanger/src/Service/Fixer.php.
const ACCESS_KEY_OPTION = 'access_key';
const LATEST_URL = 'http://data.fixer.io/api/latest?base=%s&access_key=%s';
const HISTORICAL_URL = 'http://data.fixer.io/api/%s?base=%s&access_key=%s';
To pass the access key i tried this:
I have a swap.php in config folder which looks something like this:
return [
'options' => [
'cache_ttl' => 86400, // 24 hours.
'cache_key_prefix' => 'currency_rate'
],
'services' => [
'fixer' => true,
],
'currency_layer' => [
'access_key' => 'asdfas7832mw3nsdfa776as8dfa', // Your app id
'enterprise' => true, // True if your AppId is an enterprise one
],
'cache' => env('CACHE_DRIVER', 'file'),
'http_client' => null,
'request_factory' => null,
'cache_item_pool' => null,
];
This had one more option which was commented, i enabled and passed the access_key in it but it doesn't work.
I also added it in services block below 'fixer => true'.
'currency_layer' => [
'access_key' => 'asdfas7832mw3nsdfa776as8dfa'
]
Also in options block:
'options' => [
'cache_ttl' => 86400, // 24 hours.
'cache_key_prefix' => 'currency_rate',
'access_key'=>'7ca208e9136c5e140d6a14427bf9ed21'
],
I tried with adding access_key in config/services.php file but it also didn't work.
'fixer' => [
'access_key' => 'asdfas7832mw3nsdfa776as8dfa'
],
Even i tried, adding to env file and calling from there, but no success. How do i pass the access_key, can anyone help me on this, what should be the approach.
vendor/florianv/exchanger/src/Service/Fixer.php -> don't touch the constant (that was my own error).
Pass the options-array by creating the Builder:
$options = ['access_key' => 'YourGeneratedAPIKeyAtCurrencyLayer'];
$this->exchangeSwap = (new Builder($options))
->add('fixer', $options )
->build();
I hope I could help ;-)

Yii2 Translate Manager doesn't work

I m using a basic template for a small project on Yii2. I have already set the module Language Picker of Lajax (Doc) and I am trying now to manage the translation with the module Translate Manager of Lajax (Github). The plugin is scanning perfectly the project and getting the translatable texts. I even set some translations through this module and everything is saved in the database, but these translations are not set when changing the language.
here are my web.php Configurations:
'language' => 'en-GB',
'components' => [
...
'languagepicker' => [
'class' => 'lajax\languagepicker\Component',
'languages' => ['en-GB', 'fr-FR']
],
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\DbMessageSource',
'db' => 'db',
'sourceLanguage' => 'en-GB',
'sourceMessageTable' => '{{%language_source}}',
'messageTable' => '{{%language_translate}}',
'forceTranslation' => true,
'cachingDuration' => 86400,
'enableCaching' => true,
],
],
],
...
]
'modules' => [
...
'translatemanager' => [
'class' => 'lajax\translatemanager\Module',
'root' => '#app', // The root directory of the project scan.
'scanRootParentDirectory' => false, // Whether scan the defined `root` parent directory, or the folder itself.
// IMPORTANT: for detailed instructions read the chapter about root configuration.
'layout' => 'language', // Name of the used layout. If using own layout use 'null'.
'allowedIPs' => ['127.0.0.1'], // IP addresses from which the translation interface is accessible.
'roles' => ['#'], // For setting access levels to the translating interface.
'tmpDir' => '#runtime', // Writable directory for the client-side temporary language files.
// IMPORTANT: must be identical for all applications (the AssetsManager serves the JavaScript files containing language elements from this directory).
'phpTranslators' => ['::t'], // list of the php function for translating messages.
'jsTranslators' => ['lajax.t'], // list of the js function for translating messages.
'patterns' => ['*.js', '*.php'],// list of file extensions that contain language elements.
'ignoredCategories' => ['yii'], // these categories won't be included in the language database.
'ignoredItems' => ['config'], // these files will not be processed.
'scanTimeLimit' => null, // increase to prevent "Maximum execution time" errors, if null the default max_execution_time will be used
'searchEmptyCommand' => '!', // the search string to enter in the 'Translation' search field to find not yet translated items, set to null to disable this feature
'defaultExportStatus' => 1, // the default selection of languages to export, set to 0 to select all languages by default
'defaultExportFormat' => 'json',// the default format for export, can be 'json' or 'xml'
'tables' => [ // Properties of individual tables
[
'connection' => 'db', // connection identifier
'table' => '{{%language}}', // table name
'columns' => ['name', 'name_ascii'],// names of multilingual fields
'category' => 'database-table-name',// the category is the database table name
]
],
'scanners' => [ // define this if you need to override default scanners (below)
'\lajax\translatemanager\services\scanners\ScannerPhpFunction',
'\lajax\translatemanager\services\scanners\ScannerPhpArray',
'\lajax\translatemanager\services\scanners\ScannerJavaScriptFunction',
'\lajax\translatemanager\services\scanners\ScannerDatabase',
],
],
...
]
I always use something like this im code for translatable strings:
<?= Yii::t('app','Test') ?>
Am I doing something wrong?

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.

Categories