Articles tagged with: form

Google - Forms in PHP Without API

on Saturday, 01 October 2011. Posted in All

Get the source code
$1.99

Includes working source code with form, style sheet 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 - Go to Tutorial
  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. - See Tutorial Below

 

Steps:

  1. Create your google form
  2. Preview you form
    example google form
    example google spreadsheet
  3. Copy the form source code
  4. Change the form post action to this custom php script
    example copy of form

 

Video Tutorial

 

 

Code Sample

Note: This is just a basic example without the CSS or captcha. For all my sample code please purchase the package above.

 

googlesandwich.php
//----------------------------------------------------
// Google Form Sandwich
// Created by Jaz Witham (Jazzerup)
// 2011
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND
// Script allows you to write custom php code
// before submitting a form to google
//----------------------------------------------------
//Google Form Key
$formkey = "dFdDTFBFRG1yZm9MckZUanFuM2dEd1E6MQ";
//Email address of person who should get email notification of form submission
$toemail = "
 This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
 ";
$thankyou = "http://www.jazzerup.com/blogexamples/googleform/thankyou.html";
//Change this URL to your google form address
$googleformURL = "https://spreadsheets.google.com/formResponse?formkey=$formkey";
//-----------------Start send email script------------------------
//This is where you would put any custom scripting such as using php to send confirmation emails
$name = $_POST["entry_0_single"];  //Replace the periods in the field name with underscore.
$fromemail = $_POST["entry_1_single"];
$subject = $_POST["entry_2_single"];
$body = $_POST["entry_3_single"];
$header = "From: " . $fromemail . "\r\n";
$header .= "Reply-To: " . $fromemail . "\r\n";
if (!(mail($toemail,$subject,$body,$header))) {
   echo("
<p>Message delivery failed...</p>
 
");
   echo("from email: $fromemail to email: $toemail");
  }
//-----------------End send email script------------------------
 
//----------------Send Form Fields to Google--------------------
//Loops through the form fields and creates a query string to submit to google
foreach ($_POST as $var => $value) {
 
    if ($var != "ignore") {
    $postdata=$postdata . htmlentities(str_replace("_", "." , $var)) . "=" . $value . "&amp;";
    }
}
//remove the extra comma
$postdata=substr($postdata,0,-1);
//Submit the form fields to google
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL,$googleformURL);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$data = curl_exec ($ch);
curl_close($ch);
//echo $data;
//Redirect to your thank you page
header( "Location: $thankyou" ) ;
 



Now that you have a custom form page you can add a captcha to it if you want.
How to add captcha

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";
}