Here is my code which works if I run it locally but not if I run on my server to transfer my csv to s3 using PHP from my server.
<?php
// Include the AWS SDK using the Composer autoloader.
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-2'
]);
$bucket = 'edtopia';
$keyname = 'sample_1.csv';
try {
// Upload data.
$result = $s3->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'Body' => fopen('numberclub.org/edtopiadb/df_corr.csv', 'r'),
'ACL' => 'public-read'
));
echo $result['ObjectURL'] . "\n";
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
EDIT- This now working for me on the server, Now my challenge is to access the file on the local system to be sent to s3 using this php script where in the BODY i need to define my local system file path and this code running on the server. What is the effective way to achieve it
Related
I am trying to use AWS to store all files from my app there. I was successfully able to upload them to the bucket, but I am not able to retrieve the object to show it to the user. I am getting an error "You cannot call GetObject on the service resource." I am not sure what is wrong? I thought it was permission issues? but if so how come I can upload the file?
Here is what I have
function aws_file_upload($key,$file)
{
$aws = aws();
// Get a resource representing the S3 service.
$s3 = $aws->s3;
$bucket = $s3->bucket('my-bucket-name');
try{
$result = $object = $bucket->putObject([
'Key' => $key,
'Body' => fopen($file, 'r'),
]);
$status = 'OK';
}catch(Exception $e){
$status = 'error';
}
return $status;
}
function aws_file_get($key)
{
$aws = aws();
$s3 = $aws->s3;
$result = $s3->getObject([
'Bucket' => 'my-bucket-name',
'Key' => $key
]);
// Display the object in the browser.
header("Content-Type: {$result['ContentType']}");
echo $result['Body'];
}
$key = 'Cases/my-file.pdf';
$file_name = 'my-file.pdf';
$res = aws_file_upload($key,$file_name);/// this will put the file into the AWS bucket
$result = aws_file_get($key);/// this will through the error
You need to create an s3 client.
Here is some sample code from Creating and Using Amazon S3 Buckets with the AWS SDK for PHP Version 3 - AWS SDK for PHP:
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-west-2',
'version' => '2006-03-01'
]);
$result = $s3Client->putObject([
'Bucket' => $bucket,
'Key' => $key,
'SourceFile' => $file_Path,
]);
For anyone wanting an answer here was my solution.
$aws = aws();
$s3 = $aws->s3;
$bucket = $s3->bucket('my-bucket-name');
$result = $bucket->object($key)->get();
header("Content-Type: {$result['ContentType']}");
echo $result['Body'];
I want to upload my images in the amazon s3 bucket. My images database uploaded to another web server. I am unable to move it to the S3 bucket. I referred to some solutions from StackOverflow.
Here is my code I have tried:
use \usr\share\php\AWSSDKforPHP\S3;
use \usr\share\php\AWSSDKforPHP\S3\S3Client;
use \usr\share\php\AWSSDKforPHP\S3\Exception\S3Exception;
$bucket = 'cdn.example.com';
$keyname = $newfilename;
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => [
'key' => "**********************",
'secret' => "**********************************"
]
]);
try {
// Upload data.
$result = $s3->putObject([
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => $oldfilepath,
'ACL' => 'public-read'
]);
// Print the URL to the object.
echo $result['ObjectURL'] . PHP_EOL;
} catch (S3Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
Showing error in output:
Fatal error: Class 'usr\share\php\AWSSDKforPHP\S3\S3Client' not found in /var/www/html/cron-jobs/shift-img.php on line 35
I hope you are doing well.
My issue using AWS S3 is when I download images (png, jpg, jpeg) and documents (txt, doc, docx) from the bucket, the files are corrupted. I can't open them even though in the AWS S3 storage i can see them and downloaded manually and they open.
The only type I can upload and download correctly is PDF. With the other types I upload them correctly but when I download them the issue happens.
Here is my code for download:
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = 'some text';
$IAM_KEY = 'some text';
$IAM_SECRET = 'some text';
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation.
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => '2006-03-01',
'region' => 'us-east-2',
'signature' => 'v4'
)
);
} catch (Exception $e) {
// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
// return a json object.
die("Error: " . $e->getMessage());
}
$keyName = 'filepath';
// Add it to S3
try {
// Uploaded:
$result = $s3->getObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName
)
);
header("Content-Type: {$result['ContentType']}");
header('Content-Disposition: filename="' . basename($keyName) .'"');
echo $result['Body'];
} catch (Exception $e) {
die("Error: " . $e->getMessage());
}
I'm trying to transfer files from Shopify to S3, and I'm getting this error:
"You must specify a non-null value for the Body or SourceFile parameters." I believe it's because I'm transferring files from a remote location but I don't know how to get around this problem. I have validated that the remote file does exist, and that my code works fine if I'm uploading using a form.
My code:
require dirname(__FILE__).'/../../vendor/autoload.php';
use Aws\S3\S3Client;
$s3Client = null;
$bucket="mybucketname";
$myfile="myfilename.jpg";
$mypath="https://shopifyfilepath/".$myfile;
function SendFileToS3($filename, $filepath, $bucket)
{
global $s3Client;
if (!$s3Client)
{
$s3Client = S3Client::factory(array(
'key' => $_SERVER["AWS_ACCESS_KEY_ID"],
'secret' => $_SERVER["AWS_SECRET_KEY"]
));
}
$result = $s3Client->putObject(array(
'Bucket' => $bucket,
'Key' => $filename,
'SourceFile' => $filepath,
'ACL' => 'public-read'
));
return $result;
}
SendFileToS3($myfile, $mypath, $bucket);
You can't transfer a file directly from a HTTP path to S3. You'll need to download it to a local file (or variable) first, then transfer that.
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;
}