How do I upload images to the Google Cloud Storage from PHP form?
Asked Answered
S

2

0

I'm currently utilizing a php app to upload images to the Google cloud storage platform, however, unlike on my local server, I am having tremendous trouble figuring out how to make this work.

Here is exactly what I am trying to do:

  1. Write the Path of the image to my Google cloud SQL
  2. Actually upload the image to the Google cloud storage platform
  3. write a script calling on the image, from the saved SQL path, to then post to my site

Can anyone point in the right direction?

Thanks!

Serial answered 5/3, 2014 at 17:55 Comment(3)
Local dev and production dev is not yet the same environment (gae 1.9.0). I presume you have read this: developers.google.com/appengine/docs/php/googlestorageShaefer
I have, but again it seems what I am trying to do is slightly outside the scope of their basic explanation. I would like to know if anyone else on this site was trying, or had tried to do something similar?Serial
It's not clear to me what you're trying to do that isn't explained on the page dennis@ linked.Carillon
B
3

Something like this worked for me with the form on GAE - upload photo from Form via php to google cloud storage given your folder permission are set...

// get image from Form
$gs_name = $_FILES["uploaded_files"]["tmp_name"]; 
$fileType = $_FILES["uploaded_files"]["type"]; 
$fileSize = $_FILES["uploaded_files"]["size"]; 
$fileErrorMsg = $_FILES["uploaded_files"]["error"]; 
$fileExt = pathinfo($_FILES['uploaded_files']['name'], PATHINFO_EXTENSION);

// change name if you want
$fileName = 'foo.jpg';

// put to cloud storage
$image = file_get_contents($gs_name);
$options = [ "gs" => [ "Content-Type" => "image/jpeg"]];
$ctx = stream_context_create($options);
file_put_contents("gs://<bucketname>/".$fileName, $gs_name, 0, $ctx);

// or move 
$moveResult = move_uploaded_file($gs_name, 'gs://<bucketname>/'.$fileName); 

The script to call the image to show on your site is typical mysqli or pdo method to get filename, and you can show the image with...

<img src="https://storage.googleapis.com/<bucketname>/<filename>"/>  
Bathsheeb answered 6/3, 2014 at 16:34 Comment(3)
Excellent my friend. You are a saint. Kudos!Serial
@Gerry Pesavento after image is uploaded, how to rename dynamically the image? How to find image in GCS and change the name and then save it in database? Because if I have 20 images how to know which one shoul be renamed?Thebault
Why speed to retrieving images from bucket is very very slow? And how to improve that?Nashner
E
3

in case anyone may be interested, I made this, only upload a file, quick & dirty:

(I do not want 500+ files from the php sdk just to upload a file)

<?php
/**
 * Simple Google Cloud Storage class
 * by SAK
 */

namespace SAK;

use \Firebase\JWT\JWT;

class GCStorage {
    const 
        GCS_OAUTH2_BASE_URL = 'https://oauth2.googleapis.com/token',
        GCS_STORAGE_BASE_URL = "https://storage.googleapis.com/storage/v1/b",
        GCS_STORAGE_BASE_URL_UPLOAD = "https://storage.googleapis.com/upload/storage/v1/b";
    protected $access_token = null;
    protected $bucket = null;
    protected $scope = 'https://www.googleapis.com/auth/devstorage.read_write';
    


    function __construct($gservice_account, $private_key, $bucket) 
    {
        $this->bucket = $bucket;
        // make the JWT
        $iat = time();
        $payload = array(
            "iss" => $gservice_account,
            "scope" => $this->scope,
            "aud" => self::GCS_OAUTH2_BASE_URL,
            "iat" => $iat,
            "exp" => $iat + 3600
        );
        $jwt = JWT::encode($payload, $private_key, 'RS256');
        // echo "Encode:\n" . print_r($jwt, true) . "\n"; exit;

        $headers = array(
            "Content-Type: application/x-www-form-urlencoded"
        );

        $post_fields = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$jwt";
        // $post_fields = array(
        //     'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        //     'assertion' => $jwt
        // );

        $curl_opts = array(
            CURLOPT_URL => self::GCS_OAUTH2_BASE_URL,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $post_fields,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        // var_dump($curl); exit;
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            die('Error:' . curl_error($curl));
        }
        curl_close($curl);
        $response = json_decode($response, true);
        $this->access_token = $response['access_token'];
        // echo "Resp:\n" . print_r($response, true) . "\n"; exit;
    }

    public function uploadObject($file_local_full, $file_remote_full, $content_type = 'application/octet-stream')
    {
        $url = self::GCS_STORAGE_BASE_URL_UPLOAD."/$this->bucket/o?uploadType=media&name=$file_remote_full";
    
        if(!file_exists($file_local_full)) {
            throw new \Exception("$file_local_full not found.");
        }
    
        // $filesize = filesize($file_local_full);

        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Content-Type: $content_type",
            // "Content-Length: $filesize"
        );

        // if the file is too big, it should be streamed
        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => file_get_contents($file_local_full),
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }

    public function uploadData(string $data, string $file_remote_full, string $content_type = 'application/octet-stream')
    {
        $url = self::GCS_STORAGE_BASE_URL_UPLOAD."/$this->bucket/o?uploadType=media&name=$file_remote_full";
    
        // $filesize = strlen($data);

        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Content-Type: $content_type",
            // "Content-Length: $filesize"
        );

        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }

    public function copyObject($from, $to)
    {
        // 'https://storage.googleapis.com/storage/v1/b/[SOURCEBUCKET]/o/[SOURCEOBJECT]/copyTo/b/[DESTINATIONBUCKET]/o/[DESTINATIONOBJECT]?key=[YOUR_API_KEY]'
        $from = rawurlencode($from);
        $to = rawurlencode($to);
        $url = self::GCS_STORAGE_BASE_URL."/$this->bucket/o/$from/copyTo/b/$this->bucket/o/$to";
        // $url = rawurlencode($url);
        
        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Accept: application/json",
            "Content-Type: application/json"
        );
    
        $payload = '{}';
    
        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);
        // echo '<pre>'; var_dump($response); exit;
        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }

    public function deleteObject($name)
    {
        // curl -X DELETE -H "Authorization: Bearer OAUTH2_TOKEN" "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"
        //
        $name = rawurlencode($name);
        $url = self::GCS_STORAGE_BASE_URL."/$this->bucket/o/$name";
        
        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Accept: application/json",
            "Content-Type: application/json"
        );
    
        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "DELETE",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);
        // echo '<pre>'; var_dump($response); exit;
        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }


    public function listObjects($folder)
    {
        // curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o"
        //
        $folder = rawurlencode($folder);
        $url = self::GCS_STORAGE_BASE_URL."/$this->bucket/o?prefix=$folder";
        
        $headers = array(
            "Authorization: Bearer $this->access_token",
            "Accept: application/json",
            "Content-Type: application/json"
        );
    
        $curl_opts = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
        );
        // echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;

        $curl = curl_init();
        curl_setopt_array($curl, $curl_opts);
    
        $response = curl_exec($curl);
        // echo '<pre>'; var_dump($response); exit;
        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            throw new \Exception($error_msg);
        }

        curl_close($curl);

        return $response;
    }

}

Evenfall answered 22/8, 2020 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.