Articles tagged with: spreadsheet

Google - Forms API Using PHP

on Saturday, 12 November 2011. Posted in All

Get the source code
$1.99

Includes examples, working source code with forms, style sheet, spreadsheet sample and recaptcha integration

Have you ever wanted to do the following?

  • Embed a google form into your site without using iframes?

  • Control the thank you page of your google form?
  • Send out confirmation emails to the user who submitted the form or to people who should receive the google form data?

  • Attach a file to your form?

  • Setup a captcha script on your google form?

 

There are two ways to accomplish this:

  1. Use the Google API - Tutorial Below
  2. Use a PHP curl function to submit to the form but you have to make your form public so you can access it anonymously from your curl script. - Go to Tutorial

 

Step 1 - Install PHP, Zend & Google API Libraries

To get started you will need PHP, Zend and the Gdata Zend Libraries installed on your web server. Google has an excellent tuttorial on how to do it with special scripts to check if your installation was successful.

Google API ZEND PHP Getting Started Tutorial

Here are the Highlights:

  1. Install PHP (run phpinfo to ensure itsuccessfully installed)
  2. Download Google Zend Library (Zend Gdata Downloads)
  3. Rename the folder to ZendGdata
  4. Upload the ZendGdata folder to your website
  5. Update your php.ini file include path to point to the installation of your ZendGdata library folder.
    include_path = ".:/usr/lib/php:/usr/local/lib/php:/yourpath/toyour/ZendGdata/library"
    (Note: On Unix paths are colon delimited and on windows they are semicolon delimited)
  6. Run the php installation checker to ensure your library is setup correctly

Now ASSUMING you have zend and php working then congratulations, the difficult part is done!

 

Step 2 - Create your Google Form

Create your Google Form and save the form to your desktop or build an html form from scratch.

Want a head start? You can use the Google Docs Template that I created for this tutorial.



 

The form fields on your web page will need to match your column headers in your google spreadsheet BUT it has to be all lower case and no space.

 

Google Forms API Tutorial

 

Example: If your column name is "First Name" then your field name needs to be "firstname"

Have your form action do a post to the "googlesandwich.php" page

<form action="googlesandwich.php" method="POST" enctype="multipart/form-data" id="ss-form"></form>

 

 

Step 3 - Create your Google Sandwich Page

A Google sandwich page is the page you submit your form to. It does all the hard work and then redirects to a thank you page.

 

Example 1 - Submit to Google Spreadsheet

Copy this code and paste into a googlesandwich.php page. Change the variables at the top to match your information.

 

googlesandwich_basic.php
 
//----------------------------------------------------
// Google Form Sandwich
// Created by Jaz Witham (Jazzerup)
// 2011
// http://www.jazzerup.com
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND
// Script uses the Google API to save values of a form into
// a Google Spreadsheet
//----------------------------------------------------
 
 
// Gmail email address and password for google spreadsheet
$user = "
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
 ";
$pass = "yourpassword";
 
// Google Spreadsheet ID (You can get it from the URL when you view the spreadsheet)
$spreadsheetKey = "0AqPXsH_13gn4dFpaelRsN2RZOXlDd1Zvdzk2OGV3S1E";
 
// od6 is the first worksheet in the spreadsheet
$worksheetID = "od6";
 
// Redirect to your thank you page
$thankyou = "../thankyou.html";
 
//-----------------------------------------------------------
// No need to edit below unless you're a hacker =)
//-----------------------------------------------------------
 
// Include the loader and Google API classes for spreadsheets
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Gdata_Docs');
 
// Authenticate ourselves with Google Docs and create a Zend_Gdata_Spreadsheets object.
$authService = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService);
$spreadsheetService = new Zend_Gdata_Spreadsheets($httpClient);
 
foreach ($_POST as $var => $value) {
//Populate the form values into an array to save to the google spreadsheet
      $FormData[$var] = $value;
} 
 
// Save your form data to your Google spreadsheet
$insertedListEntry = $spreadsheetService->insertRow($FormData, $spreadsheetKey, $worksheetID);
 
//Redirect to your thank you page
header( "Location: $thankyou" ) ;
 
 
 

 

Example 2 - Submit to Google Spreadsheet and Upload Attachment to Google Docs

This form will submit the form values to a spreadsheet and also upload a file to google docs

 
//----------------------------------------------------
// Google Form Sandwich
// Created by Jaz Witham (Jazzerup)
// 2011
// http://www.jazzerup.com
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND
// Script uses the Google API to save values of a form into
// a Google Spreadsheet and uploads file to Google Docs
//----------------------------------------------------
 
// Gmail email address and password for google spreadsheet
$user = "
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
 ";
$pass = "yourpassword";
 
// Google Spreadsheet ID (You can get it from the URL when you view the spreadsheet)
$spreadsheetKey = "0AqPXsH_13gn4dEJCc3VieGFkbWNsUGNMSkdFbVFLdEE";
 
// od6 is the first worksheet in the spreadsheet
$worksheetID="od6";
 
// Redirect to your thank you page
$thankyou = "../thankyou.html";
 
//-----------------------------------------------------------
// No need to edit below unless you're a hacker =)
//-----------------------------------------------------------
 
// Include the loader and Google API classes for spreadsheets
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Gdata_Docs');
 
//-----------------------------------------------------------
// Part One - Connect to our Google Spreadsheet
//-----------------------------------------------------------
// Authenticate ourselves with Google Docs and create a Zend_Gdata_Spreadsheets object.
$authService = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService);
$spreadsheetService = new Zend_Gdata_Spreadsheets($httpClient);
 
foreach ($_POST as $var => $value) {
  //Populate the form values into an array to save to the google spreadsheet
      $FormData[$var] = $value;
} 
 
// Give your file a unique name
$useruploaded = $FormData["yourname"];
$fileToUpload = $_FILES['attachment']['name'];
$dateuploaded = date("ymd_Hi", time());
 
// The file a unique name will be the user who uploaded, the file name and the date uploaded.
$filenewname = $useruploaded .  " - " . $fileToUpload . " - " . $dateuploaded;
 
// push the attachment to the bottom of the array so it shows up in your spreadsheet
$FormData["attachment"] = $filenewname;
 
// Save your form data to your Google spreadsheet
// Save your form data to your Google spreadsheet
$insertedListEntry = $spreadsheetService->insertRow($FormData, $spreadsheetKey, $worksheetID);
 
//-----------------------------------------------------------
// Part Two - Upload Attached File to Google Docs
//-----------------------------------------------------------
$fileToUploadTemp = $_FILES['attachment']['tmp_name'];
$content_type = $_FILES['attachment']['type'];
 
 
//-----------------------------------------------
// Upload File
//-----------------------------------------------
// Upload the file and convert it into a Google Document. 
// With this version of the API you can only upload certain files
// csv, txt, doc, docx, xls, xlsx,ppt, pptx   
 
$service = Zend_Gdata_Docs::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$docs = new Zend_Gdata_Docs($client);
 
// Find out the file mimetype
$filenameParts = explode('.', $fileToUpload);
$fileExtension = end($filenameParts);
 
// Upload the file to google docs
$newDocumentEntry = $docs->uploadFile($fileToUploadTemp, $filenewname, Zend_Gdata_Docs::lookupMimeType($fileExtension), Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI);
 
// Redirect to your thank you page
header( "Location: $thankyou" ) ;
 
 

 

Example 3 - Submit to Google Spreadsheet and Upload Attachment to Your Web Site

This form will submit the form values to a spreadsheet and also upload a file to a folder on your web site

 
 
//----------------------------------------------------
// Google Form Sandwich
// Created by Jaz Witham (Jazzerup)
// 2011
// http://www.jazzerup.com
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND
// Script uses the Google API to save values of a form into
// a Google Spreadsheet and uploads file to your web server
//----------------------------------------------------
 
// Gmail email address and password for google spreadsheet
$user = "
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
 ";
$pass = "yourpassword";
 
// Google Spreadsheet ID (You can get it from the URL when you view the spreadsheet)
$spreadsheetKey = "0AqPXsH_13gn4dEJCc3VieGFkbWNsUGNMSkdFbVFLdEE";
 
// od6 is the first worksheet in the spreadsheet
$worksheetID="od6";
 
// Redirect to your thank you page
$thankyou = "../thankyou.html";
 
// Path to your web folder for saving the attachment.  This folder needs to have 777 permissions on it.
$webfolder = "/path/to/your/webfolder/";
 
//-----------------------------------------------------------
// No need to edit below unless you're a hacker =)
//-----------------------------------------------------------
 
// Include the loader and Google API classes for spreadsheets
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Gdata_Docs');
 
//-----------------------------------------------------------
// Part One - Connect to our Google Spreadsheet
//-----------------------------------------------------------
// Authenticate ourselves with Google Docs and create a Zend_Gdata_Spreadsheets object.
$authService = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService);
$spreadsheetService = new Zend_Gdata_Spreadsheets($httpClient);
 
foreach ($_POST as $var => $value) {
  //Populate the form values into an array to save to the google spreadsheet
      $FormData[$var] = $value;
} 
 
// Give your file a unique name
$useruploaded = $FormData["yourname"];
$fileToUpload = $_FILES['attachment']['name'];
$dateuploaded = date("ymd_Hi", time());
 
// The file a unique name will be the user who uploaded, the file name and the date uploaded.
$filenewname = $useruploaded .  " - " . $fileToUpload . " - " . $dateuploaded;
 
// push the attachment to the bottom of the array so it shows up in your spreadsheet
$FormData["attachment"] = $filenewname;
 
// Save your form data to your Google spreadsheet
// Save your form data to your Google spreadsheet
$insertedListEntry = $spreadsheetService->insertRow($FormData, $spreadsheetKey, $worksheetID);
 
//-----------------------------------------------------------
// Part Two - Upload Attached File to Google Docs
//-----------------------------------------------------------
$fileToUploadTemp = $_FILES['attachment']['tmp_name'];
$content_type = $_FILES['attachment']['type'];
 
//-----------------------------------------------
// Upload File
//-----------------------------------------------
// Upload the file to your web server
 
 
if ($_FILES['attachment']['error'] > 0)
    {
    echo "An error has occurred.";
    echo "Error Code: " . $_FILES['attachment']['error'];
    }
 else
    {
 
    move_uploaded_file($_FILES['attachment']['tmp_name'],
    $webfolder . $filenewname);
  }
 
// Redirect to your thank you page
header( "Location: $thankyou" ) ;
 
 

 

Example 4 - Submit to Google Spreadsheet and Send Email with Attached File

This form will submit the form values to a spreadsheet and also send an email with an attached file

 
//----------------------------------------------------
// Google Form Sandwich
// Created by Jaz Witham (Jazzerup)
// 2011
// http://www.jazzerup.com
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND
// Script uses the Google API to save values of a form into
// a Google Spreadsheet and sends an email with attachment
//----------------------------------------------------
 
// Gmail email address and password for google spreadsheet
$user = "
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
 ";
$pass = "yourpassword";
 
// Google Spreadsheet ID (You can get it from the URL when you view the spreadsheet)
$spreadsheetKey = "0AqPXsH_13gn4dFpaelRsN2RZOXlDd1Zvdzk2OGV3S1E";
 
// od6 is the first worksheet in the spreadsheet
$worksheetID="od6";
 
// Redirect to your thank you page
$thankyou = "../thankyou.html";
 
/*
If you want it to go to multiple recipients then make a comma delimited list
"
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
  , 
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
  , 
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
 "
*/
$mail_to = "
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
 ";
$from_mail = "
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
 ";
$from_name = "Name";
$reply_to =  "
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
 ";
$subject = $_POST['subject'];
$message = $_POST['message'];
 
// Include the loader and Google API classes for spreadsheets
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Gdata_Docs');
 
//-----------------------------------------------------------
// Part One - Connect to our Google Spreadsheet
//-----------------------------------------------------------
// Authenticate ourselves with Google Docs and create a Zend_Gdata_Spreadsheets object.
$authService = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService);
$spreadsheetService = new Zend_Gdata_Spreadsheets($httpClient);
 
foreach ($_POST as $var => $value) {
  //Populate the form values into an array to save to the google spreadsheet
  $FormData[$var] = $value;
} 
 
// push the attachment to the bottom of the array so it shows up in your spreadsheet
$FormData["attachment"] = $_FILES['attachment']['name'];
 
// Save your form data to your Google spreadsheet
$insertedListEntry = $spreadsheetService->insertRow($FormData, $spreadsheetKey, $worksheetID);
 
 
//Redirect to your thank you page
header( "Location: $thankyou" ) ;
 
//-----------------------------------------------------------
// Part Two - Send Email with Attachment
//-----------------------------------------------------------
 
// Attachment Information
$file_name = $_FILES['attachment']['name'];
$path = $_FILES['attachment']['tmp_name'];
 
// Read the file content
$file = $path;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
 
// Generate a boundary
$boundary = md5(uniqid(time()));
 
// Email header
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$reply_to."\r\n";
$header .= "MIME-Version: 1.0\r\n";
 
// Multipart wraps the Email Content and Attachment
$header .= "Content-Type: multipart/mixed; boundary=\"".$boundary."\"\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$boundary."\r\n";
 
 
// Content-type can be text/plain or text/html
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= "$message\r\n";
$header .= "--".$boundary."\r\n";
 
// Attachment
// Edit content type for different file extensions
$header .= "Content-Type: application/xml; name=\"".$file_name."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$header .= $content."\r\n";
$header .= "--".$boundary."--";
 
// Send email
if (mail($mail_to, $subject, "", $header)) {
  // Redirect to your thank you page
  $thankyou = "../thankyou.html";
} else {
  echo "Error";
}