Google Cloud Hosting + File Upload Google Storage in PHP

Joshua Etim
4 min readJun 13, 2021

Google Cloud is a very powerful platform for deploying fast, efficient apps. It provides a wide breadth of features you can use to solve many real problems we face as developers. Just like AWS, you can use it for free — to a limit. Fortunately, that limit is more than enough to host small services and personal projects.

This tutorial will walk you through the steps to deploy a PHP application on Google Cloud. You will also learn how to use Google Cloud for storing files like images from user uploads.

Prerequisites:

  • Active Google Cloud account (create one here)
  • Ensure you have a project created (link)
  • Install and initialize the Cloud SDK on your computer (link)

For Laravel Users

Follow the instructions listed here: https://cloud.google.com/community/tutorials/run-laravel-on-appengine-standard

One additional step to ensure you don’t run into errors:

Run this code in your Laravel folder:

composer remove --dev nunomaduro/collision

For Core PHP users

Create an app.yaml file in your root folder with this content:

runtime: php74
runtime_config: document_root: .
handlers:# Serve a directory as a static resource.- url: /assets static_dir: public/assets# Serve images as static resources.- url: /(.+\.(gif|png|jpg|css|js|map))$ static_files: \1 upload: .+\.(gif|png|jpg|css|js|map)$# Serve your app through a front controller at index.php or public/index.php.- url: .* script: auto

The public/assets section assumes your CSS and image files are located at ‘public/assets/) and your URL points to /assets/{filename}. If this is different, please replace the link accordingly.

The SQL part is identical to the Laravel section. After creating the database, you can also decide to directly hardcode your credentials in your Database object or use an environment variable. Here is an example:

$capsule->addConnection(['driver'    => 'mysql','host'      => '127.0.0.1','port'      => 3306,'unix_socket' => getenv('DB_SOCKET'),'database'  => 'photo', // edit for your unique database name'username'  => '<username>', // generally 'root''password'      => <your password>,'charset'   => 'utf8','collation' => 'utf8_unicode_ci','prefix'    => '','sslmode' => 'require',]);

For the environment variable, add this to the end of your app.yaml file

env_variables:  DB_SOCKET: '/cloudsql/<your connection name>'

So your entire app.yaml file looks like this:

runtime: php74runtime_config:  document_root: .handlers:# Serve a directory as a static resource.- url: /assets  static_dir: public/assets# Serve images as static resources.- url: /(.+\.(gif|png|jpg|css|js|map))$  static_files: \1  upload: .+\.(gif|png|jpg|css|js|map)$# Serve your app through a front controller at index.php or public/index.php.- url: .*  script: auto
env_variables: DB_SOCKET: '/cloudsql/<your connection name>'

Now you can use this command to deploy

gcloud app deploy

(Note: any further error you may get is reflective of your code structure. Please leave a comment if you’re stuck)

Uploading to Google Cloud Storage

Using Google Cloud Storage is recommended when storing important data such as uploaded photos, relevant files, and more. This is because Cloud Storage acts as a CDN (Content Delivery Network) which means it is hosted on multiple proxy servers so that access is faster and reliable to users.

For this tutorial, I will use the Cloud Storage service for users uploading photos in your application.

To begin, install the google cloud storage package for PHP:

composer install google/cloud-storage

Then, go ahead and create a ‘bucket’. A bucket is a small storage unit associated with the project you created. A bucket can contain many ‘objects’ which are basically the files you stored there.

If you have the Cloud SDK installed on your local system, use the command below to create a bucket:

gsutil mb gs://YOUR_BUCKET_NAME

More info on creating buckets is here.

After that, create a file to handle your file uploads. This is a working example:

$storage = new \Google\Cloud\Storage\StorageClient([
'projectId' => 'your-project-id' //use your project id on gcloud
]);

$bucket = $storage->bucket('YOUR_BUCKET_NAME'); //use yours
$file = $_POST['file']; // or any method of accessing your file// get file stream
$stream = fopen($file['tmp_name'], 'r+');
// adding random values to name to avoid duplication
$prefix = substr(microtime(), -4, 4); // unique number generator
$name = $prefix . str_replace(' ', '_', $file['name']); // remove space

// Upload a file to the bucket.
$bucket->upload($stream, [
'name' => $name,
]);

Make your bucket public

To enable your users to access the photos they created, make your bucket available for public access. Run the code on your local system:

gsutil iam ch allUsers:objectViewer gs://YOUR_BUCKET_NAME

More info on that can be found here.

After that, use the Google API link to let your users access the file:

https://storage.googleapis.com/YOUR_BUCKET_NAME/OBJECT_NAME

OBJECT_NAME here refers to the name of the file you created — I would assume you stored it in the database.

Conclusion

Google Cloud Hosting is very robust and can considerably improve your understanding of Cloud Computing. You can also search the web for more tips on Google Cloud or if you’re stuck following the steps above.

I wish you the best development experience.

Cloud API reference for PHP: https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.134.0/storage/storageobject

--

--

Joshua Etim

Software Engineer and Machine Learning Enthusiast.