Hi all wanted to ask how to set chromeDriver options default path to a specific directory so that if one downloads file using laravel dusk headless driver, files downloads to the directory.
Thanks in advance.
Try this:
$this->browse(function (Browser $browser) {
$url = $browser->driver->getCommandExecutor()->getAddressOfRemoteServer();
$uri = '/session/' . $browser->driver->getSessionID() . '/chromium/send_command';
$body = [
'cmd' => 'Page.setDownloadBehavior',
'params' => ['behavior' => 'allow', 'downloadPath' => '/your/download/path']
];
(new \GuzzleHttp\Client())->post($url . $uri, ['body' => json_encode($body)]);
$browser->visit('/');
});
Replace /your/download/path with the actual path.
This example requires the guzzlehttp/guzzle package to execute the POST request.
There are other solutions without external dependencies:
How do I send a POST request with PHP?
Related
I'm new to all this, so please be gentle. I know basic php and have WAMP installed on my computer. All I need is a simple way to transcribe audio files. I have the google cloud shell sdk installed and used that to have composer install the required files (copied and pasted the command from google's tutorial), which it put in a vendor folder.
I then modified the php code google put on github which I'll paste below. When I try to run the php file, however, I get the following error message(s). What am I doing wrong? :(
<?php
# [START speech_quickstart]
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Speech\SpeechClient;
# Your Google Cloud Platform project ID
$projectId = 'xxxx';
# Instantiates a client
$speech = new SpeechClient([
'projectId' => $projectId,
'languageCode' => 'en-US',
]);
# The name of the audio file to transcribe
$fileName = __DIR__ . '/audio/transcribe.mp3';
# The audio file's encoding and sample rate
$options = [
'encoding' => 'LINEAR16',
'sampleRateHertz' => 16000,
'languageCode' => 'en-US',
'enableWordTimeOffsets' => false,
'enableAutomaticPunctuation' => true,
'model' => 'video',
];
# Detects speech in the audio file
$results = $speech->recognize(fopen($fileName, 'r'), $options);
foreach ($results as $result) {
echo 'Transcription: ' . $result->alternatives()[0]['transcript'] . PHP_EOL;
}
# [END speech_quickstart]
return $results;
The error message indicate cURL does not have the list of certificate authority's certificates available, so is unable to verify the integrity of the connection to Google. The steps in this answer should resolve the issue.
Issue
The same code, on almost identical servers, fails locally and on production, however works on our staging server. When we attempt to interact with an item in a bucket, we get an Error retrieving credentials....
- Both servers, staging and production, are deployed by Envoyer and provisioned by Forge to AWS EC2 instances.
- Both instances hit the same bucket with the same bucket policy.
- .env settings are same for all, minus the server name and debugging
Error on production:
Aws\Exception\CredentialsException
Error retrieving credentials from the instance profile metadata server. (cURL error 28: Connection timed out after 1003 milliseconds (see http://curl.haxx.se/libcurl/c/libcurl-errors.html))
Server settings
Staging
Ubuntu 16.04.2 LTS on AWS
PHP 7.1.3-3
NPM 3.10.10
Node v6.10.1
Production
Ubuntu 16.04.1 LTS on AWS EC2
PHP 7.1.6-1
npm 3.10.10
Node v6.10.1
Composer.json packages
"laravel/framework": "5.4.*", // 5.4.25
"aws/aws-sdk-php-laravel": "~3.0", // 3.1.0
"guzzlehttp/guzzle": "~6.0", // 6.2.3
Code sample
function getPhoto($personID)
{
$contents = '';
$id = $personID;
$cloudFront = env('AWS_CLOUDFRONT_PHOTO'); // d212rosgvhtylp.cloudfront.net
$fileKey = filePath($id) . '_t.jpg'; // 9ae299a1990e79d62f07c28bb60ecf6f_t.jpg
$fileURL = $cloudFront . '/' . filePath($id) . '_t.jpg'; // d212rosgvhtylp.cloudfront.net/9ae299a1990e79d62f07c28bb60ecf6f_t.jpg
// check if in remote storage then get contents
$contents = Storage::disk('s3photo')->get($fileKey); /* ****** FAILS HERE ****** */
// stream bioPhoto
header('Content-Type: image/jpeg');
echo $contents;
}
After ensuring your .env files contain the correct values for the AWS client, run the following command:
php artisan config:clear
This should clear up your issue if it is caused by initially having incorrect or missing env data, not sure when the cache is updated on it's own but the config cache seems to be pretty persistent.
I encountered this issue after I accedentially had entered the AWS_ACCESS_KEY_ID in the .env file twice.
.env:
AWS_ACCESS_KEY_ID=MYREALID
AWS_SECRET_ACCESS_KEY=myrealkey
...
...a lot of variables..
...
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
The AWS sdk therefor tries to search for these credentials elsewhere, at that's have the error occures.
I recently had this problem. In my case, it worked locally and not on the EC2 instance. I did not understand too much. In the end I realized that I had set up IAM locally in the default folder ~/.aws/credentials, so in local everything was good. So I poked in the laravel sources and I noticed that laravel was going to take the connection configs in the file services.php config folder.
Edit config/services.php and put in the AWS IAM keys.
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('AWS_KEY'),
'secret' => env('AWS_SECRET'),
'region' => env('AWS_REGION'),
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
So I saw that my .env file did not have the AWS IAM login keys, those called in the config /services.php file.
After a small adjustment everything works great.
This issue may occur if you are passing the wrong ENV variables, check your config/filesystems.php:
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
See: https://github.com/laravel/laravel/blob/master/config/filesystems.php#L60
And make sure the keys are matching in your .env.
Pretty sure they changed the name in the last couple updates.
I am trying to write a script to automatically update the nameservers that I registered in Route 53.
This can be done via Amazon Rest API:
http://docs.aws.amazon.com/Route53/latest/APIReference/api-update-domain-name-servers.html
Up to this point, I have been using the Amazon PHP SDK...but this SDK doesn't even have support for this command (or a majority of Route 53 commands).
I've spent hours trying to form a request using php+curl. I have everything I need - an acesskeyID, secret key, etc. No matter what I do I can NOT seem to get the signature to be valid. The docs are a nightmare...everything related to PHP immediately points you to the SDK, which is no help here.
Please show me how to make a REST request with PHP, sign it using my key, and get a response.
Edit: Here is what I tried to follow to sign the request.
Which version of the SDK are you using?
According to api v3 docs you can use this:
$result = $client->updateDomainNameservers([/* ... */]);
$promise = $client->updateDomainNameserversAsync([/* ... */]);
And these are the relevant parameters:
$result = $client->updateDomainNameservers([
'DomainName' => '<string>', // REQUIRED
'FIAuthKey' => '<string>',
'Nameservers' => [ // REQUIRED
[
'GlueIps' => ['<string>', ...],
'Name' => '<string>', // REQUIRED
],
// ...
],
]);
If you are not using the latest version of the sdk you can install it using composer:
php composer.phar require aws/aws-sdk-php
or use any of the installation methods here.
I really think its best for you to stick with the SDK, unless really not possible (which I don't think is the case here, correct me if I'm wrong).
If installed using composer you can update your composer.json file to contain:
{
"require": {
"aws/aws-sdk-php": "3.*"
}
}
and run composer update
If you just want to check which version of the sdk you are working with you can run composer info (inside that directory):
> composer info
aws/aws-sdk-php 3.18.32 AWS SDK for PHP - Use Amazon Web Services in your PHP project
guzzlehttp/guzzle 6.2.1 Guzzle is a PHP HTTP client library
guzzlehttp/promises 1.2.0 Guzzle promises library
guzzlehttp/psr7 1.3.1 PSR-7 message implementation
mtdowling/jmespath.php 2.3.0 Declaratively specify how to extract elements from a JSON document
psr/http-message 1.0 Common interface for HTTP messages
Or check the content of the composer.lock file. You should have there the version of the sdk you are using:
"packages": [
{
"name": "aws/aws-sdk-php",
"version": "3.18.32",
"source": {
"type": "git",
"url": "https://github.com/aws/aws-sdk-php.git",
"reference": "84b9927ee116b30babf90a9fc723764672543e29"
},
Make sure you use the last one.
Thanks to #Dekel, I was able to solve this problem. Here is my final code.
require_once '/vendor/autoload.php';
$access_key="XXXXX";
$secret_key="XXXXXXXXXXXX";
$client = Aws\Route53Domains\Route53DomainsClient::factory(array(
'region'=> "us-east-1",
'version'=>'2014-05-15',
'credentials' => array(
'key' => $access_key,
'secret' => $secret_key,
)));
$result = $client->updateDomainNameservers([
'DomainName' => 'example.com',
"Nameservers"=>array(
array("Name"=>"ns.1.com"),
array("Name"=>"ns.2.com")
)
]);
How do I integrate my Yii 2.0 project with Aws ?
I have installed it using composer
"aws/aws-sdk-php": "2.*",
and included the
require '../vendor/aws/aws-autoloader.php';
But when I try to instantiate my S3 client, it keeps telling me that Aws does not exist.
You can refer the following link on github
https://github.com/JDpawar/yii2-aws-s3-sdk
It has the exact details how to use the S3 SDK along with the Yii 2 App.
AWS SDK for Yii2 - Use Amazon Web Services in your Yii2 project
This extension provides the AWS SDK 3 integration for the Yii2 framework
Installation
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist fedemotta/yii2-aws-sdk "*"
or add
"fedemotta/yii2-aws-sdk": "*"
to the require section of your composer.json file.
Note: You can still use AWS version 2 if you specify fedemotta/yii2-aws-sdk "1.*"
Usage
To use this extension, simply add the following code in your application configuration:
<?php
return [
//....
'components' => [
'awssdk' => [
'class' => 'fedemotta\awssdk\AwsSdk',
'credentials' => [ //you can use a different method to grant access
'key' => 'your-aws-key',
'secret' => 'your-aws-secret',
],
'region' => 'your-aws-region', //i.e.: 'us-east-1'
'version' => 'your-aws-version', //i.e.: 'latest'
],
],
];
?>
Getting all balancer names from AWS:
<?php
$aws = Yii::$app->awssdk->getAwsSdk();
$elb = $aws->createElasticloadbalancing();
$load_balancers = $elb->describeLoadBalancers()->toArray();
if (isset($load_balancers['LoadBalancerDescriptions'])){
foreach ($load_balancers['LoadBalancerDescriptions'] as $balancer){
if (isset($balancer['LoadBalancerName'])){
echo $balancer['LoadBalancerName'];
}
}
}
?>
Download an object from S3:
<?php
//specify the region if it is different than the main configuration region
Yii::$app->awssdk->region = 'sa-east-1';
$aws = Yii::$app->awssdk->getAwsSdk();
//use s3
$s3 = $aws->createS3();
$result = $s3->listObjects(['Bucket' => 'your-bucket-id',
"Prefix" => "your-path"])->toArray();
//get the last object from s3
$object = end($result['Contents']);
$key = $object['Key'];
$file = $s3->getObject([
'Bucket' => 'your-bucket-id',
'Key' => $key
]);
//download the file
header('Content-Type: ' . $file['ContentType']);
echo $file['Body'];
?>
Run the Composer command to install s3 extension. composer require frostealth/yii2-aws-s3 ~1.0#stable
Open common/config/main.php file and add below code into "components" section. "s3bucket" => [ "class" => \frostealth\yii2\aws\s3\Storage::className(), "region" => "Your region", "credentials" => [ "key" => "your aws s3 key", "secret" => "your aws s3 secret", ], "bucket" => "your aws s3 bucket", "defaultAcl" => \frostealth\yii2\aws\s3\Storage::ACL_PUBLIC_READ, "debug" => false, // bool|array ],
Use below code to upload image on s3 $s3 = Yii::$app->get('s3bucket')->upload('upload image name', 'path of local folder where image located');
After uploading you get status code and image url. you can get like below $status = $s3["#metadata"]["statusCode"]; $imageUrl = $s3["#metadata"]["effectiveUri"];
I reimport my extension using composer,
and adding
require (\Yii::getAlias('#vendor/autoload.php'));
Somehow I got it working by adding 'autoload' in json composer
"autoload": {
"psr-4": {
"vendor\\aws\\" :""
}
}
and then run
php composer.phar dumpautoload
Was looking around for this for a few hours and only found other packages to solve the issue. Wanted to implement the AWS package directly. So from
Installed the latest aws-sdk via composer.
I am using
"aws/aws-sdk-php": "^3.259"
Make sure aws source and location is correct in the vendor/composer/autoload_psr4.php
'Aws\\' => array($vendorDir . '/aws/aws-sdk-php/src')
After that ran composer update as mentioned by #Karate_Dog
php composer.phar dumpautoload
I don't want to use composer to install Omnipay but rather use traditional PHP includes to setup Omnipay with Stripe.
How do i do this? I have extracted it to this folder:
www.mysite.com/payments/src
Stripe.php with example code is here:
www.mysite.com/payments/Stripe.php
Where do i put the stripe payment gateway files?
What PHP files do i need to include in the header example code?
I am using this example code:
include $_SERVER['DOCUMENT_ROOT']."/payments/src/Omnipay/Omnipay.php";
use Omnipay\Omnipay;
$gateway = Omnipay::create('Stripe');
$gateway->setApiKey('abc123');
$formData = ['number' => '4242424242424242', 'expiryMonth' => '6', 'expiryYear' => '2016', 'cvv' => '123'];
$response = $gateway->purchase(['amount' => '10.00', 'currency' => 'USD', 'card' => $formData])->send();
if ($response->isSuccessful()) {
// payment was successful: update database
print_r($response);
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
$response->redirect();
} else {
// payment failed: display message to customer
echo $response->getMessage();
}
Not sure why you want to go that way, but if you really want to why not just install it with composer in another location and then copy the files (including the composer autoload file) in your project.
I'm running xampp on Windows and initially I didn't want to use composer either but once composer is installed then all I needed to do was to create the composer.json file in the project directory with the code below and in cmd change path to the project directory and type composer install.
{
"require": {
"omnipay/stripe": "~2.0"
}
}
I could then see why a manual installation is not documented because it automatically installed the all the following dependancies and configured the autoload files vendor/composer/:
vendor/autoload.php
vendor/composer
vendor/guzzle
vendor/omnipay/common
vendor/omnipay/stripe
vendor/symfony/event-dispatcher
vendor/symfony/http-foundation
vendor/symfony/polyfill-mbstring
composer.lock