Posted on 2019-02-18

Send HTML Form to Google Sheets using PHP… without Google Forms

  1. Download google-api-php-client (via compose or direct download from https://github.com/googleapis/google-api-php-client/releases)
  2. Create a project on https://console.developers.google.com/apis/dashboard.
  3. Enable APIs, enable the Google Sheets API
  4. Go to Credentials/Create credentials, select "Service account key"

  5. Select New service account. Give the account a name, choose JSON.

  6. For Role choose "Service Account Actor For Key type"
  7. Download the file with credentials, save it on your server
  8. Go to your spreadsheet you want to access and share "Edit" privileges access to the "client_email" address from JSON file from the previous step.


Let's create "apply for a job" web form with 4 fields: email, name, phone, and position.

index.html

<form action="/post2sheet.php" method="post">
  First name: <input type="text" name="name"><br>
  Email: <input type="text" name="email"><br>
  Phone: <input type="text" name="phone"><br>
  Position: <input type="text" name="position"><br>
  <input type="submit" value="Submit">
</form>


post2sheet.php

<?php
// TODO: validate input params, ignore bots...

require __DIR__ . '/vendor/autoload.php'; // google-api-php-client path

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Project');
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS);
    //PATH TO JSON FILE DOWNLOADED FROM GOOGLE CONSOLE FROM STEP 7
    $client->setAuthConfig('PROJECT-NAME-e2262b350d03.json'); 
    $client->setAccessType('offline');
    return $client;
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
$spreadsheetId = '1rPWDc6E0Hreg5mmnM0tIKkEnzN_n1ZMDavYhZM1MhfE'; // spreadsheet Id
$range = 'Sheet1'; // Sheet name

$valueRange= new Google_Service_Sheets_ValueRange();
$valueRange->setValues(["values" => ["a", "b"]]); // values for each cell
$valueRange->setValues(["values" => [
    $_POST["name"]
  , $_POST["email"]
  , $_POST["position"]
  , $_POST["phone"]
  , date("F j, Y, g:i a", time()) 
]]);

$conf = ["valueInputOption" => "RAW"];
$response = $service->spreadsheets_values->append($spreadsheetId, $range, $valueRange, $conf);