I'm creating presigned URL with aws-sdk-php for uploading files to S3 bucket. URLs for GET are working.
Here is the code
$client = S3Client::factory(array('region' => 'eu-west-1','key' => 'xxx','secret' => 'xxx',));
//option 1
$command = $client->getCommand('PutObject', array(
'Bucket' => 'myBucket',
'Key' => 'testing/signedPHP1_'.time(),
'ContentType' => 'image/jpeg',
'Body' => 'dump' //it's mandatory
));
$signedUrl = $command->createPresignedUrl('+5 minutes');
$signedUrl .= '&Content-Type=image%2Fjpeg';
echo("\n\nThe URL is: ". $signedUrl . "\n");
echo("Now run from console for upload:\ncurl -v -H \"Content-Type: image/jpeg\" -T /tmp/temp.jpg '" . $signedUrl . "'");
//option 2
$request = $client->put('myBucket/testing/signedPHP2_'.time());
$signedUrl = $client->createPresignedUrl($request, '+5 minutes');
$signedUrl .= '&Content-Type=image%2Fjpeg';
echo("\n\nThe URL is: ". $signedUrl . "\n");
echo("Now run from console for upload:\ncurl -v -H \"Content-Type: image/jpeg\" -T /tmp/temp.jpg '" . $signedUrl . "'");
//GET which works
$request = $client->get('myBucket/testing/existingFile.txt');
$signedUrl = $client->createPresignedUrl($request, '+5 minutes');
echo("\n\nThe URL is: ". $signedUrl . "\n");
echo("Now run:\ncurl '" . $signedUrl . "'");
//GET which works
$command = $client->getCommand('GetObject', array('Bucket' => 'myBucket','Key' => 'upload/data.txt'));
$signedUrl = $command->createPresignedUrl('+5 minutes');
echo("\n\nThe URL is: ". $signedUrl . "\n");
echo("Now run:\ncurl '" . $signedUrl . "'");
When trying to use curl command I'm getting and error
SignatureDoesNotMatch with message The request signature we calculated does not match the signature you provided. Check your key and signing method.
The similar code in aws-sdk for Javascript is working
var AWS = require('aws-sdk');
AWS.config.update({ accessKeyId: 'xxx', secretAccessKey: 'xxx', region: 'eu-west-1' });
var s3 = new AWS.S3();
var params = {
Bucket: 'myBucket',
Key: 'testing/preSignedURLnodeJS_' + (+new Date),
ContentType: 'image/jpeg',
Expires: 60 * 5
};
s3.getSignedUrl('putObject', params, function(err, url) {
console.log('The URL is: ', url);
console.log('Now run from console for upload:\n\ncurl -v -H "Content-Type: image/jpeg" -T /tmp/temp.jpg \'' + url + '\'');
});
Already done a lot of researching but no results. What am I doing wrong?
On Github I got an answer from SDK developer and it says
$command = $client->getCommand('PutObject', array(
'Bucket' => 'myBucket',
'Key' => 'testing/signedPHP1_'.time(),
'ContentType' => 'image/jpeg',
'Body' => '',
'ContentMD5' => false
));
Reference: https://github.com/aws/aws-sdk-php/issues/239
Here you go:
First, create the presigned URLs
<?php
/**
* getDocumentUploadUrls
*
* creates a list of url so you can upload multiple files per
* document. After uploading the files it is requires for you
* to confirm the uploads.
*
* #param Int $documentId the document id
* #param Int $count the amount of files you want to upload for this document
*
* #return Array list of URLs to use with PUT request to upload files to s3.
*/
public function getDocumentUploadUrls(Int $documentId, Int $count = 1): Array
{
$awsService = $this->getService('aws');
$s3Client = $awsService->getSdk()->createS3();
$urls = array_fill(1, $count, null);
$bucket = 'yourbucket';
$result = [];
$expire = '+20 minutes';
for ($i = 0; $i < $count; $i++) {
$fileCount = $i + 1;
$key = "{$documentId}/{$fileCount}";
$cmd = $s3Client->getCommand('PutObject', [
'Bucket' => $bucket,
'Key' => $key
]);
$request = $s3Client->createPresignedRequest($cmd, $expire);
$result[] = [
'url' => (string) $request->getUri(),
'reference' => "{$bucket}/{$key}"
];
}
return $result;
}
The result may look similar to this:
$result = [
0 => [
'url' => 'AwsS3://put/uri',
'reference' => 'docId/count'
]
];
Now, to upload with php cURL:
if ($request->isPost()) {
$files = $request->getFiles()->toArray();
$files = reset($files);
$data = $request->getPost();
$docId = $data['documentId']; // get this from your frontend POST params
$docCount = count($files);
try {
$endpoints = $this->getDocumentUploadUrls($userId, $docId, $docCount);
$uploadInfo = $this->uploadDocuments($endpoints, $files);
} catch (\Exception $e) {
// handle exception
}
}
public function uploadDocuments(Array $endpoints, Array $files)
{
$info = [];
foreach ($files as $index => $file) {
$url = $endpoints[$index]['url']; // the no. of files must match the number of endpoints for this to work
$type = isset($file['type']) ? $file['type'] : 'application/octet-stream';
$headers = [
"Content-Type: $type",
'Access-Control-Allow-Origin: *',
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $file);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_errno($ch)) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
$info[] = [
'headers' => $headers,
'response' => $response
];
}
return $info;
}
If you are using the sdk why not use the putObject command, rather than creating a put request yourself. This will take care of the signedUrl for you.
$result = $client->putObject(array(
'Bucket' => $bucket,
'Key' => 'data_from_file.txt',
'SourceFile' => $pathToFile
));
http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_putObject
If you don't want that, you need to look at the body of your put command, this should be the contents of the file you are uploading, not just a random string 'dump'.
Run wireshark on the machine running the command and you will see the body of the request curl is making is the contents of the file.
Related
can someone assist where i am doing mistake
generate vapid keys and store them
use push-api and store endpoint, p256dh and auth
send push notification using webPush protocol
but getting this at 3rd stage
Warning: openssl_sign(): Supplied key param cannot be coerced into a private key
code from 1 to 3 please go through
generate VAPID keys in php on server side and store them
// Generate VAPID keys
$private_key = openssl_pkey_new([
'private_key_type' => OPENSSL_KEYTYPE_EC,
'curve_name' => 'prime256v1',
]);
$details = openssl_pkey_get_details($private_key);
$private_key_raw = $details['ec']['d'];
$public_key_raw = $details['ec']['x'] . $details['ec']['y'];
$auth_token = base64_encode(openssl_random_pseudo_bytes(16));
$vapid = [
'private_key' => rtrim(strtr(base64_encode($private_key_raw), '+/', '-_'), '='),
'public_key' => rtrim(strtr(base64_encode($public_key_raw), '+/', '-_'), '='),
'auth_token' => $auth_token,
];
echo json_encode($vapid);
generate applicationServerKey using public key
$publicKey = 'SzRJTTxfRvvoIfYJye-Oj-xJ-eDxHjIBhPLxILieNbZ86KjRE_EIvdjdKDmUH9RLwgmkITs-v_z_6J44aP1TtA';
// Base64-decode the public key
$public_key_bytes = base64_decode($publicKey);
// Check that the public key has the correct format
if (strlen($public_key_bytes) != 65 || ord($public_key_bytes[0]) != 4) {
// The public key has an incorrect format
// Handle the error here
}
// Extract the x and y coordinates of the point
$x = substr($public_key_bytes, 1, 32);
$y = substr($public_key_bytes, 33, 32);
// Pack the bytes of the public key in the correct order
$application_server_key = "\x04" . $x . $y;
echo base64_encode($application_server_key);
use the base64 applicationServerKey on client side
let b64ASK = 'BDRJTTxfRvvoIfYJyeOjxJeDxHjIBhPLxILieNbZ86KjREEIvdjdKDmUH9RLwgmkITsvz6J44aP1TtAauthtokc=';
let asKey = encodeToUint8Array(b64ASK);
pushManager.subscribe({applicationServerKey:asKey,userVisibleOnly:true})
.then(subscription=>{console.log(subscription.toJSON())})
store endpoint,p256dh,auth and send push notification using vapid keys on server side
send-notification.php
$publicKey = 'SzRJTTxfRvvoIfYJye-Oj-xJ-eDxHjIBhPLxILieNbZ86KjRE_EIvdjdKDmUH9RLwgmkITs-v_z_6J44aP1TtA';
$privateKey = '-----BEGIN EC PRIVATE KEY-----
Lnp9eUjWE7o8oqneZPzOW8nbz7hTVosE25sJm47Arrg=
-----END EC PRIVATE KEY-----';
$endpoint = "https://fcm.googleapis.com/fcm/send/cI0XqQ4quFM:APA91bExZFUuSZ9lgTDJQqmrHJpV-w5pIVnvaiODI9WIeER-K0Vg0U5P8wfTslRF5KdTlCmF9_Tp7bpAohKLxLvQCuS2Cy6ZG2BpVKO4f0wLWrfU-mGD6GCMCVUYLna3uwDLR6NqZxNi";
$auth = "X6syP0cUxjDjMAcUunH3FA";
$p256dh = "BIUuCWdoJykH6u3vERcfZe8gxEx1ajaFTPGnM4cWdYv-Hp-qRgt5GShAtbFYRr5my8hH66uIJEiHf22XW_i_Bps";
// Set the payload for the notification
$payload = [
'title' => 'push-message-test',
'body' => 'This is a test notification using VAPID.',
'icon' => 'assets/icons/favicon-32x32.png',
];
// Encode the payload as a JSON string
$payloadJson = json_encode($payload);
// Generate the JWT header
$header = [
'alg' => 'ES256',
'typ' => 'JWT',
];
$headerJson = json_encode($header);
$headerBase64Url = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($headerJson));
// Generate the JWT claim
$now = time();
$exp = $now + (12 * 60 * 60); // 12 hours in the future
$claim = [
'aud' => $endpoint,
'exp' => $exp,
'sub' => 'https://example.com',
];
$claimJson = json_encode($claim);
$claimBase64Url = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($claimJson));
// Generate the JWT signature
$signingString = $headerBase64Url . '.' . $claimBase64Url;
$signature = '';
$privateKeyResource = openssl_pkey_get_private($privateKey);
openssl_sign($signingString, $signature, $privateKeyResource, 'sha256');
// Encode the signature as base64url
$signatureBase64Url = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
// Combine the JWT components into a string
$jwt = $headerBase64Url . '.' . $claimBase64Url . '.' . $signatureBase64Url;
// Send the notification using the Web Push protocol
$headers = [
'Authorization: Bearer ' . $jwt,
'Crypto-Key: p256ecdsa=' . $publicKey,
'Content-Length: ' . strlen($payloadJson),
'Content-Type: application/json',
];
$data = [
'endpoint' => $endpoint,
'publicKey' => $p256dh,
'authToken' => $auth,
'payload' => $payloadJson,
];
$options = [
'http' => [
'header' => implode("\r\n", $headers),
'method' => 'POST',
'content' => json_encode($data),
],
];
$context = stream_context_create($options);
$result = file_get_contents($endpoint, false, $context);
// Handle the response
if ($result === false) {
// Error handling
echo 'failed to send push';
} else {
// Success handling
echo 'succesfully sent push using push protocol';
}
I am writing a webhook in bref and want it to send a message to SQS. Using the entire AWS SDK for this is a colossal waste. How could I calculate the signature?
const AWS_DATETIME_FORMAT = 'Ymd\THis\Z';
$url = getenv('SQS_URL');
$data = [
'Action' => 'SendMessage',
'MessageBody' => $body,
'Expires' => (new DateTime('UTC'))->add(new DateInterval('PT1M'))->format(AWS_DATETIME_FORMAT),
'Version' => '2012-11-05',
];
$result = Requests::post($url, sign_request($url, $data), $data);
function sign_request($url, $data) {
// These values are provided by AWS Lambda itself.
$secret_key = getenv('AWS_SECRET_ACCESS_KEY');
$access_key = getenv('AWS_ACCESS_KEY_ID');
$token = getenv('AWS_SESSION_TOKEN');
$region = getenv('AWS_REGION');
$service = 'sqs';
$current = new DateTime('UTC');
$current_date_time = $current->format(AWS_DATETIME_FORMAT);
$current_date = $current->format('Ymd');
$signed_headers = [
'content-type' => 'application/x-www-form-urlencoded',
'host' => "sqs.$region.amazonaws.com",
'x-amz-date' => $current_date_time,
'x-amz-security-token' => $token, // leave this one out if you have a IAM created fixed access key - secret pair and do not need the token.
];
$signed_headers_string = implode(';', array_keys($signed_headers));
$canonical = [
'POST',
parse_url($url, PHP_URL_PATH),
'', // this would be the query string but we do not have one.
];
foreach ($signed_headers as $header => $value) {
$canonical[] = "$header:$value";
}
$canonical[] = ''; // this is always an empty line
$canonical[] = $signed_headers_string;
$canonical[] = hash('sha256', http_build_query($data));
$canonical = implode("\n", $canonical);
$credential_scope = [$current_date, $region, $service, 'aws4_request'];
$key = array_reduce($credential_scope, fn ($key, $credential) => hash_hmac('sha256', $credential, $key, TRUE), 'AWS4' . $secret_key);
$credential_scope = implode('/', $credential_scope);
$string_to_sign = implode("\n", [
'AWS4-HMAC-SHA256',
$current_date_time,
$credential_scope,
hash('sha256', $canonical),
]);
$signature = hash_hmac('sha256', $string_to_sign, $key);
unset($signed_headers['host']);
$signed_headers['Authorization'] = "AWS4-HMAC-SHA256 Credential=$access_key/$credential_scope, SignedHeaders=$signed_headers_string, Signature=$signature";
return $signed_headers;
}
Note this code is using rmccue/requests to do a POST request.
My serverless.yml looks like:
provider:
name: aws
region: us-east-1
runtime: provided.al2
environment:
SQS_URL: !Ref BadgeQueue
resources:
Resources:
BadgeQueue:
Type: AWS::SQS::Queue
Properties:
RedrivePolicy:
maxReceiveCount: 3
deadLetterTargetArn: !GetAtt BadgeDeadLetterQueue.Arn
BadgeDeadLetterQueue:
Type: AWS::SQS::Queue
Properties:
MessageRetentionPeriod: 1209600
In my wp project, I am using Assently for e-signature implementation. Though I have an account and created a pdf form file to be filled by the user I just am not able to proceed a bit. I am finding documentation not clear.
Also, I am not clear about what needs to be done so that the user will be shown form to process the transaction.
So, any help/suggestions to proceed forward is appreciated.
I have tried the following based on assently-laravel. But it's asking me to login. What is an error here?
Code:
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$url = 'https://test.assently.com/api/v2/createcasefromtemplate';
$default = array(
'Id' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce'
);
$data = array(
'auth' => $assently->auth(),
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce',
'agentUsername' => ''
);
$data = array(
'json' => $data
);
$options = array(
'http' => array(
'header' => "Content-type: application/json; charset=utf-8\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo '<pre>';
print_r($result);
die;
create this class inside assently folder
use Assently\AssentlyCase;
use Exception;
class CustomAssentlyCase extends AssentlyCase
{
public function createFromTemplate($data)
{
$default = [
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce'
];
$json = array_merge($default, $data);
try{
$response = $this->client->post($this->url('createcasefromtemplate'), [
'auth' => $this->assently->auth(),
'json' => $json
]);
}catch(Exception $e){
print_r($e->getMessage());
}
return $response;
}
}
Use
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
include_once('assently/CustomAssentlyCase.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$data = array(
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce',
'agentUsername' => 'agentUsername' // PUT your agent username here it is required
);
$customAssentlyCase = new CustomAssentlyCase($assently);
$result = $customAssentlyCase->createFromTemplate($data);
print_r($result);
Try this, though not tested but should work. Good luck.
I'm using the SDK found here:
https://github.com/facebook/facebook-php-sdk-v4
In addition, I'm using the process found here:
https://developers.facebook.com/docs/graph-api/video-uploads
Here is a summary of the relevant code I have so far:
$path = '/' . $fb->getUid() . '/videos';
$params = array('upload_phase' => 'start', 'file_size' => filesize($fileName));
$startResult = (new \Facebook\FacebookRequest($this->fbSession, 'POST', $path, $params, 'v2.3'))->execute()->getGraphObject();
print_r($startResult);
$startOffset = $startResult->getProperty('start_offset');
$endOffset = $chunkSize = $startResult->getProperty('end_offset');
$uploadSessionId = $startResult->getProperty('upload_session_id');
chdir(sys_get_temp_dir());
$splitCmd = "split --bytes=$chunkSize --suffix-length=1 --numeric-suffixes $fileName {$prefix}";
exec($splitCmd);
$part = 0;
while(($startOffset < $endOffset) && ($part <= 10))
{
$curChunk = sys_get_temp_dir() . '/' . $prefix . $part;
$params = array('upload_phase' => 'transfer',
'start_offset' => $startOffset,
'upload_session_id' => $uploadSessionId,
'video_file_chunk' => '#' . $curChunk);
print_r($params);echo "\n";
$upldResult = (new \Facebook\FacebookRequest($this->fbSession, 'POST', $path, $params, 'v2.3'))->execute()->getGraphObject();
$startOffset = $upldResult->getProperty('start_offset');
$endOffset = $upldResult->getProperty('end_offset');
unlink($curChunk);
$part++;
echo "$startOffset > $endOffset\n";
}
echo "Done uploading\n";
$params = array('upload_session_id' => $uploadSessionId,
'upload_phase' => 'finish',
'title' => 'My Title',
'description' => 'My Description',
);
print_r($params); echo "\n";
$postResult = (new \Facebook\FacebookRequest($this->fbSession, 'POST', $path, $params, 'v2.3'))->execute()->getGraphObject();
print_r($postResult);
There is an exception thrown everytime on the $upldResult line:
$upldResult = (new \Facebook\FacebookRequest($this->fbSession, 'POST', $path, $params, 'v2.3'))->execute()->getGraphObject();
The code is 1363041, and the message is "Invalid upload session given".
The entire output from my script is:
Facebook\GraphObject Object
(
[backingData:protected] => Array
(
[video_id] => 10205411650964653
[start_offset] => 0
[end_offset] => 1048576
[upload_session_id] => 10205411651004654
)
)
Array
(
[upload_phase] => transfer
[start_offset] => 0
[upload_session_id] => 10205411651004654
[video_file_chunk] => #/tmp/MyPrefix0
)
status: 1363041
message: (#1363041) Invalid upload session given.
I can't figure out how to fix this. I'm giving it the session id it just gave back to me to use in the resumable upload, and it's telling me that it's invalid (I think). Is anyone else using resumable upload, and how did you get it to work?
UPDATE: I no longer think this is related specifically to the php sdk. I can duplicate this exact same error using command line curl and also the API explorer.
UPDATE2: Here is the most basic way to duplicate this error, using curl and your own access token and fb profile:
curl -X POST "https://graph-video.facebook.com/v2.3/<your_fb_id>/videos" -F "access_token=<your_access_token>" -F "upload_phase=start" -F "file_size=3512954"
Response:{"video_id":"10205422595678264","start_offset":"0","end_offset":"1048576","upload_session_id":"10205422595718265"}
curl -X POST "https://graph-video.facebook.com/v2.3/<your_fb_id>/videos" -F "access_token=<your_access_token>" -F "upload_phase=transfer" -F "start_offset=0" -F "upload_session_id=10205422595718265" -F "video_file_chunk=#/tmp/CHUNK0.mp4"
Response: {"error":{"message":"(#1363041) Invalid upload session given.","type":"OAuthException","code":1363041}}
I'm trying to upload a picture on my amazon S3 via their PHP SDK. So I made a little script to do so. However, my script doesn't work and my exception doesn't send me back any error message.
I'm new with AWS thank you for your help.
Here is the code :
Config.php
<?php
return array(
'includes' => array('_aws'),
'services' => array(
'default_settings' => array(
'params' => array(
'key' => 'PUBLICKEY',
'secret' => 'PRIVATEKEY',
'region' => 'eu-west-1'
)
)
)
);
?>
Index.php
<?php
//Installing AWS SDK via phar
require 'aws.phar';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$bucket = 'infact';
$keyname = 'myImage';
// $filepath should be absolute path to a file on disk
$filepath = 'image.jpg';
// Instantiate the client.
$s3 = S3Client::factory('config.php');
// Upload a file.
try {
$result = $s3->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => $filePath,
'ContentType' => 'text/plain',
'ACL' => 'public-read',
'StorageClass' => 'REDUCED_REDUNDANCY'
));
// Print the URL to the object.
echo $result['ObjectURL'] . "\n";
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
?>
EDIT : I'm now using this code but its still not working. I don't even have error or exception message.
<?php
require 'aws.phar';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$bucket = 'infactr';
$keyname = 'sample';
// $filepath should be absolute path to a file on disk
$filepath = 'image.jpg';
// Instantiate the client.
$s3 = S3Client::factory(array(
'key' => 'key',
'secret' => 'privatekey',
'region' => 'eu-west-1'
));
try {
// Upload data.
$result = $s3->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => $filePath,
'ACL' => 'public-read',
'ContentType' => 'image/jpeg'
));
// Print the URL to the object.
echo $result['ObjectURL'] . "\n";
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
?>
Try something like this (from the AWS docs):
<?php
require 'aws.phar';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$bucket = '<your bucket name>';
$keyname = 'sample';
// $filepath should be absolute path to a file on disk
$filepath = '/path/to/image.jpg';
// Instantiate the client.
$s3 = S3Client::factory(array(
'key' => 'your AWS access key',
'secret' => 'your AWS secret access key'
));
try {
// Upload data.
$result = $s3->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => $filepath,
'ACL' => 'public-read'
));
// Print the URL to the object.
echo $result['ObjectURL'] . "\n";
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
?>
It works fine for me as long as you have the right credentials. Keep in mind that the key name is the name of your file in S3 so if you want to have your key have the same name of your file you have to do something like: $keyname = 'image.jpg'; . Also, a jpg is generally not a plain/text file type, you can ommit that Content-type field or you can just simply specify: image/jpeg
$s3 = S3Client::factory('config.php');
should be
$s3 = S3Client::factory(include 'config.php');
For those looking an up to date working version, this is what I am using
// Instantiate the client.
$s3 = S3Client::factory(array(
'credentials' => [
'key' => $s3Key,
'secret' => $s3Secret,
],
'region' => 'us-west-2',
'version' => "2006-03-01"
));
try {
// Upload data.
$result = $s3->putObject(array(
'Bucket' => $s3Bucket,
'Key' => $fileId,
'SourceFile' => $filepath."/".$fileName
));
return $result['ObjectURL'];
} catch (S3Exception $e) {
return false;
}
An alternative way to explain is by showing the curl, and how to build it in php - the pragmatic approach.
Please don't stone me for ugly code, just thought that this example is easy to follow for uploading to Azure from PHP, or other language.
$azure1 ='https://viperprodstorage1.blob.core.windows.net/bucketnameAtAzure/';
$azure3 ='?sr=c&si=bucketnameAtAzure-policy&sig=GJ_verySecretHashFromAzure_aw%3D';
$shellCmd='ls -la '.$outFileName;
$lsOutput=shell_exec($shellCmd);
#print_r($lsOutput);
$exploded=explode(' ', $lsOutput);
#print_r($exploded);
$fileLength=$exploded[7];
$curlAzure1="curl -v -X PUT -T '" . $outFileName . "' -H 'Content-Length: " . $fileLength . "' ";
$buildedCurlForUploading=$curlAzure1."'".$azure1.$outFileName.$azure3."'";
var_dump($buildedCurlForUploading);
shell_exec($buildedCurlForUploading);
This is the actual curl
shell_exec("curl -v -X PUT -T 'fileName' -H 'Content-Length: fileSize' 'https://viperprodstorage1.blob.core.windows.net/bucketnameAtAzure/fileName?sr=c&si=bucketNameAtAzure-policy&sig=GJ_verySecretHashFromAzure_aw%3D'")
Below are the code for upload image/file in amazon s3 bucket.
function upload_agreement_data($target_path, $source_path, $file_name, $content_type)
{
$fileup_flag = false;
/*------------- call global settings helper function starts ----------------*/
$bucketName = "pilateslogic";
//$global_setting_option = '__cloud_front_bucket__';
//$bucketName = get_global_settings($global_setting_option);
/*------------- call global settings helper function ends ----------------*/
if(!$bucketName)
{
die("ERROR: Template bucket name not found!");
}
// Amazon profile_template template js upload URL
$target_profile_template_js_url = "/".$bucketName."/".$target_path;
// Chatching profile_template template js upload URL
//$source_profile_template_js_url = dirname(dirname(dirname(__FILE__))).$source_path."/".$file_name;
// file name
$template_js_file = $file_name;
$this->s3->setEndpoint("s3-ap-southeast-2.amazonaws.com");
if($this->s3->putObjectFile($source_path, $target_profile_template_js_url, $template_js_file, S3::ACL_PUBLIC_READ, array(), array("Content-Type" => $content_type)))
{
$fileup_flag = true;
}
return $fileup_flag;
}