javascript - Upload files to Google Cloud Storage Bucket using PHP


I've searched a lot (and even found some helpful links like this one Upload a file to Google Cloud Storage Bucket with PHP and Ajax) but I couldn't get it working. I need to upload a txt file to my google cloud storage bucket.

Here's my code:



    $errors= array();
    // Authentication with Google Cloud Platform
    $client = new StorageClient(['keyFilePath' => 'cloudtest-2412**-a66e94ba56**.json']);
    $bucket = $client->bucket('cloudtest-2412** ');

    // Upload a file to the bucket.
    $file = pathinfo($_FILES['file']['name']);
    $prefix = uniqid('prefix_', true); //generate random string to avoid name conflicts
    $filename = $prefix . "." . $file['extension'];

      fopen($_FILES['file']['tmp_name'], 'r'),
      ['name' => $filename]


html and js:

<form id="fileForm" action="" method="post" enctype="multipart/form-data">
  <div >
    <div >
      <label for="textFile">Text File: </label>
      <input type="file" name="file" id="textFile">
  <button type="submit" > Upload </button>




  $(document).on('submit', '#fileForm', function (e) {
  var data = new FormData($('#fileForm').get(0));
    type: 'POST',
    url: 'gcp_storage.php',
    data: data,
    processData: false,
    contentType: false,
    success: function ($data) {
      $('#success').attr('hidden', false);


*It shows on my console success but when I go to my bucket on google cloud, nothing appears...

*I downloaded the .json file from the IAM page (the file is in the same directory as the other filse)


Don't know if this really helps, if I remove theuse Google\Cloud\Storage\StorageClient, PHP throws me the errorClass 'StorageClient' not found in /base/data/home/apps/i (when I put back the use code it just throws the 500 error, see below)

I've been changing the code and putting breakpoints to see if I find where the 500 error is coming from. If I remove everything from my PHP file and just putecho "Test", it works fine.

After putting some breakpoints at the original code, I found out that the 500 error comes from this lines of code:

$client = new StorageClient(['keyFilePath' => 'cloudtest-2412**-a66e94ba56**.json']);
$bucket = $client->bucket('cloudtest-2412**');

(The authentication code)

Any suggestions?





I think, we can see a permission error. In most cases, an internal 500 server error is due to incorrect permission in one or more files or folders.

Please try with this steps:

People are also looking for solutions to the problem: php - Transforming SQL query using Doctrine Query Builder


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.