Delete object or bucket in Amazon S3? - php

I created a new amazon bucket called "photos". The bucket url is something like:
www.amazons3.salcaiser.com/photos
Now I upload subfolders containing files, into that bucket for example
www.amazons3.salcaiser.com/photos/thumbs/file.jpg
My questions are, does thumbs/ is assumed a new bucket or is it an object?
Then if I want to delete the entire thumbs/ directory need I first to delete all files inside that or can I delete all in one time?

In the case you are describing, "photos" is the bucket. S3 does not have sub-buckets or directories. Directories are simulated by using slashes in the object key. "thumbs/file.jpg" is an object key and "thumbs/" would be considered a key prefix.
Dagon's examples are good and use the older version 1.x of the AWS SDK for PHP. However, you can do this more easily with the newest 2.4.x version AWS SDK for PHP which includes a helper method for deleting multiple objects.
<?php
// Include the SDK. This line depends on your installation method.
require 'aws.phar';
use Aws\S3\S3Client;
$s3 = S3Client::factory(array(
'key' => 'your-aws-access-key',
'secret' => 'your-aws-secret-key',
));
// Delete the objects in the "photos" bucket with the a prefix of "thumbs/"
$s3->deleteMatchingObjects('photos', 'thumbs/');

//Include s3.php file first in code
if (!class_exists('S3'))
require_once('S3.php');
//AWS access info
if (!defined('awsAccessKey'))
define('awsAccessKey', 'awsAccessKey');
if (!defined('awsSecretKey'))
define('awsSecretKey', 'awsSecretKey');
//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);
if ($s3->deleteObject("bucketname", `filename`)) {
echo 'deleted';
}
else
{
echo 'no file found';
}

found some code snippets for 'directory' deletion - i did not write them:
PHP 5.3+:
$s3 = new AmazonS3();
$bucket = 'your-bucket';
$folder = 'folder/sub-folder/';
$s3->get_object_list($bucket, array(
'prefix' => $folder
))->each(function($node, $i, $s3) {
$s3->batch()->delete_object($bucket, $node);
}, array($s3));
$responses = $s3->batch()->send();
var_dump($responses->areOK());
Older PHP 5.2.x:
$s3 = new AmazonS3();
$bucket = 'your-bucket';
$folder = 'folder/sub-folder/';
$s3->get_object_list($bucket, array(
'prefix' => $folder
))->each('construct_batch_delete', array($s3));
function construct_batch_delete($node, $i, &$s3)
{
$s3->batch()->delete_object($bucket, $node);
}
$responses = $s3->batch()->send();
var_dump($responses->areOK());

I have implemented this in Yii as,
$aws = Yii::$app->awssdk->getAwsSdk();
$s3 = $aws->createS3();
$s3->deleteMatchingObjects('Bucket Name','object key');

Related

Download File from Amazon s3. Download succees but File Empty

I tried to download file from amazon s3 to local storage. Download success, file appear in local storage but the file is empty no content. Looks like missed something in the Code. Need your help friends. Thanks in Advance
here's the code :
<?php
namespace App\Console\Library;
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
use Storage;
class DownloadAWS
{
public function downloadFile(){
$s3_file = Storage::cloud()->url('Something.jsonl');
$s3 = Storage::disk('local')->put('Order.jsonl', $s3_file);
}
}
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
try {
// Get the object.
$result = $s3->getObject([
'Bucket' => $bucket,
'Key' => $keyname
]);
// Display the object in the browser.
header("Content-Type: {$result['ContentType']}");
echo $result['Body'];
} catch (S3Exception $e) {
echo $e->getMessage() . PHP_EOL;
Currently, you are retrieving an URL to the s3 file and you are putting it in a file. Your code should currently create a file Order.jsonl containing the link to the s3 file.
What you really seem to want is getting the file and storing it locally. You can achieve this with the following code:
public function downloadFile()
{
$s3_file = Storage::cloud()->get('Something.jsonl');
$s3 = Storage::disk('local')->put('Order.jsonl', $s3_file);
}
The only difference is using get() vs. url().

how do i upload a file to a directory in google cloud storage using Google_Client library

i want to upload a file to google cloud storage using google client php library on github. Am able to upload file to cloud storage but am not able to upload to a directory in cloud storage. i get the error message No such object: bucketName/abc/test.jpg
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=files/google_cloud.json');
$client->useApplicationDefaultCredentials();
$storage = new Google\Cloud\Storage\StorageClient([
'projectId' => $googleprojectID
]);
$sPath = "files/com/test.jpg";
$objectName = "/abc/test.jpg";
$bucketName = $googlebucketName;
$bucket = $storage->bucket($bucketName);
$bucket->upload( fopen($sPath, 'r') );
$object = $bucket->object($objectName);
$info = $object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
First of all, let me share with you this documentation page where you will find the complete reference for the Google Cloud Storage PHP Client Library. More specifically, if you have a look at the upload() method, you will see that in order to set the name of the object uploaded (and therefore its location, given that GCS has a flat namespace), you have to use the options parameter, which can contain a name field pointing to the right location to upload.
Also, note that the correct object name should not start with a slash /, given that it will automatically be added after the bucket name. Therefore, you should modify your code to add something like this:
$sPath = "files/com/test.jpg";
$objectName = "abc/test.jpg"; # Note the removal of "/" here
$options = [
'name' => $objectName
];
$bucketName = $googlebucketName;
$bucket = $storage->bucket($bucketName);
$bucket -> upload(
fopen($sPath, 'r'),
$options
);

Download files from firebase Storage with php

i am new in firebase web if it possible to upload, download, and delete file using php. i have upload file using JS but i want to download using PHP.
Here is script of download file using JS but i want in PHP.
Thanks in advance...
My Code
[START storage_quickstart]
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Storage\StorageClient;
# Your Google Cloud Platform project ID
$projectId = 'My project ID';
# Instantiates a client
$storage = new StorageClient([
'projectId' => $projectId
]);
# The name for the new bucket
$bucketName = 'my bucket';
# Creates the new bucket
$bucket = $storage->createBucket($bucketName);
echo 'Bucket ' . $bucket->name() . ' created.';
# [END storage_quickstart]
return $bucket;
The short answer is that you should use gcloud-php. This requires that you set up a service account (or use Google Compute Engine/Container Engine/App Engine which provide default credentials).
It's likely that you'll create a service account, download a keyfile.json, and provide it as an argument to the StorageClient, like so:
# Instantiates a client
$storage = new StorageClient([
'keyFilePath' => '/path/to/key/file.json',
'projectId' => $projectId
]);
Alternatively, it looks like they've built another layer of abstraction, which takes the same arguments but allows you to use lots of other services:
use Google\Cloud\ServiceBuilder;
$gcloud = new ServiceBuilder([
'keyFilePath' => '/path/to/key/file.json',
'projectId' => 'myProject'
]);
$storage = $gcloud->storage();
$bucket = $storage->bucket('myBucket');
That's an old question, but I was struggling with same problem... hope my solution help someone.
In fact, I really don't know if there is an official way to do that, but I created the method below and it worked for me.
function storageFileUrl($name, $path = []) {
$base = 'https://firebasestorage.googleapis.com/v0/b/';
$projectId = 'your-project-id';
$url = $base.$projectId.'/o/';
if(sizeof($path) > 0) {
$url .= implode('%2F', $path).'%2F';
}
return $url.$name.'?alt=media';
}
To access files in the root of bucket:
$address = storageFileUrl('myFile');
Result: https://firebasestorage.googleapis.com/v0/b/your-project-id.appspot.com/o/myFile?alt=media
To access files inside some folder, do:
$address = storageFileUrl('myFile', ['folder', 'subfolder']);
Result: https://firebasestorage.googleapis.com/v0/b/your-project-id.appspot.com/o/folder%2Fsubfolder%2FmyFile?alt=media
Enjoy.

Set Private files to Public Amazon S3

Is it possible to convert from private s3 files in bucket to public using PHP library provided by Amazon AWS S3?
All you need to do is set the ACL to public-read, you can do this with the PHP SDK using the update_object() function.
$s3 = new AmazonS3();
$bucket = 'my-bucket' . strtolower($s3->key);
$response = $s3->update_object($bucket, 'test1.txt', array(
'acl' => AmazonS3::ACL_PUBLIC
));
Source

uploading posted file to amazon s3

I'm trying to upload a file to Amazon S3 via Laravel 4.
After user submit a form, the file will be passed to a function where I need to use Amazon PHP SDK and upload the file to Amazon S3 bucket.
But how do I upload the file straight away to Amazon S3 without saving the file onto server.
My current code looks like this,
private function uploadVideo($vid){
$file = $vid;
$filename = $file->getClientOriginalName();
if (!class_exists('S3'))require_once('S3.php');
if (!defined('awsAccessKey')) define('awsAccessKey', '123123123');
if (!defined('awsSecretKey')) define('awsSecretKey', '123123123');
$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->putBucket("mybucket", S3::ACL_PUBLIC_READ);
$s3->putObject($vid, "mybucket",$filename , S3::ACL_PUBLIC_READ);
}
Grab the official SDK from http://docs.aws.amazon.com/aws-sdk-php/latest/index.html
This example uses http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_upload
require('aws.phar');
use Aws\S3\S3Client;
use Aws\Common\Enum\Region;
// Instantiate the S3 client with your AWS credentials and desired AWS region
$client = S3Client::factory(array(
'key' => 'KEY HERE',
'secret' => 'SECRET HERE',
'region' => Region::AP_SOUTHEAST_2 // you will need to change or remove this
));
$result = $client->upload(
'BUCKET HERE',
'OBJECT KEY HERE',
'STRING OF YOUR FILE HERE',
'public-read' // public access ACL
);

Categories