Buckets
in package
Class to Handle GCS Buckets based on Google Cloud Storage for PHP
php example to create a class object:
$bucket = $this->core->loadClass('Buckets','gs://{BucketName}');
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
Url references
Table of Contents
Properties
- $error : bool
- If there is an error in the last execution
- $errorCode : string|int
- If there is an error it shows the error code
- $errorMsg : array<string|int, mixed>
- If there is an error it shows an array of error messages
- $version : string
- version of the class.
Methods
- deleteFile() : bool|void
- Delete a filename from $path. if $path is empty it assumes '/'
- fastScan() : array<string|int, mixed>|void
- Execute a scandir over the path. if $path is empty it assumes '/'
- getAdminUrl() : string|null
- Returns the GCS Admin URL for the bucket
- getBucketPath() : string
- Return the path including the bucket name
- getContents() : string|void
- Return $filename content from $path
- getFileInfo() : array<string|int, mixed>|void
- Returns the GCS $file_path object info
- getInfo() : array<string|int, mixed>|void
- Returns the GCS bucket info of the gs://bucketname you passed in the Object construction
- getMimeTypeFromExtension() : string
- Return the mime type for $extension. If the extension is not found it returns 'application/octet-stream'
- getPublicUrl() : string|void
- It returns a public URL for the object making it Public you have the rights and the Bucket is Granular
- getSignedDownloadUrl() : string|void
- Provides a temporal signed URL to download an object.
- getSignedUploadUrl() : string|void
- Provides a PUT-signed URL that is used to upload an object.
- getUploadUrl() : mixed
- Deprecated method
- isDir() : bool
- tell if path is a dir
- isFile() : bool
- Tell if path is a file
- manageUploadFiles() : array<string|int, mixed>
- Move files uploaded in $_FILES to temporal space to Bucket $path taking $options
- mkdir() : bool|void
- Create a folder inside the bucket. If the folder exist then return true;
- putContents() : bool
- Create $filename with $data content in $path
- rmdir() : bool|void
- Delete a folder inside the bucket
- scan() : array<string|int, mixed>|null|void
- Execute a scandir over the path and evluate if they are files or directories. If the path is incorrect it will return void. If $path is empty it assumes '/'
- setFilePrivate() : string|void
- Set the file as private
- setFilePublic() : string|void
- Set the file as publicRead
- updateFileObject() : array<string|int, mixed>|void
- Update File object properties
- uploadContents() : array<string|int, mixed>
- Upload $source_file_path to the bucket with $filename_path
- uploadFile() : array<string|int, mixed>
- Upload $source_file_path to the bucket with $filename_path
Properties
$error
If there is an error in the last execution
public
bool
$error
= \false
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
$errorCode
If there is an error it shows the error code
public
string|int
$errorCode
= ''
if($bucket->error) echo $bucket->errorCode;
$errorMsg
If there is an error it shows an array of error messages
public
array<string|int, mixed>
$errorMsg
= array()
if($bucket->error) var_dump($bucket->$errorMsg);
$version
version of the class.
public
string
$version
= '202305311'
$bucket->version;
version of the class
Methods
deleteFile()
Delete a filename from $path. if $path is empty it assumes '/'
public
deleteFile(string $filename_path) : bool|void
example:
if(!$bucket->deleteFile('/tmp/file.txt')) {
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
else echo "/tmp/file.txt does not exist or can not be deleted";
} else echo "/tmp/file.txt has been deleted";
Parameters
- $filename_path : string
-
path to the file starting with '/' inside the bucket
Return values
bool|void —true if the file has been deleted. false if out exist and void if error
fastScan()
Execute a scandir over the path. if $path is empty it assumes '/'
public
fastScan([string $path = '' ]) : array<string|int, mixed>|void
example:
$files = $bucket->fastScan('/');
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
die(json_encode($bucket->fastScan('/'),JSON_PRETTY_PRINT));
output example:
[ "documents", "images" ]
Parameters
- $path : string = ''
-
path starting with '/' inside the bucket
Return values
array<string|int, mixed>|void —Array of files in the bucket. if there is any error it will return void
getAdminUrl()
Returns the GCS Admin URL for the bucket
public
getAdminUrl() : string|null
Example of php code
$bucket = $this->core->loadClass('Buckets',"{$bucket_name}");
if(!$bucket->error) echo $bucket->getAdminUrl();
Return values
string|nullgetBucketPath()
Return the path including the bucket name
public
getBucketPath(string $path) : string
Parameters
- $path : string
Return values
stringgetContents()
Return $filename content from $path
public
getContents(mixed $file[, string $path = '' ]) : string|void
example:
if(!$content = $bucket->getContents('file.txt','mi content','/tmp')){
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
else echo "/tmp/file.txt' does not exist or does not have any content";
} else echo $content;
Parameters
- $file : mixed
- $path : string = ''
-
optinal path starting with '/' inside the bucket
Return values
string|void —if $filename exist return string content
getFileInfo()
Returns the GCS $file_path object info
public
getFileInfo(string $file_path) : array<string|int, mixed>|void
Example of php code
$bucket = $this->core->loadClass('Buckets',"{$bucket_name}");
if(!$bucket->error) return $bucket->errorMsg;
$info= $bucket->getFileInfo('/path/to_file');
if(!$bucket->error) return $bucket->errorMsg;
else var_dump($info);
Parameters
- $file_path : string
-
route to the file taking gs://{bucket_name}/ as the root path
Return values
array<string|int, mixed>|voidgetInfo()
Returns the GCS bucket info of the gs://bucketname you passed in the Object construction
public
getInfo() : array<string|int, mixed>|void
Example of php code
$bucket = $this->core->loadClass('Buckets',"{$bucket_name}");
$bucket->getInfo();
example to array returned
{
"kind": "storage#bucket",
"selfLink": "https://www.googleapis.com/storage/v1/b/{$bucket_name}",
"id": "{id-backet-name}",
"name": "academy-bucket-public",
"projectNumber": "{number of bucket}}",
"metageneration": "2",
"location": "EUROPE-WEST1",
"storageClass": "STANDARD",
"etag": "CAI=",
"timeCreated": "2022-12-16T08:47:07.180Z",
"updated": "2022-12-16T08:47:24.727Z",
"iamConfiguration": {
"bucketPolicyOnly": {
"enabled": true,
"lockedTime": "2023-03-16T08:47:07.180Z"
},
"uniformBucketLevelAccess": {
"enabled": true,
"lockedTime": "2023-03-16T08:47:07.180Z"
},
"publicAccessPrevention": "inherited"
},
"locationType": "region"
}
Return values
array<string|int, mixed>|voidgetMimeTypeFromExtension()
Return the mime type for $extension. If the extension is not found it returns 'application/octet-stream'
public
getMimeTypeFromExtension(string $extension) : string
Example of php code
$bucket = $this->core->loadClass('Buckets',"{$bucket_name}");
if(!$bucket->error) return $bucket->errorMsg;
$mime_type= $bucket->getMimeTypeFromExtension('jpg');
else echo($mime_type);
The list has been got from https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Parameters
- $extension : string
-
is the extension: jpeg,txt,...
Return values
stringgetPublicUrl()
It returns a public URL for the object making it Public you have the rights and the Bucket is Granular
public
getPublicUrl(string $file_path[, string $content_type = '' ]) : string|void
Example of php code
$bucket = $this->core->loadClass('Buckets',"{$bucket_name}");
if(!$bucket->error) return $bucket->errorMsg;
$url= $bucket->getPublicUrl('/path/to_file');
if(!$bucket->error) return $bucket->errorMsg;
else echo($url);
Parameters
- $file_path : string
-
filename path without starting with '/'
- $content_type : string = ''
-
optionally you can set content_type
Return values
string|void —return string public url or void if error
getSignedDownloadUrl()
Provides a temporal signed URL to download an object.
public
getSignedDownloadUrl(string $filename_path[, init $expiration_in_minutes = 1 ][, array<string|int, mixed> $download_options = [] ]) : string|void
More information in https://cloud.google.com/storage/docs/access-control/signing-urls-with-helpers#client-libraries_1
notes:
- if you are using postman send file content as binary.
- you need to use a service account with the right credentials instead a personal credential to avoid the error: Credentials fetcher does not implement Google\Auth\SignBlobInterface
example
$url = $this->bucket->getSignedDownloadUrl('/uploads/video_file',2,['responseDisposition'=>'attachment; filename="myvideo.mp4"'])
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
Parameters
- $filename_path : string
-
file name path to upload the file
- $expiration_in_minutes : init = 1
-
minutes to expire the url. 1 minute by default
- $download_options : array<string|int, mixed> = []
-
[optional] { Available options to update the object.
@type string $responseDisposition Disposition of the file. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition for further information. Exmples: "inline", 'attachment; filename="{filename}"'
}
Return values
string|void —the url to redirect in order to download or access to the object
getSignedUploadUrl()
Provides a PUT-signed URL that is used to upload an object.
public
getSignedUploadUrl(string $upload_file_path[, init $expiration_in_minutes = 15 ]) : string|void
More information in https://cloud.google.com/storage/docs/access-control/signing-urls-with-helpers#client-libraries_1
notes:
- if you are using postman send file content as binary.
- you need to use a service account with the right credentials instead a personal credential to avoid the error: Credentials fetcher does not implement Google\Auth\SignBlobInterface
example
$url = $this->bucket->getSignedUploadUrl('/uploads/video_file')
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
Parameters
- $upload_file_path : string
-
file name path to upload the file
- $expiration_in_minutes : init = 15
-
minutes to expire the url
Return values
string|void —$returnUrl is the url the system has to call once the file has been uploaded
getUploadUrl()
Deprecated method
public
getUploadUrl([string $returnUrl = null ]) : mixed
Parameters
- $returnUrl : string = null
-
is the url the system has to call once the file has been uploaded
Tags
isDir()
tell if path is a dir
public
isDir([string $path = '' ]) : bool
example:
if(!$bucket->isDir('/tmp')){
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
else echo "/tmp does not exist or it is not a dir";
} else echo "/tmp is dir";
Parameters
- $path : string = ''
-
path inside the bucket. If $path starts with gs:// it will try to find the file outside of $this->bucket
Return values
bool —true if the path is dir.
isFile()
Tell if path is a file
public
isFile(string $path) : bool
example:
if($info = $this->bucket->uploadFile('/uploads/image_to_upload.jpg',__DIR__.'/image_to_upload.jpg',['public'=>true])){
var_dump ($info);
} else var_dump ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
Parameters
- $path : string
-
path inside the bucket. If $path starts with gs:// it will try to find the file outside of $this->bucket
Return values
bool —true if the path is file.
manageUploadFiles()
Move files uploaded in $_FILES to temporal space to Bucket $path taking $options
public
manageUploadFiles([string $path = '' ][, array<string|int, mixed> $options = [] ]) : array<string|int, mixed>
example:
if(!$bucket->uploadedFiles) die('there are not files uploaded');
$options = [];
$options['public'] = true; // It tries to make the document public returning "publicUrl" and "mediaLink" attributes in the returned array
$options['apply_hash_to_filenames'] = true; // It rewrites filename with a format: {datetime}_{hash}.{extension} and add "hash_from_name" attribute in the returned array with the original name
$options['allowed_extensions'] = ['jpg'];
$options['allowed_content_types'] = ['image/jpeg'];
$uploaded_files = $this->bucket->manageUploadFiles('/uploads',$options);
if($bucket->error) return $bucket->errorMsg;
else return $uploaded_files;
Parameters
- $path : string = ''
-
optional path to store files uploaded. If it is passed it has to start with '/'
- $options : array<string|int, mixed> = []
-
[optional] {
@type string $public Makes the files to be public @type string $field_name it says only to process documents with the variable $field_name otherwise it processes the document of all variables @type bool $apply_hash_to_filenames change the original name by a hash to avoid duplicated files @type array $allowed_extensions extensions to be allowed in file names: ['jpg','pdf',..] @type array $allowed_content_types content_types allowed to be allowed in file names: ['image','image/jpg','plain/txt',..]
}
Return values
array<string|int, mixed> —the output is an array with the following structure where 'files' if the name of formParms to send the files in this example:
{
"field_name1": [
{
"name": "20221221042421_upload63a9cab5988acf3ccdd27d2000e3f9255a7e3e2c48800.jpg",
"type": "image/jpeg",
"tmp_name": "/private/var/folders/hb/9499jh9s3jd9gx0q68sm5bj80000gn/T/phpG9pBMz",
"error": 0,
"size": 1412041,
"hash_from_name": "1.jpg",
"movedTo": "gs://academy-bucket-mix/uploads/20221221042421_upload63a9cab5988acf3ccdd27d2000e3f9255a7e3e2c48800.jpg",
"publicUrl": "https://storage.googleapis.com/academy-bucket-mix/uploads/20221221042421_upload63a9cab5988acf3ccdd27d2000e3f9255a7e3e2c48800.jpg",
"mediaLink": "https://storage.googleapis.com/download/storage/v1/b/academy-bucket-mix/o/uploads%2F20221221042421_upload63a9cab5988acf3ccdd27d2000e3f9255a7e3e2c48800.jpg?generation=1672071863226633&alt=media"
}],
"field_name2":[
{
"name": "IMAGE1.jpg",
"type": "image/jpeg",
"tmp_name": "/private/var/folders/hb/9499jh9s3jd9gx0q68sm5bj80000gn/T/php3uVF7y",
"error": 0,
"size": 1111558,
"movedTo": "gs://academy-bucket-mix/uploads/20221223042423_upload63a9cab752d3dfa7ea700b267bf1ef4c9f556f17314bd.jpg",
}
]
}
mkdir()
Create a folder inside the bucket. If the folder exist then return true;
public
mkdir(string $path) : bool|void
example:
$created = $bucket->mkdir('/tmp');
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
if($deleted) echo "dir /tmp created";
Parameters
- $path : string
-
path starting with '/' inside the bucket
Return values
bool|void —true if the path is dir and has been created. if there is any error it will return void
putContents()
Create $filename with $data content in $path
public
putContents(string $filename, string $data[, string $path = '' ][, array<string|int, mixed> $options = [] ]) : bool
example:
if(!$bucket->putContents('file.txt','mi content','/tmp',['gs' =>['Content-Type' => 'text/plain'])){
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
else echo "/tmp/file.txt' can no be created";
} else echo "/tmp/file.txt' has been created";
Parameters
- $filename : string
-
name of the file to create
- $data : string
-
Info to put in $file
- $path : string = ''
-
optinal path starting with '/' inside the bucket
- $options : array<string|int, mixed> = []
-
optional to assign file properties taking https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body
- supported values: ['contentType' =>'text/html','metadata'=>['var1'=>,'value1',..]]
Return values
bool —true if the path is file.
rmdir()
Delete a folder inside the bucket
public
rmdir(string $path) : bool|void
example:
$deleted = $bucket->rmdir('/tmp');
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
if($deleted) echo "dir /tmp deleted";
Parameters
- $path : string
-
path starting with '/' inside the bucket
Return values
bool|void —true of the path is dir and has been deleted. if there is any error it will return void
scan()
Execute a scandir over the path and evluate if they are files or directories. If the path is incorrect it will return void. If $path is empty it assumes '/'
public
scan([string $path = '' ]) : array<string|int, mixed>|null|void
example:
$files = $bucket->scan('/');
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
die(json_encode($bucket->fastScan('/'),JSON_PRETTY_PRINT));
output example:
{ "documents": { "type": "dir" }, "images": { "type": "dir" },"image.jpg": {"type":"file"} }
Parameters
- $path : string = ''
Return values
array<string|int, mixed>|null|voidsetFilePrivate()
Set the file as private
public
setFilePrivate(string $file_path) : string|void
example
$bucket->setFilePrivate('/file.txt');
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
Parameters
- $file_path : string
-
file path without gs://
/
Return values
string|void —return string public url or void if error
setFilePublic()
Set the file as publicRead
public
setFilePublic(string $file_path) : string|void
example
$bucket->setFilePublic('/file.txt');
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
Parameters
- $file_path : string
-
file path without gs://
/
Return values
string|void —return string public url or void if error
updateFileObject()
Update File object properties
public
updateFileObject(string $filename_path, array<string|int, mixed> $file_options) : array<string|int, mixed>|void
example:
$filename = 'video.mp4';
$mime_type = $this->bucket->getMimeTypeFromExtension(pathinfo($filename, PATHINFO_EXTENSION));
$options = ['filename'=>$filename,'contentType'=>$mime_type,'public'=>true,'private'=>false];
$object_info =$this->bucket->updateFileObject('/uploads/upload_tmp_file',$options);
if($this->bucket->error) return $this->setErrorFromCodelib($this->bucket->errorCode,$this->bucket->errorMsg);
Parameters
- $filename_path : string
-
file path starting with '/'
- $file_options : array<string|int, mixed>
-
[optional] { Available options to update the object.
@type string $filename We can change the name of the file with this parameter. It can not have '/' char @type string $contentType contentType of the file @type string $contentDisposition Disposition of the file. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition for further information @type string $predefinedAcl defines the access of the file. It can be: "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead" @type bool $public It says the object has to be public and return publicUrl attribute. It equals to ['predefinedAcl'=>'publicRead']. If it is sent with true value then $predefinedAcl is ignored @type bool $private It says the object has to be public and return publicUrl attribute. It equals to ['predefinedAcl'=>'private']. If it is sent with true value then $public and $predefinedAcl are ignored
}
Return values
array<string|int, mixed>|void —return the array with the file properties
example:
{
+ "kind": "storage#object",
id": "{bucket}/uploads/video.mp4/xxxxx",
selfLink": "https://www.googleapis.com/storage/v1/b/{bucket}/o/uploads%2Fvideo.mp4",
mediaLink": "https://storage.googleapis.com/download/storage/v1/b/{bucket}/o/uploads%2Fvideo.mp4?generation=1672201560118273&alt=media",
name": "uploads/video.mp4",
bucket": "{bucket}",
generation": "1672201560118273",
metageneration": "5",
contentType": "video/mpeg",
storageClass": "STANDARD",
size": "1298315450",
md5Hash": "h0KTFOhrEFbwdWqhRBQRkQ==",
cacheControl": "no-cache",
crc32c": "dML25A==",
etag": "CIGo75+8m/wCEAU=",
timeCreated": "2022-12-28T04:26:00.124Z",
updated": "2022-12-28T04:31:15.669Z",
timeStorageClassUpdated": "2022-12-28T04:26:00.124Z",
acl": [
{
kind": "storage#objectAccessControl",
object": "uploads/video.mp4",
generation": "1672201560118273",
id": "{bucket}/uploads/video.mp4/1672201560118273/user-datastore-terminal@cloudframework-io.iam.gserviceaccount.com",
selfLink": "https://www.googleapis.com/storage/v1/b/{bucket}/o/uploads%2Fvideo.mp4/acl/user-datastore-terminal@cloudframework-io.iam.gserviceaccount.com",
bucket": "{bucket}",
entity": "user-datastore-terminal@cloudframework-io.iam.gserviceaccount.com",
role": "OWNER",
email": "datastore-terminal@cloudframework-io.iam.gserviceaccount.com",
etag": "CIGo75+8m/wCEAU="
},
{
kind": "storage#objectAccessControl",
object": "uploads/video.mp4",
generation": "1672201560118273",
id": "{bucket}/uploads/video.mp4/1672201560118273/allUsers",
selfLink": "https://www.googleapis.com/storage/v1/b/{bucket}/o/uploads%2Fvideo.mp4/acl/allUsers",
bucket": "{bucket}",
entity": "allUsers",
role": "READER",
etag": "CIGo75+8m/wCEAU="
}
],
owner": {
entity": "xxxxl@xxxxx.iam.gserviceaccount.com"
},
publicUrl": "https://storage.googleapis.com/{bucket}/video.mp4"
}
uploadContents()
Upload $source_file_path to the bucket with $filename_path
public
uploadContents(string $filename_path, string $contents[, string $options = [] ]) : array<string|int, mixed>
example:
if($info = $this->bucket->uploadContents('/uploads/hello.txt','Hello World',['public'=>true])){
var_dump ($info);
} else var_dump ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
Parameters
- $filename_path : string
-
file name path of the file to create
- $contents : string
-
The contents to upload to the file
- $options : string = []
-
[optional] {
Options to create the object file.
@type bool $public It says the object has to be public and return publicUrl attribute. It equals to ['predefinedAcl'=>'publicRead'] @type string $predefinedAcl defines the access of the file. It can be: "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead" @type array $metadata for the object to create: contentType, cacheControl.. More info in: : https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body
}
Return values
array<string|int, mixed> —with the object created in the bucket
uploadFile()
Upload $source_file_path to the bucket with $filename_path
public
uploadFile(string $filename_path, string $source_file_path[, string $options = [] ]) : array<string|int, mixed>
example:
if(!$bucket->putContents('file.txt','mi content','/tmp',['gs' =>['Content-Type' => 'text/plain'])){
if($bucket->error) return ['errorCode'=>$bucket->errorCode,'errorMsg'=>$bucket->errorMsg];
else echo "/tmp/file.txt' can no be created";
} else echo "/tmp/file.txt' has been created";
Parameters
- $filename_path : string
-
file name path of the file to create
- $source_file_path : string
-
local source file to upload
- $options : string = []
-
[optional] {
Options to create the object file.
@type bool $public It says the object has to be public and return publicUrl attribute. It equals to ['predefinedAcl'=>'publicRead'] @type string $predefinedAcl defines the access of the file. It can be: "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead" @type array $metadata for the object to create: contentType, cacheControl.. More info in: : https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body
}
Return values
array<string|int, mixed> —with the object created in the bucket