Google Cloud Storage Code not working - php

After everything was created in Google Cloud below code was written to upload images from my server to google cloud but i am getting error with google storage class
My upload_gcs.php code below
require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;
if (isset($_FILES) && $_FILES['file']['error']== 0) {
$allowed = array ('png', 'jpg', 'gif', 'jpeg');
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array(strtolower ($ext), $allowed)) {
echo 'The file is not an image.';
die;
}
$projectId = 'photo-upload-205311';
$storage = new StorageClient ([
'projectId' => $projectId,
'keyFilePath' => 'Photo Upload-3af18f61531c.json'
]);
$bucketName = 'photo-upload-205311.appspot.com';
$bucket = $storage->bucket($bucketName);
$uploader = $bucket-> getResumableUploader (
fopen ($_FILES['file']['tmp_name'], 'r'),[
'name' => 'images/load_image.png',
'predefinedAcl' => 'publicRead',
]);
try {
$uploader-> upload ();
echo 'File Uploaded';
} catch (GoogleException $ex) {
$resumeUri = $uploader->getResumeUri();
$object = $uploader->resume($resumeUri);
echo 'No File Uploaded';
}
}
else {
echo 'No File Uploaded';
}
Error which i am getting is below
> Warning: The use statement with non-compound name
> 'GoogleCloudStorageStorageClient' has no effect in upload_gcs.php on
> line 4
>
> Fatal error: Class 'StorageClient' not found in upload_gcs.php on line
> 16
Is my process correct or are there any other ways to upload image from my server to google cloud storage.

The correct namespace for the script has to be used otherwise it's unresolvable. See correction below.
<?php
require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;
class GCPStorage {
function __construct()
{
$projectId = '<your-project-id>';
$bucketName = '<your-bucket-name>';
$storage = new StorageClient([
'projectId' => $projectId,
'keyFilePath' => '<your-service-account-key-file>'
]);
$this->bucket = $storage->bucket($bucketName);
}
function uploadToBucket()
{
if(/your-precondition/) {
return 'No File Uploaded';
}
$uploadedFileLocation = $_FILES['file']['tmp_name'];
$uploader = $this->bucket->getResumableUploader(
fopen($uploadedFileLocation, 'r'),
['name' => 'images/file.txt', 'predefinedAcl' => 'publicRead']
);
try {
$object = $uploader->upload();
} catch(GoogleException $ex) {
$resumeUri = $uploader->getResumeUri();
try {
$object = $uploader->resume($resumeUri);
} catch(GoogleException $ex) {
return 'No File Uploaded';
}
} finally {
return 'File Uploaded';
}
}
}
$gcpStorage = new GCPStorage;
echo $gcpStorage->uploadToBucket();
A small suggestion: assert your precondition early as a guard clause by returning early when it fails.

Related

Problem with upload image to google drive using php

On my site I use google api to upload images in folder. Actually, there is no official documentation from google how to use api using php, only python, js and etc. Current problem is that I get no errors, but file isn't uploading. I'm 100% sure that my service workers work (sorry for such bad english) properly. Below I put my php code for uploading images:
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig('./credentials.json');
$client->setClientId('2445617429-6k99ikago0s0jdh5q5k3o37de6lqtsd3.apps.googleusercontent.com');
$client->setClientSecret('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');
$service = new Google_Service_Drive($client);
//counting amount of files in folder, there is no real reason in doing that
//it is just a test of connecting
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$options = [
'q' => "'" . $folder_id . "' in parents",
'fields' => 'files(id, name)'
];
//printing result
$results = $service->files->listFiles($options);
echo count($results->getFiles());
//trying to add file
$data = file_get_contents("../test.jpg");
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid(). '.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$new_file = $service->files->create($file, [
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
]);
print_r($new_file);
}
This is my standard upload code for uploading.
Try removing 'uploadType' => 'multipart', in your code.
I also cant see you setting the folder id when you upload your file which means its going to root directory.
// Upload a file to the users Google Drive account
try{
$filePath = "image.png";
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$fileMetadata = new Drive\DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
Remember if you are using a service account, files are uploaded to the service accounts drive account unless you add the folder you want to upload the file to.
files list
// Print the next 10 events on the user's drive account.
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
Using the code which was suggested to me, this is full solution.
(Thanks everybody who helped me)
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setClientId('YOUR ID IN SECRET FILE');
$client->setClientSecret(YOUR SECRET IN JSON FILE);
$client->setRedirectUri(YOUR REDIRECT URI);
//you should register redirect uri
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAuthConfig('./credentials.json');
$service = new Google_Service_Drive($client);
try{
$filePath = "../test.jpg";
$folder_id = 'YOUR FOLDER ID';
$fileMetadata = new Google_Service_Drive_DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
}

Using the Google Drive API for PHP, What is the proper way to upload a file while setting the "keepRevisionForever" to true?

I am trying to allow file uploads to overwrite the previous copy and keep the revision history permanent within Google Drive. Also...Do I need to upload with a set ID or is the file name going to overwrite natively?
Here is a sample of what I have as a test function:
function uploadFile($filename = "")
{
$title="testFile";
$description="Testing the upload of the file";
$mimeType="image/jpeg";
$filename = ROOTPATH."IMG_1232.JPG"; //Temporarily overriding $filename for testing.
$file = new Google_Service_Drive_DriveFile();
$file->setName($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$this->startGDService();
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'mimeType' => $mimeType,
'keepRevisionForever' => true // <---This doesn't seem to work.
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return;
}
Looks like I was using the wrong function. The create function will always create a file on the drive. To overwrite a particular file, you need to use the update() function. See here:
function updateFile($filename, $fileID)
{
$this->startGDService();
$filename = UPLOAD_PATH.$filename;
$mimetype = mime_content_type ($filename);
try {
$emptyFile = new Google_Service_Drive_DriveFile();
$data = file_get_contents($filename);
$this->service->files->update($fileID, $emptyFile, array(
'data' => $data,
'mimeType' => $mimetype,
'uploadType' => 'multipart',
'keepRevisionForever' => true
));
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}

Does AWS PHP SDK automatically retry multipart uploads?

Based on the sdk code, the s3 client code uses retry logic, but the sample code from the docs suggest doing a loop until the multipart upload finishes correctly.
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-east-2',
'version' => '2006-03-01'
]);
$bucket = 'your-bucket';
$key = 'my-file.zip';
// Using stream instead of file path
$source = fopen('/path/to/large/file.zip', 'rb');
$uploader = new ObjectUploader(
$s3Client,
$bucket,
$key,
$source
);
do {
try {
$result = $uploader->upload();
if ($result["#metadata"]["statusCode"] == '200') {
print('<p>File successfully uploaded to ' . $result["ObjectURL"] . '.</p>');
}
print($result);
} catch (MultipartUploadException $e) {
rewind($source);
$uploader = new MultipartUploader($s3Client, $source, [
'state' => $e->getState(),
]);
}
} while (!isset($result));
Is that MultipartUploadException being thrown after the standard 3 retries for it have happened? Or are multipart uploads not covered by the retry policy?

PHP Uploading Zero Bytes To S3

I am trying to upload mp3 files to Amazon S3 but for some reason anything I upload is uploaded with a byte length of zero. I cannot seem to figure out why this is happening. I've tried following a tutorial and adjusting the code myself. Any help is appreciated.
<?php
error_reporting(0);
require '../../../../includes/aws-sdk-php/vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
if (isset($_GET['test'])){
if($_GET['test'] == "true"){
include("../../depend.php");
include("../../../../includes/okta-jwt/okta-jwt-functions.php");
include("../../../../includes/aws-s3/functions.php");
$jwtToken = $_GET['token'];
$validateJWT = validateJWT($jwtToken);
echo "$validateJWT";
die();
}
}
include("../../depend.php");
include("../../../../includes/okta-jwt/okta-jwt-functions.php");
if(isset($_POST['episodeTitle'])){
$episodeTitle = $_POST['episodeTitle'];
}
if(isset($_POST['episodeDescription'])){
$episodeDescription = $_POST['episodeDescription'];
}
if(isset($_POST['explicitContent'])){
$explicitContent = $_POST['explicitContent'];
}
if(isset($_POST['episodeShowID'])){
$episodeShowID = $_POST['episodeShowID'];
}
if(isset($_POST['jwtToken'])){
$jwtToken = $_POST['jwtToken'];
}
if(isset($_POST['audioFile'])){
$episodeAudio = $_POST['audioFile'];
}
$validateJWT = validateJWT($jwtToken);
$payloadJSON = json_decode($validateJWT);
$payloadDecoded = $payloadJSON;
$payloadUserID = $payloadDecoded->userID;
//Check if JWT Token Is Valid
if($payloadUserID != 0){
$payloadUserOrgID = $payloadDecoded->userOrgID;
$payloadRole = $payloadDecoded->role;
$payloadExp = $payloadDecoded->exp;
$payloadState = $payloadDecoded->state;
$payloadFirstName = $payloadDecoded->firstName;
$payloadLastName = $payloadDecoded->lastName;
$payloadFullName = $payloadDecoded->fullName;
$episodeStateCode = bin2hex(random_bytes(25));
date_default_timezone_set('UTC');
$showUtcTimestamp = date("Y-m-d H:i:s");
// AWS Info
$bucketName = 'XXX';
$IAM_KEY = 'XXX';
$IAM_SECRET = 'XXX';
// Connect to AWS
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' => 'latest',
'region' => 'us-east-2'
)
);
} 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 = "test_example/" . basename($_FILES["audioFile"]['name']);
// $keyName = "org-$payloadUserOrgID/$episodeStateCode-" . basename($_FILES["audioFile"]['name']);
$keyName = "org-$payloadUserOrgID/$episodeStateCode.mp3";
$pathInS3 = 'https://s3.us-east-2.amazonaws.com/' . $bucketName . '/' . $keyName;
// Add it to S3
try {
// Uploaded:
$file = $_FILES["audioFile"]['tmp_file'];
$s3->putObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName,
'SourceFile' => $file,
'StorageClass' => 'STANDARD'
)
);
} catch (S3Exception $e) {
die('Error:' . $e->getMessage());
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
echo 'Done';
}
?>
I can confirm that the file is being uploaded to S3 but the data in the file is not there. Any help in this would be very much appreciated.

Uploading mp3/zip file to AWS S3 with Pre-signed URL

I am trying to upload .mp3 file to Amazon S3 Server Using this code, i am not getting any resposne from server. On other hand .txt OR .pdf OR .odf file is working fine. What i do for .mp3 and .zip file Structure.
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Common\Aws;
use Aws\Common\Enum\Size;
use Aws\Common\Exception\MultipartUploadException;
use Aws\S3\Model\MultipartUpload\UploadBuilder;
use Aws\S3\Model\ClearBucket;
$buketname = '***********';
$filename = 'first.mp3';
$fileloc = '/var/www/html/aws/aws-sdk-php/first.mp3';
// 1. Instantiate the client.
$s3 = S3Client::factory(array(
'credentials' => array(
'key' => '**************',
'secret' => '**************',
)
));
try {
$result = $s3->putObject(array(
'Content-Type' => 'audio/mpeg',
'Bucket' => $buketname,
'Key' => $filename,
'SourceFile' => $fileloc,
'Metadata' => array(
'Agent' => 'xyz'
)
));
// We can poll the object until it is accessible
$s3->waitUntilObjectExists(array(
'Bucket' => $buketname,
'Key' => $filename
));
echo "File Uploaded : ".$filename;
} catch (\Aws\S3\Exception\S3Exception $e) {
echo $e->getMessage();
}
<?php
ob_start();
/* Amazon A3 */
// Auto Load Things i need
require 'vendor/autoload.php';
// Define Things i will use
use Aws\Common\Aws;
use Aws\Common\Enum\Size;
use Aws\Common\Exception\MultipartUploadException;
use Aws\S3\Model\MultipartUpload\UploadBuilder;
use Aws\S3\Model\ClearBucket;
// Static Variables
$aws_access_key = AWSACCESSKEY; // AWS Access key
$aws_access_security = AWSACCESSSECURITY; // AWS Security Key
$aws_default_buket = AWSDEFAULTBUKET; // Your Default Bucket
$aws_default_region = AWSDEFAULTREGION; // Your Default Region
$aws_default_scema = AWSDEFAULTSCEMA; // Default Protocol Schema
$aws_default_uploadfrom = AWSDEFAULTUPLOADFROM; // File Upload from Directory
// Instantiate the AWS client with your AWS credentials
$aws = Aws::factory(array(
'key' => $aws_access_key,
'secret' => $aws_access_security,
'region' => $aws_default_region,
'scheme' => $aws_default_scema,
));
// Define S3client Object
$s3Client = $aws->get('s3');
$useridfolder = $_REQUEST["useridfolder"];
if(!empty($_FILES['inputFilemp3']['name'])) {
$timestamp = time();
$uploaddir = "mp3uploads/";
$filename = $_FILES['inputFilemp3']['name'];
//$filename = strtolower($filename);
$filename = strip_tags($filename);
//$str = preg_replace('/[\r\n\t ]+/', ' ', $str);
//$str = preg_replace('/[\"\*\/\:\<\>\?\'\|]+/', ' ', $str);
//$str = strtolower($str);
//$str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );
//$str = htmlentities($str, ENT_QUOTES, "utf-8");
//$str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);
//$str = str_replace(' ', '-', $str);
//$str = str_replace('--','-',$str);
//$str = rawurlencode($str);
//$str = str_replace('%', '-', $str);
//$str = str_replace('#', '', $str);
//$str = ltrim($str, '-');
//$filename = preg_replace('/-{2,}/','-',$str);
///new line
$final_location = "mp3uploads/".$useridfolder."/".$timestamp."/".$filename;
/* crete and prepare directories */
/* file type check */
$type = $_FILES["inputFilemp3"]["type"];
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed','audio/mpeg','audio/x-mpeg','audio/mp3','audio/x-mp3','audio/mpeg3','audio/x-mpeg3','audio/mpg','audio/x-mpg','audio/x-mpegaudio');
$okay = false;
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
}
}
if(($okay == false) || ($_FILES["inputFilemp3"]["size"] > 157286400)){
echo "INVALID FILE";
} else{
/* file upload action */
if ($_FILES["inputFilemp3"]["error"] > 0)
{
echo " INVALID FILE";
} else {
$buketname = $aws_default_buket; // Get Bucket name
$filename = $final_location;
$fileloc = $_FILES['inputFilemp3']['tmp_name'];
$fileacl = 'private'; // private | public-read | public-read-write | authenticated-read | bucket-owner-read | bucket-owner-full-control
if(!$buketname || !$filename || !$fileloc || !$fileacl){
echo "Dude! your commands don't seems like they are ok!";
die();
}
try {
$uploader = UploadBuilder::newInstance()
->setClient($s3Client)
->setSource($fileloc)
->setBucket($buketname)
->setKey($filename)
->setConcurrency(3)
->setOption('ACL', $fileacl)
->setOption('Metadata', array('Agent' => 'aisS3Client'))
->setOption('CacheControl', 'max-age=7200')
->build();
// Perform the upload. Abort the upload if something goes wrong
try {
$uploader->upload();
//echo "File Uploaded : ".$filename;
} catch (MultipartUploadException $e) {
$uploader->abort();
//echo "File Did not Uploaded : ".$filename;
}
} catch (\Aws\S3\Exception\S3Exception $e) {
echo $e->getMessage();
}
unlink($_FILES['inputFilemp3']['tmp_name']);
$download_url= AWSDOWNLOADURL.$filename;
echo $download_url = trim($download_url);
}
}
}
?>
Source

Categories