title: Upload a file to Google Cloud Storage Bucket with PHP and Ajax
body: <p>I'm working on a PHP project in which I need to upload a file (provided by an HTML form) to the Google Cloud Storage Bucket. The form request will be received as an ajax request. My file is uploading successfully but inside the bucket, it shows a temp file but I have uploaded an image file.</p>
  
  <p>Here's what I have tried:</p>
  
  <p><strong>PHP File:</strong></p>
  
  <pre><code>if(isset($_FILES['file'])){
      $errors= array();
      // Authentication with Google Cloud Platform
      $client = new StorageClient(['keyFilePath' =&gt; 'api-project-374381085870-eaf930d9ffd7.json']);
      $bucket = $client-&gt;bucket('storage_client');
  
      // Upload a file to the bucket.
      $bucket-&gt;upload(
          fopen($_FILES['file']['name'], 'r')
      );
  }
  </code></pre>
  
  <p><strong>Ajax Code:</strong></p>
  
  <pre><code>    $(document).on('submit', '#fileForm', function (e) {
      e.preventDefault();
      var data = new FormData($('#fileForm').get(0));
      $.ajax({
          type: 'POST',
          url: 'gcp_storage.php',
          data: data,
          processData: false,
          contentType: false,
          success: function ($data) {
              console.log('Succcess');
              $('#success').attr('hidden', false);
          }
      });
  });
  </code></pre>
  
  <p><strong>HTML Code:</strong></p>
  
  <pre><code>&lt;form id="fileForm" action="" method="post" enctype="multipart/form-data"&gt;
      &lt;div class="form-row"&gt;
          &lt;br/&gt;
          &lt;div class="form-group"&gt;
              &lt;label for="textFile"&gt;Text File: &lt;/label&gt;
              &lt;br/&gt;
              &lt;input type="file" name="file" id="textFile"&gt;
          &lt;/div&gt;
      &lt;/div&gt;
      &lt;br&gt;
      &lt;button type="submit" class="btn btn-lg btn-primary"&gt; Upload &lt;/button&gt;
  &lt;/form&gt;
  </code></pre>
  
  <blockquote>
    <p>Here's how an image file looks inside bucket:
    <a href="https://i.stack.imgur.com/kXZVA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kXZVA.jpg" alt="The temp file is not formatted in any format, it&#39;s an unformatted file."></a></p>
    
    <p>Update:</p>
  </blockquote>
  
  <p>Now, I have changed:</p>
  
  <p><strong>this:</strong></p>
  
  <pre><code>// Upload a file to the bucket.
      $bucket-&gt;upload(
          fopen($_FILES['file']['name'], 'r')
      );
  </code></pre>
  
  <p><strong>to:</strong></p>
  
  <pre><code>// Upload a file to the bucket.
  $bucket-&gt;upload(
      fopen($_FILES['file']['tmp_name'], 'r')
  );
  </code></pre>
  
  <p>It's uploading the files successfully but the file extension doesn't display inside the bucket. So, is there a way I can rename the file before uploading to google cloud storage bucket?</p>
  
  <p>Help me, please!</p>
  
  <p>Thanks in advance!</p>