Code Monkey home page Code Monkey logo

backblaze-b2's Introduction

Backblaze B2 SDK for PHP

Software License Latest Version Build Status

backblaze-b2 is a client library for working with Backblaze's B2 storage service. It aims to make using the service as easy as possible by exposing a clear API and taking influence from other SDKs that you may be familiar with.

This package will cache authorization request for 1 hour so that you won't receive API Limit from B2.

This version works with both master key and application key, and version 2 (look below).

Example

This is just a short example, full examples to come on the wiki.

use obregonco\B2\Client;
use obregonco\B2\Bucket;

$client = new Client('accountId', [
	'keyId' => 'your-key-id', // optional if you want to use master key (account Id)
	'applicationKey' => 'your-application-key',
]);
$client->version = 2; // By default will use version 1
$client->domainAliases = [ // When you want to use your own domains (using CNAME)
		'f0001.backblazeb2.com' => 'alias01.mydomain.com',
	];
$client->largeFileLimit = 3000000000; // Lower limit for using large files upload support. Default: 3GB

// Returns a Bucket object.
$bucket = $client->createBucket([
    'BucketName' => 'my-special-bucket',
    'BucketType' => Bucket::TYPE_PRIVATE // or TYPE_PUBLIC
]);

// Change the bucket to private. Also returns a Bucket object.
$updatedBucket = $client->updateBucket([
    'BucketId' => $bucket->getId(),
    'BucketType' => Bucket::TYPE_PUBLIC
]);

// Retrieve an array of Bucket objects on your account.
$buckets = $client->listBuckets();

// Delete a bucket.
$client->deleteBucket([
    'BucketId' => '4c2b957661da9c825f465e1b'
]);

// Upload a file to a bucket. Returns a File object.
$file = $client->upload([
    'BucketName' => 'my-special-bucket',
    'FileName' => 'path/to/upload/to',
    'Body' => 'I am the file content'

    // The file content can also be provided via a resource.
    // 'Body' => fopen('/path/to/input', 'r')
]);

// Download a file from a bucket. Returns the file content.
$fileContent = $client->download([
    'FileId' => $file->getId()

    // Can also identify the file via bucket and path:
    // 'BucketName' => 'my-special-bucket',
    // 'FileName' => 'path/to/file'

    // Can also save directly to a location on disk. This will cause download() to not return file content.
    // 'SaveAs' => '/path/to/save/location'
]);

// Delete a file from a bucket. Returns true or false.
$fileDelete = $client->deleteFileFromArray([
    'FileId' => $file->getId()

    // Can also identify the file via bucket and path:
    // 'BucketName' => 'my-special-bucket',
    // 'FileName' => 'path/to/file'
]);

// Retrieve an array of file objects from a bucket.
$fileList = $client->listFilesFromArray([
    'BucketId' => '4d2dbbe08e1e983c5e6f0d12'
]);

// Create a new access key.
$capabilities = new Capabilities()
$key = $client->createKey($accountId, $name, new Capabilities(
    [Capabilities::DELETE_BUCKETS,
    Capabilities::LIST_ALL_BUCKET_NAMES,
    Capabilities::READ_BUCKETS]
));

$keyId = $key->getKeyId();
$applicationKeyId = $key->getApplicationKey();

// Delete an existing access key.
try {
    $client->deleteKey($keyId);
} catch (RequestException $e) {
    // $e->getCode()
}

Installation

Installation is via Composer:

$ composer require obregonco/backblaze-b2

Tests

Tests are run with PHPUnit. After installing PHPUnit via Composer (under development):

$ vendor/bin/phpunit

Contributors

Feel free to contribute in any way you can whether that be reporting issues, making suggestions or sending PRs. :)

License

LGPL.

backblaze-b2's People

Contributors

jaytagdamian avatar n0nag0n avatar robregonm avatar rodber avatar struffel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

backblaze-b2's Issues

Deprecated: Return type of obregonco\B2\File::jsonSerialize() is not compatible

Error Message

Deprecated: Return type of obregonco\B2\File::jsonSerialize() should either be compatible with JsonSerializable::jsonSerialize(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in .../vendor/obregonco/backblaze-b2/src/File.php on line 112

Environment

  • obregonco/backblaze-b2: 1.1.0
  • PHP 8.1
  • strict mode declare(strict_types=1);

Bucket Settings

  • private
  • encrypted
  • Object lock disabled

Code to reproduce

<?php
declare(strict_types=1);

require_once __DIR__ . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

$keyId = ''; // Fill with your details
$applicationKey = ''; // Fill with your details
$bucketName = ''; // Fill with your details


$accountId = substr($keyId, 3, 12);

$b = new obregonco\B2\Client($accountId, ['keyId' => $keyId, 'applicationKey' => $applicationKey]);
$b->version = 2;
$bucketId = $b->getBucketIdFromName($bucketName);

$options = [
	'BucketName' => $bucketName,
	'BucketId' => $bucketId,
];

$fileList = $b->listFiles($options);
var_dump($fileList);

Solution

See Pull request (Update File.php) #16

obregonco\B2\Http\Client::request incompatible with GuzzleHttp\Client::request (Guzzle 6)

PHP Fatal error: Declaration of obregonco\B2\Http\Client::request(string $method, $uri = '', array $options = Array): Psr\Http\Message\ResponseInterface must be compatible with GuzzleHttp\Client::request($method, $uri = '', array $options = Array) in /home/bgcdn/vendor/obregonco/backblaze-b2/src/Http/Client.php on line 28

Is this library only compatible with Guzzle 7?

Class "obregonco\B2\client" not found

When I run the composer command: composer require obregonco/backblaze-b2

It runs, installs all packages, and generates the autoload files without error.

When I run a simple test.php script with contents:

<?php
use obregonco\B2\Client;

$client = new Client('accountId', [
	'keyId' => 'your-key-id', // optional if you want to use master key (account Id)
	'applicationKey' => 'your-application-key',
]);

?>

I get the following error message:

[Tue Mar 16 12:42:32 2021] PHP Fatal error: Uncaught Error: Class "obregonco\B2\Client" not found in C:\Users\Jonathon\Downloads\backblaze-b2-1.1.0\backblaze-b2-1.1.0\test.php:4
Stack trace:
#0 {main}
thrown in C:\Users\Jonathon\Downloads\backblaze-b2-1.1.0\backblaze-b2-1.1.0\test.php on line 4
[Tue Mar 16 12:42:32 2021] [::1]:51793 [500]: GET /test.php - Uncaught Error: Class "obregonco\B2\Client" not found in C:\Users\Jonathon\Downloads\backblaze-b2-1.1.0\backblaze-b2-1.1.0\test.php:4

Support for Laravel 8.x and Guzzle 7

Backblaze-b2 has a requirement for guzzlehttp/guzzle: ^6.5 which means it will complain when used with Laravel 8 which requires guzzle 7.0

I'm guessing the library will probably still work just fine with Guzzle 7, the main difference being raising the mimimum PHP version.

Can the dependency be updated to support Guzzle 7?

Backblaze b2 cloud Uploading Large files (9GB and more) not working

Hi,

Thanks for making it to work with PHP 7.0.
I'm using this from past 1 week and I am getting an error which I cannot handle even if place try catch blocks also...

Error:
BackBlaze Service Unavailable - 500 or 503 Error while uploading Large Files like 9GB and more

I need to upload files like 9GB and more in size. But I am always getting the error "500 or 503 Service Unavailable error was encountered while trying to upload files like 9GB or more".

I've placed try catch blocks to handle errors but whenever the errors like 500 or 503 arrived then It stops all the process and we cannot handle these errors.

I'm unable to upload Large file like 5GB, 9GB or 20 GB files.
After I have tried many times I can upload 5GB. But I tried 9GB files 50 times to upload and same error is returning.

Can anyone please look into it and resolve it ASAP.
Or Please guide me how to resolve these issues.

Thanks

Adding Prefix Support

I ran into a situation using your lib where i needed to search for files matching a specific criteria. I saw b2 supports a prefix option. I added prefix into the client class and it worked without a hitch. I'm sure there is probably a better way of doing this but here is what I changed. I only did this for list files in order to get the id's then download the matching ones:

`
public function listFiles(array $options)
{
// if FileName is set, we only attempt to retrieve information about that single file.
$fileName = !empty($options['FileName']) ? $options['FileName'] : null;

    $prefix = !empty($options['Prefix']) ? $options['Prefix'] : null;

`

and

// B2 returns, at most, 1000 files per "page". Loop through the pages and compile an array of File objects. while (true) { $response = $this->request('POST', '/b2_list_file_names', [ 'json' => [ 'bucketId' => $options['BucketId'], 'startFileName' => $nextFileName, 'maxFileCount' => $maxFileCount, 'prefix' => $prefix, ], ]);

Then when i called the client i just used. (with dates in my case) for the directory structure

$fileList = $client->listFiles([ 'BucketId' => 'somebuckid', 'Prefix' => $somevariable. '/'. date("Y") . '/' . date("n") . '/' . date("j"), ]);

Issue: Needs support for prefix.

Backblaze b2 Issue while downloading file

Hi,

I curenlty working with php 7.2.
List of file, delete file, upload etc works.
When i try to download a file, i get the following:

Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 3: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in C:\xampp\htdocs\backblaze\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:201 Stack trace: #0 C:\xampp\htdocs\backblaze\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(155): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 C:\xampp\htdocs\backblaze\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(105): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory)) #2 C:\xampp\htdocs\backblaze\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(44): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory)) #3 C:\xampp\htdocs\backblaze\vendor\guzzlehttp\guzzle\src\Handler\Proxy.php(28): GuzzleHttp\Handler\CurlHandler->__invoke(Objec in C:\xampp\htdocs\backblaze\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 201

Thank you in advance!

Missing dependency - yii framework

Client.php has this line at the top:

user yii\helpers\ArrayHelper;

yii is not required by composer.json. Is it assumed we need to have the yii framework already in our project to use this backblaze library? The only reason it is included is for this one command:

  $options = ArrayHelper::merge([
            'headers' => $headers,
        ], $options);

Is it possible to rewrite this line of code without using yii? I can't run the project unless I install the yii framework

Option to list files based on filename prefix

At the moment the client function listFiles() can only list either an entire bucket or a single file (as far as I can see it). It would be great to have the option to list all files with a certain prefix. This could save unnecessary API calls because I don't have to list everything and then filter the names manually.

Discussion: Moving forward with PHP 7.4 vs PHP 8

Are there plans to continue to support PHP 7.4 moving forward? I noticed in one of the latest commits the addition of a lot of explicit typing which I'm not sure is supported by PHP 7.4.

I ask because I've been working on a patched version to support concurrent uploads which is based off of 1.1. I have no plans to migrate to PHP 8 any time soon so I'm wondering whether I'm going to need to maintain my own fork to continue to support PHP 7.4.

Tag new release

Thanks for your work!

I tried migrating from https://github.com/gliterd/backblaze-b2 to your package, however since the latest two commits haven't been tagged as a relase yet I received the ArrayHelper errors. This could easily fixed by tagging the latest two commits as a relase so a composer install works!

fileExists with no BucketId does not work

When calling fileExists, if we don't pass in the BucketId in the options array, we should probably try to resolve this like what's done in the upload function, i.e. with the following code:

        if (!isset($options['BucketId']) && isset($options['BucketName'])) {
            $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']);
        }

At present, if BucketId isn't passed in, we get an undefined index error when we try to access this in the $response line in listFiles.

At the same time, I recommend making getBucketIdFromName (and the inverse) public functions as they can be useful for callers.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.