简体   繁体   中英

How to stop upload to Google Cloud Storage if file already exists using PHP?

I'm having a problem with GAE and GCS.

I'm trying to upload a file, which works - but I can't seem to stop the upload if the file already exists. It just gets a random temp name.

I have this code, but it doesn't do the job.

<?php
require_once 'google/appengine/api/cloud_storage/CloudStorageTools.php';
use google\appengine\api\cloud_storage\CloudStorageTools;

SESSION_START();

$gs_new_name = $_FILES["uploaded_files"]['name'];
$image = CloudStorageTools::getPublicUrl("gs://bucket/".$gs_new_name, true);

if(getimagesize($image) !== FALSE){
    $gs_name = $_FILES["uploaded_files"]['tmp_name'];
    move_uploaded_file($gs_name, "gs://bucket/".$gs_new_name);
} else{
    die();
}

?>

It is not possible to stop an upload to GCS through PHP. When uploading directly to GCS via CloudStorageTools::createUploadUrl() the entire HTTP request is sent to the GCS proxy which handles the upload and then forwards the request back to your App Engine application. At that time PHP adds the location of the upload file on GCS to the $_FILES array. As such the current approach of executing die() would not work since the entire upload has already been performed prior to the execution of your script.

Short of checking client side (via JavaScript) for a particular filename/extension (plenty of topics on that) I am not sure how you would do something like this. I am also not entirely sure what you are trying to accomplish. Are you simply looking to restrict files to image types only? If so checking the extension on client side and then performing a check similar to the one you have should do the trick. Only instead of calling die() you could call unlink($gs_name) to remove the temporary file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM