Articles tagged with: php

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

 

Google - Spreadsheets API php Zend Tutorial

on Wednesday, 09 November 2011. Posted in All

Viewing your Spreadsheet data while keeping your spreadsheet private

So you want to customize your google forms and spreadsheet but you do not understand the Google API instructions? Welcome to my club =)

The advantage of using the API instead of PHP CURL is that you do not have to make your spreadhseet data public so it is more secure.

After a few hours I was finally able to piece together everything I needed to get started with the Google API and hopefully I can save you painstaking hours of hair pulling trying to get code that will work on your site.

To get the Google API to work with PHP you need the Zend Framework installed. Don't hypervenilate yet, it's not that difficult.

For detailed instructions on getting the Google API to work with Zend I highly recommend checking out this site.

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!

Let us start with displaying all the data in your spreadsheet


demo

//----------------------------------------------------
// Google Spreadsheets API PHP Tutorial
// Created by Jaz Witham (Jazzerup)
// 2011
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND
// Script allows you to connect to a google spreadsheet via
// the google php zend api
//----------------------------------------------------
 
// 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 = "your email password";
 
// Google Spreadsheet ID (You can get it from the URL when you view the spreadsheet)
$GSheetID = "0AqPXsH_13gn4dGsxbVZpc1JvYWJZd3JjWGxxbXlSSnc";
 
// od6 is the first worksheet in the spreadsheet
$worksheetID="od6";
 
// Include the loader and Google API classes for spreadsheets
require_once('Zend/Loader.php');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Http_Client');
 
// Authenticate on Google Docs and create a Zend_Gdata_Spreadsheets object.            
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
 
// The function will echo out a list of spreadsheets in your account            
function DisplaySpreadsheets($feed)
{
    $i = 0;
    foreach($feed->entries as $entry) {
        if ($entry instanceof Zend_Gdata_Spreadsheets_CellEntry) {
        echo $entry->title->text .' '. $entry->content->text . "
";
    } else if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) {
        echo $i .' '. $entry->title->text .' '. $entry->content->text . "
";
    } else {
        echo $i .' '. $entry->title->text . "
";
    }
    $i++;
    }
}
 
//The function will create a table of the data from your spreadsheet  
function DisplayWorksheetData($feed)
{
    echo ''; $rowData = $feed->entries[0]->getCustom(); echo ""; echo ''; foreach($rowData as $customEntry) { echo ""; } echo ""; $i = 2; // the first row of content is row 2 foreach($feed->entries as $row) { echo ""; $i++; $rowData = $row->getCustom(); foreach($rowData as $customEntry) { echo ""; } echo ""; } echo '
<table style="width: 200px;" border="1">
<tbody>
<tr>
<td>Row Number</td>
<td>" . $customEntry->getColumnName() . "</td>
</tr>
<tr>
<td>" . "Row " . $i .' '. $row->title->text . "</td>
<td>" . $customEntry->getText(). "</td>
</tr>
</tbody>
</table>
';
}
 
// First echo a list of your Google Spreadsheets
 
$feed = $spreadsheetService->getSpreadsheetFeed();
echo "
<h1>List of all your Spreadsheets</h1>
";
DisplaySpreadsheets($feed);
 
// echo the content of a specific Spreadsheet/Worksheet
// set a query to return a worksheet and echo the contents of the worksheet
 
$query = new Zend_Gdata_Spreadsheets_ListQuery();
$query->setSpreadsheetKey($GSheetID);
$query->setWorksheetId($worksheetID);
$listFeed = $spreadsheetService->getListFeed($query);
 
echo "
 
";
echo "
<h1>List of data in your Spreadsheet</h1>
";
DisplayWorksheetData($listFeed);
 

Dynamic Nav Bar Based on Files in Folder

on Wednesday, 12 October 2011. Posted in All

Get the source code
$1.99

Includes working php source code with images, style sheet and javascript.

Thie php script automatically generates a navigation menu based on the pages in the same directory.

The php script does the following:


  • Loops through all the files in the directory looking for php, html and htm files
  • Uses the PHP Simple HTML DOM Parser to find the page h2 title with id="maintitle"
    Note: you can set it to find any tag on the page
  • It stores the page title and the page URL
  • It alphabetizes the pages and displays the into a <li> list
  • Using jQuery the current <li> item class is set to "active"

Demo uses a modified version of a free template from CSS Heaven


Also made the loopedslider dynamic so it dynamically grabs all the images in the slideshow directory and reads the image metadata for the title and text.


demo


In order for the example to work below you will need to add the following code to each of your web pages. This is what the script looks for and makes it the text part of the sidebar links

 
  <h2 id="maintitle">Your Title</h2>
 

Here is the auto navigation script. I recommend putting it into an include file on all your pages.

auto_navigation.php
<!--
//----------------------------------------------------
// Auto Navigation Scripts
// Created by Jaz Witham (Jazzerup)
// 2011
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND
// Script reads the php, htm and html files in a directory
// and builds a navigation bar.
//----------------------------------------------------
-->
<?php
include 'simple_html_dom.php';
 
//Webite URL to that current directory
$dirURL =  dirname("http://" . $_SERVER['HTTP_HOST']  . $_SERVER['REQUEST_URI']);
 
//get the current folder you are in
$dirpath = getcwd();
 
$folder = opendir($dirpath);
$file_types = array("php", "htm", "html");
$index = array();
$filelist = array();
 
//Loop through the files in the directory
while ($file = readdir ($folder)) {
  if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$file_types))
      {                   
    $html = file_get_html("$dirpath/$file");
  //Checking for a homepage so it always displays first int he list and is not alphabetized with the rest of the files.
  if ($file == "index.php"){
    //$homepgtime = $html->find('h2[id=maintitle]',0)->plaintext;
    $homepgtime = "Home";    
  }else{    
    $filelist[] = array('mytitle' => $html->find('h2[id=maintitle]',0)->plaintext, 'mypath' => $dirURL . "/" . $file);
  }
    }
}
 
//array to sort a 2-dimentional array
function array_qsort2 (&$array, $column=0, $order="ASC") {
  $oper = ($order == "ASC")?">":"<"; 
  if(!is_array($array)) return;
  usort($array, create_function('$a,$b',"return (\$a['$column'] $oper \$b['$column']);")); 
  reset($array);
}
array_qsort2($filelist, "mytitle", "ASC");
 
//Build the <li> list.  The homepage always listed first
echo "<li><a href='index.php' accesskey='1'>$homepgtime</a></li>";
 
$j = 1;
//Loop through the rest of the files
for($i=0; $i<sizeof($filelist); $i++) {
$j = $j + 1;  
  echo "<li><a href='" . $filelist[$i]['mypath'] . "' accesskey='$j'>" .$filelist[$i]['mytitle'] . "</a></li>";
  }
//clean up
closedir($folder);
 
?>
 
 



This jQuery will add the "active" class to the current item in your navigation

 
<script type="text/javascript">
$(document).ready(function(){     
  var str = $("#maintitle").text();    
  $('.nav').children().each(function(){
  if (str == $(this).text()) {
    $(this).addClass('active');
  } else { 
    $(this).removeClass('active') }
  });
});
</script>
 

jQuery Carousel - Images From Folder

on Tuesday, 11 October 2011. Posted in All, Slideshow

Get the source code
$1.99

Includes working source code with images, style sheet and javascript.

One of my favorite free jquery slideshow scripts is Jquery Carousel Lite

The major problem I had with the script is everytime I wanted to add another picture to the slideshow, I had to modify the jquery code to include that image. I wrote a script that will do the following:


1) Automatically lists the image files inside a directory and load them into your jquery carousel.


2) Reads the picture metadata and adds it to the jquery carousel script


  • Metadata: Title becomes the Image Alt Tag
  • Metadata: Subject becomes the Image Link URL
  • Metadata: Comments becomes the Caption

demo


carouselexample.php
//----------------------------------------------------
// jQuery Carousel Enhancement
// Created by Jaz Witham (Jazzerup)
// 2011
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND
// Script reads the image files and 
// image metadata into the jQuery Carousel Script
//----------------------------------------------------
 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script> 
<script src="js/jcarousellite_1.js" type="text/javascript"></script>
</head>
<body>
<!-- Carousel -->
<div id="carousel"> <a href="#" title="Previous" class="prev">Previous</a> <a href="#" title="Next" class="next">Next</a>
  <div style="visibility: visible; overflow: hidden; position: relative; z-index: 2; left: 0px; width: 864px;" class="content">
    <ul style="margin: 0pt; padding: 0pt; position: relative; list-style-type: none; z-index: 1; width: 2592px; left: -864px;">
 
<?php 
//Relative path to yout image directory
$dirpath = "../slideshow";
//Website URL to that same image directory
$dirURL = "http://www.jazzerup.com/blogexamples/slideshow/";
 
$folder = opendir($dirpath);
$pic_types = array("jpg", "jpeg");
$alttag = ""; 
$websiteurl= ""; 
$caption = ""; 
$index = array();
 
//Loop through the images in the directory
while ($file = readdir ($folder)) {
  if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$pic_types))
      {                       
      $items[] = $file;            
    }
}
//each time it loads it shuffles the images
shuffle($items);
for($i=0; $i<sizeof($items); $i++) {
  $picpath = $dirpath . "/" . $items[$i];
  $exif = exif_read_data($picpath, 'EXIF');
  $alttag = $exif['Title']; //alt tag
  $websiteurl= $exif['Subject']; //website url
  $caption = $exif['Comments']; //caption
 
  $varimages = $varimages . "<li style='overflow: hidden; float: left; width: 216px; height: 136px;'>";
 
//Build the html code based on the metadata 
  $varimages =  $varimages . " <img src='$picpath' height='120' width='200' style='border:3px solid #FFF;' alt='$alttag' />" . "\n\n" ;
 
  $alttag = ""; 
  $websiteurl= ""; 
  $caption = "";
  $varimages =  $varimages . "</li>";
 }
closedir($folder);
 
echo $varimages;
?>
    </ul>
  </div>
</div>
<!-- [END] Carousel --> 
<script type="text/javascript">
    $(window).load(function() {
 
      $("#carousel .content").jCarouselLite({
          btnNext: ".next",
          btnPrev: ".prev",
          speed: 800,
          visible: 4
      });
 
 
    });
    </script>
</body>
 

jQuery Nivo Slider - Images From Folder

on Sunday, 02 October 2011. Posted in All, Slideshow

Get the source code
$1.99

Includes working source code with images, style sheet and javascript.

One of my favorite free jQuery slideshow scripts is Nivo Slider

The major problem I had with the script is everytime I wanted to add another picture to the slideshow, I had to modify the jquery code to include that image. I wrote a script that will do the following:


1) Automatically lists the image files inside a directory and load them into your nivo slider.


2) Reads the picture metadata and adds it to the Nivo script


  • Metadata: Title becomes the Nivo Image Alt Tag
  • Metadata: Subject becomes the Nivo Image Link URL
  • Metadata: Comments becomes the Nivo Caption

demo

nivoexample.php
<!--
//----------------------------------------------------
// Nivo Slider Enhancement
// Created by Jaz Witham (Jazzerup)
// 2011
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND
// Script reads the image files and 
// image metadata into the nivo slider script
//----------------------------------------------------
-->
<body>
<div id="wrapper"> 
  <div class="slider-wrapper theme-default">
    <div class="ribbon"></div>
    <div id="slider" class="nivoSlider">
<?php 
//This php code will generate your list of images based on 
//image files in a folder
 
$dirpath = "slideshow";
$dirURL = "http://www.jazzerup.com/blogexamples/slideshow/";
$folder = opendir($dirpath); // Use 'opendir(".")' if the PHP file is in the same folder as your images. Or set a relative path 'opendir("../path/to/folder")'.
$pic_types = array("jpg", "jpeg", "gif", "png");
$alttag = ""; //caption
$websiteurl= ""; //alt tag
$caption = ""; //website url
 
$index = array();
while ($file = readdir ($folder)) {
  if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$pic_types))
      {                       
      $items[] = $file;                                  
      }
}
for($i=0; $i<sizeof($items); $i++) {                  
  $picpath = $dirpath . "/" . $items[$i];
 
  //Get the meta data
  $exif = exif_read_data($picpath, 'EXIF');
  $alttag = $exif['Title']; //alt tag
  $websiteurl= $exif['Subject']; //website url
  $caption = $exif['Comments']; //caption
  if ($caption != "") {
    $caption =  "title='" . $caption  . "'";
    $alt = "alt='" . $caption  . "'";
  }
  if ($alttag != "") {
    $alt =  "alt='" . $alttag . "'";
  }
  if ($websiteurl != "") {
    $varimages =  $varimages . " <a href='$websiteurl'><img src='$picpath' $alt $caption /></a>" . "\n\n" ;
  } else {
  $varimages =  $varimages . " <img src='$picpath' $alt $caption />" . "\n\n" ;
      }
  $alttag = ""; //caption
  $websiteurl= ""; //alt tag
  $caption = ""; //website url
}
closedir($folder);
$varimages = substr_replace($varimages ,"",-1);
echo $varimages;
?>
    </div>
  </div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.nivo.slider.pack.js"></script> 
<script type="text/javascript">
    $(window).load(function() {
        $('#slider').nivoSlider();
    });
    </script>
</body>
 
 
 

 

Updating Metadata in a file is very easy. On windows:

  1. Right click on the file
  2. Select Properties
  3. Select the "Details" tab
  4. Update Title, Subject and Comments and press "Okay"


Joomla - JReviews Tags Listing

on Sunday, 01 April 2012. Posted in Joomla, All

Get the source code
$4.99

Module for Jreviews to display tags on your joomla site
I was looking for a tagcloud solution for jreviews and decided to write my own. However instead of doing a tagcloud I decided to do something more modern and easier to read using google charts.
See screenshot below

Note: You can click on each tag and it will take you to a filtered list of all listing with that tag.

Screenshot:



In JReviews create a multiple select custom field and enable Autocomplete UI.





This is what it looks like when you add or edit a listing on the front-end

Install the module and you can customize the parameters


Table with tags: If you are using jreviews then keep the default value "jreviews_content"
Field with tags: This is the name of the custom field
Delimiter: If you are using jreviews the delimeter in the database is a star *

 




Manually Embed the Module

If you want to embed the module into a jreviews page manually Open the file and save a copy into your "jreviews_overrides" folder
example:
Path to Baseline file:
\components\com_jreviews\jreviews\views\themes\default\directories\directory.thtml

Path to Custom file:
\templates\jreviews_overrides\views\themes\default\directories\directory.thtml

Here is the code you would type into the custom page.
 
<?php
 
     jimport('joomla.application.module.helper');
$mod = JModuleHelper::getModule('mod_taglist');
//$mod->params    = "cols=2\nrows=10";
$attribs['tagstable'] = 'jreviews_content';
$attribs['tagsfield'] = 'jr_producttags';
$attribs['tagsdelimeter'] = '*';
$attribs['width'] = '700';
$attribs['height'] = '400';
$attribs['taglink'] = '/component/jreviews/tag/producttags/';
  echo JModuleHelper::renderModule($mod, $attribs);  
?>