joshhunt joshhunt - 4 months ago 21
PHP Question

Requesting images from Google Cloud makes page extremely slow

I am making a PHP Google App Engine site and I've found that requesting images from the Google Cloud service makes the page load extremely slow.

Without loading in the images it takes around 0.5s for the page to load and with the images it takes 10-15s. I assume I am doing something wrong so any help would be much appreciated.

See this example.

My Code

require_once "google/appengine/api/cloud_storage/CloudStorageTools.php";
use google\appengine\api\cloud_storage\CloudStorageTools;

...

function cloudStorageUrl($url, $size, $crop) {
if (file_exists($url)) {
$object_image_url = CloudStorageTools::getImageServingUrl($object_image_file, ['size' => $size, 'crop' => $crop]);
return $object_image_url;
}
else {
return false;
}
}

Answer

As suggested by Paul & Stuart I solved this issue by creating a table in Google Cloud SQL where I could store the url returned from Google Cloud Storage so that I didn't have to repeatedly request the url.

Code Example

// Cloud Storage URL function
function cloudStorageUrl($url, $size, $crop) {
    if (file_exists($url)) {
        $object_image_url = CloudStorageTools::getImageServingUrl($object_image_file, ['size' => $size, 'crop' => $crop]);
        return $object_image_url;
    } else {
        return 'none';
    }
}

// Connect to database
$db = new pdo('mysql:unix_socket=/cloudsql/<your-project-id>:<your-instance-name>;dbname=guestbook', 'root', '');

foreach($db->query('SELECT * FROM `images` WHERE `id`="'.$id.'"') as $row) {
    // Check if Cloud Storage URL already exists
    if ($row['url'] && $row['url'] !== 'none') {
        $url = $row['url'];
    } else {
        // Get the Cloud Storage URL and save it
        $url = cloudStorageUrl($row['cloud_storage_location'], 400, false);
        $stmt = $db->prepare('INSERT INTO `images` (id, url) VALUES (:id, :url ON DUPLICATE KEY UPDATE url=VALUES(url))');
        $stmt->execute(array(':id' => intval($id), ':url' => htmlspecialchars($url)));
    }
}