Creating Google Calendar Events with PHP

Many small businesses are now using the extensive Google Apps for Business framework to manage many of their daily activities. However due to the increase of Cloud Applications being programmed as well to assist this businesses, sometimes they have to be importing their online application information into their Google Apps. With the available API’s however this has not to be necessarily the case.

Using the new Google Calendar API and the following PHP code you can easily create events dynamically when they are generated in your cloud business application. Please be aware than in order to connect through their API you will need to have Zend installed on your server.

<?php
// Load required libraries
$path = 'Zend/Gdata';
$oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');

class google {
	public $client;
	public $service;

	function createCalendarEvent( ) {
		// Authentication with Google
		$user = 'user@gmail.com';
		$pass = 'userPass';
        // Load required libraries
		 // predefined service name for calendar
		$serviceName = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
		$this->client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $serviceName);
		$this->service = new Zend_Gdata_Calendar( $this->client );
		// get time
        $this->eventStart = "07:00:00";
        $this->eventEnd = "08:30:00";
		// Create a new event to add required parameters
		$event = $this->service->newEventEntry();
		// Create a new title for your calendar event
		$event->title = $this->service->newTitle( 'My First Google API Interaction' );
		// Set a location for your event
		$eventAddress = '123 Test St, Chula Vista';
		$event->where = array( $this->service->newWhere( $eventAddress  ) );
		// You can also add aditional information to your appoitnment
		$event->content = $this->service->newContent( 'Extra event information');
		$when = $this->service->newWhen();
		// Set start and end times
		$eventInfo = '2008-09-08';
		// 2008-09-08T22:47:31-07:00 (For Pacific Times)
		$when->startTime = $eventInfo . "T" . $this->eventStart . "-07:00";
		$when->endTime = $eventInfo . "T" . $this->eventEnd . "-07:00";
		// Set the when attribute for the event
		$event->when = array($when);
		// Create the event on google server
		$newEvent = $this->service->insertEvent($event);
		// URI of the new event which can be saved locally for later use
		$eventUri = $newEvent->id->text;
	}
}

 

New Web Sites Do Not Validate

HTML and CSS Validation is a tool that was created in the beginning of the World Wide Web to make sure that web sites were constructed correctly. Many times when creating projects using new technologies, for multiple devices or that use third party applications we come to the problem that it does not validate according to the W3C standard. There are many developers and clients that react in a bad way when they see errors when validating and believe that the application still has bugs in it. Many time developers have to go back and change features just to make the site get a perfect score. Many times this makes the development time longer and the project more expensive. Developers and clients have to remember that validation is only a tool and nothing more than that, and while we do need to follow the standards set by the W3C we also have to make sure that usability and functionality are our top priority.

Usability over Technicalities

We always have to keep in mind that everything that we develop is intended for a person and not for a machine. Usability and Functionality for the target user of the application is the goal that we always try to achieve. While robots from search engines might crawl the application, we have to remember they are not our main audience. We also have to keep in mind that Google does not take validation as a ranking factor. You can see more about Google’s stand on this matter in the following video made by Matt Cuts for the Google Webmaster Forum:

When using many of the newer CSS3 techniques there will be an error created in the validation tool. For example when using border-radius that help us give rounded corners to our backgrounds. To go around this the designer has to design the curves and the developer implements them, which will take longer that using CSS3. We have to keep in mind that cases like this we have to always put user usability over irrelevant technicalities.

Validation is Irrelevant yet Important

While your validation score does not affect how search engine see you, it might still give you an extra boost in search engine optimization or SEO when the algorithm is looking at the web page overall usability. Validation as well still an important tool to review when working on a project. This tool will help you find unclosed tags and improperly nested div’s, extra semicolons, among other things. There will always be the error from Google’s Analytics or from that jQuery slider but as long as the integrity of the structure is impeccable you do not have to worry about the validation score from the W3C Tool. Remember that the score is only there to help you build a useable application; there is no target score you want to achieve just as long as you get 100% in usability with your target audience.

Please feel free to leave any questions or comments below.

Import CSV Files into a MySQL Database

Web Developer have to face a large amount of obstacles in their every day tasks in order to complete them. There are some thing that are easier to complete than other but a little bit of help can make a big difference when it comes down to finishing on time. Importing a CSV file into a MySQL database is often needed when creating projects for new clients. This is because they will use a variety of desktop software and they will probably tell you, “Here you go” when it comes to geting the data. To your advantage most of this applications have some way of exporting their data into Comma Separated Value files or CSV. Basically it’s a file that has a layout similar to a spreadsheet but instead of boxes for columns you have a coma separating the fields. In the same way in lieu of rows you will have a new line in the document.

The first step is to get that file from the customer or from it’s source and upload it into your server. After this you will need to access your server’s command line via an application like Putty and start your MySQL server.

$ mysql -h localhost -u root -ppassword

You will need to create your database with the fields that you will be needing. once your database has been set up you can import the data from your CSV file into your MySQL database. Here is the command that you will require in order to import the information into your database table.

load data local infile 'myphpdeveloper.com/httpdocs/_assets/cities.csv'
into table phpdev.gc_cities
fields terminated by ','
enclosed by '"'
lines terminated by '\n'
(zipCode, city, state, county, areaCode);

In the first line of the command is where the location to your Comma Separated Values or CSV file is located at. The second line is the table that you want the information to go into. The third line is telling your MySQL server that the values are separated by comas. In the same way the fourth line is describing how the values are enclosed by single quotes. The fifth line is telling your server that your row ends when the line end. Finally the sixth lane is the fields in your database table. They need to be aligned with the order of your file for example if your files is ID, Price, Description then your locations will be (id, price, description) and so on.

Often there are times that the above command will not work. This is due to the fact that this option is considered to be a big security risk. Some hosting companies like Media Temple are disabling this by default so you will need to make a couple of small changes in order for it to work.

You will have to locate your MySQL configuration file which is usually located at ‘etc/my.cnf’ and comment out the line that prevents the import. You will have to do this while being a root user in your server, if not it will only allow you to read the file but not to reconfigure it. The line that you are looking for is:

local-infile=0

You will have to comment it by adding a “#’ sign at the beginning of the line like:

#local-infile=0

You can learn more about this on the MySQL Documents. After you have completed the change you will need to restart the MySQL server and then do the process once more. The command to restart the server is:

service mysql restart

Hope that this helps any web developers out there. Please feel free to leave any comments, questions or suggestions down below and we will be happy to assist you.

Google Analytics eCommerce Tracking

Here is the script that needs to be added to the receipt or confirmation page, after the user has completed the sale. You will just need to add php inside of the script so that the content can be created dynamically per customer. One tip is to use a PHP loop. Here is the code:

<script type="text/javascript">



ξ var _gaq = _gaq || [];

ξ _gaq.push(['_setAccount', 'UA-XXXXX-X']);

ξ _gaq.push(['_trackPageview']);

ξ _gaq.push(['_addTrans',

ξ ξ '1234', ξ ξ ξ ξ ξ // order ID - required

ξ ξ 'Acme Clothing', ξ// affiliation or store name

ξ ξ '11.99', ξ ξ ξ ξ ξ// total - required

ξ ξ '1.29', ξ ξ ξ ξ ξ // tax

ξ ξ '5', ξ ξ ξ ξ ξ ξ ξ// shipping

ξ ξ 'San Jose', ξ ξ ξ // city

ξ ξ 'California', ξ ξ // state or province

ξ ξ 'USA' ξ ξ ξ ξ ξ ξ // country

ξ ]);



ξ ξ// add item might be called for every item in the shopping cart

ξ ξ// where your ecommerce engine loops through each item in the cart and

ξ ξ// prints out _addItem for each

ξ _gaq.push(['_addItem',

ξ ξ '1234', ξ ξ ξ ξ ξ // order ID - required

ξ ξ 'DD44', ξ ξ ξ ξ ξ // SKU/code - required

ξ ξ 'T-Shirt', ξ ξ ξ ξ// product name

ξ ξ 'Green Medium', ξ // category or variation

ξ ξ '11.99', ξ ξ ξ ξ ξ// unit price - required

ξ ξ '1' ξ ξ ξ ξ ξ ξ ξ // quantity - required

ξ ]);

ξ _gaq.push(['_trackTrans']); //submits transaction to the Analytics servers



ξ (function() {

ξ ξ var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;

ξ ξ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

ξ ξ var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

ξ })();



</script>

Creating custom 404 page

Everyone at some point has been browsing trough google or their favorite search engine and clicked on a link just to go into a white page with the words ???404 Error??? up on top. After this the only thing you have is to hit the ???Back??? button on your browser. As a user, this means that you go backand try another link. As a developer do, it means that you lost a potential clients, and that you have a glitch in ξyour application that you are not aware of.

You can set upt a custom 404 page using your apache .htaccess file. Here is how to do this:

  1. Access your server via FTP
  2. Make sure that you can see hidden files
  3. Locate for .htaccess
  4. If .htaccess does not exist go ahead and create it
  5. Open the file
  6. Type: ErrorDocument 404 /404.php
  7. Save the file
  8. Now you can go and edit this file so that you can have a custom error page.

That is all that you have to do in order to set up your server to have a custom 404 page. Use your imagination on this one, for examle you can have a search function or related pages to what the user was looking for. You can also have this page email you so that you become aware of the situation.

Hope this helps, any questions or concerns can be submitted below.

Basic AJAX connection using the POST method to retrieve content

Hello guys,

I have been working on a project for school which used AJAX and I just wanted you guys to have this code for reference. This code basically makes a call to a PHP script which gets Zip Code information (city and state) and then adds them into your web page. I used a span tag with id of ???zipinfo??? to act as a holder for the content that was going to be retrieved. Hopefully this helps some of you in your projects.

//Get Zip Code Information

function zipInfo(zipcode) {

fieldValue = ???connection=zipInfo&zip=???+zipcode;

var url=???includes/management.php???;

httpRequest(???POST???, url, true, fieldValue, function(result){

document.getElementById(???zipInfo???).innerHTML = result;

});

}

//AJAX Request

function httpRequest(reqType, url, asynch, fieldValue, callback) {

request = new XMLHttpRequest();

request.open(reqType,url,asynch);

request.setRequestHeader(???Content-type???, ???application/x-www-form-urlencoded???);

request.setRequestHeader(???Content-length???, fieldValue.length);

request.setRequestHeader(???Connection???, ???close???);

request.send(fieldValue);

request.onreadystatechange = function() {//Call a function when the state changes.

if(request.readyState == 4 && request.status == 200) {

callback(request.responseText);

}

}

}

Creating a Sample HTML5 Structure

 

TML5 is the thing that developers are starting to take a look more and more. More and more browsers are getting compatible with it and with the iPhone choosing this as it???s main multimedia language I have no doubt that this will be demanded in great quantities. In this post I will explain how to create a sample HTML5 structure for your web site.

<!DOCTYPE HTML>

<html lang="en">

<head>

<meta charset=utf-8>

<title>Sample HTML5 Structure</title>

<style>

header, nav, article, footer, address, section {

ξdisplay: block;

}

#container {

ξwidth:900px;

ξmargin:auto;

ξbackground-color:white;

}

header {

ξbackground-color:#666;

}

nav li {

ξdisplay:inline;

ξpadding-right:1em;

}

nav a {

ξcolor:white;

ξtext-decoration:none;ξ

}

nav a:hover {

ξtext-decoration:overline;ξ

}

h1, h2 {

ξmargin:0px;

ξfont-size:1.5em;

}

h2 {

ξfont-size:1em;

}

footer {

ξbackground-color:#999;

ξtext-align:center;

}

</style>

<script>

document.createElement("article");ξ

document.createElement("footer");ξ

document.createElement("header");ξ

document.createElement("hgroup");ξ

document.createElement("nav");ξ

</script>

</head>

<body>

<div id="container">

ξξξ <header>

ξξξ ξ<h1>Sample HTML5 Structure</h1>

ξξξξξξξ <nav>

ξξξξξξξξξξξ <ul>

ξξξξξξξξξξξξξξξ <li><a href="#">Home</a></li>

ξξξξξξξξξξξξξξξ <li><a href="#">About</a></li>

ξξξξξξξξξξξ </ul>

ξξξξξξξ </nav>

ξξξ </header>

ξξξ <section>

ξξξ ξ<hgroup>

ξξξξξξξ ξ<h1>Main Section</h1>

ξξξξξξξξξξξ <h2>This is a sample HTML5 Page</h2>

ξξξξξξξ </hgroup>

ξξξ ξ<article>

ξξξξξξξ ξ<p>This is the content for the first article</p>

ξξξξξξξ </article>

ξξξξξξξ <article>

ξξξξξξξ ξ<p>This is the content for the second article</p>

ξξξξξξξ </article>

ξξξ </section>

ξξξ <footer>

ξξξ ξ<p>This is the Footer</p>

ξξξ </footer>

</div>

</body>

</html>

As you can see the syntax is very similar, the start tags changed somewhat, but it makes it more convinient for the coder. Alsoas you can see now instead of making separate divs to stylize the header and footer, now HTML5 gives you a specified tag for each of them. The <nav> tag is the where your main site navigation will be at. You can also see the <section> tag, this will define the differents parts of your page, for example articles, blogroll, etc.ξ The <hgroup> tag is used to group various content heading, for example when you have an Article title and a Subtitle.

The JavaScript part of the code will create the tags so that older browsers and IE will accept them. This step is very important, if you do go ahead and skip it then older browsers will have trouble understanding your ode and the results will vary a lot.

Please leave any comments and/or suggestions below,

Gilberto Cortez

Image Resizing with PHP

Hello guys,

Today I will post a image resizing script, this will assist you in all of your sites specially ecommerce ones in which you need to display your products with different sizes. The script is self explanatory, but please send me a message or a comment if you need further assistance with it.

//Image Target

$pic = ???images/???.$_GET[‘pic’];

//Set Max Sizes

$max_height = 48;

$max_width = 48;

//Get Image Size

$size= getimagesize($pic);

//Set Ratios

$width_ratioξ = ($size[0] / $max_width);

$height_ratio = ($size[1] / $max_height);

if($width_ratio >=$height_ratio)

{

$ratio = $width_ratio;

}

else

{

$ratio = $height_ratio;

}

//Set new size

$new_widthξξξ = ($size[0] / $ratio);

$new_heightξξ = ($size[1] / $ratio);

//Set header

header(???Content-Type: image/jpeg???);

//Create Image

$src_img = imagecreatefromjpeg($pic);

$thumb = imagecreatetruecolor($new_width,$new_height);

imagecopyresampled($thumb, $src_img, 0,0,0,0,$new_width,$new_height,$size[0],$size[1]);

imagejpeg($thumb);

imagedestroy($src_img);

imagedestroy($thumb);

All you need to do now is to point the src element of your image tag to this script, and set the file you desire using the get method. Ex: img.php?pic=image.jpg

Please contact me with any doubts,

GilbertoξCortez

Interactive Web Development for ???The Cloud???

Transfer a Large Database using MySQL Dump and a SHH Client

Have you needed to transfer a large database? One of an eCommerce Cart or of a big blog? phpMyAdmin only allow’s imports of databases of 2 mbs, if you fix the php.ini file you can get maybe 10 or 12 max on most servers. In order to move this you will need to do it through shell access. Here is instructions on how to do this:

  1. Contact your service provider and tell them to allow shell access in your account.
  2. Download a SHH client like puTTY
  3. Open the application, enter your domain and the port. (I have usually encounter them to be 22 or 2222)
  4. Enter your username and password. These are usually the same as your FTP credentials.
  5. To export or dump the MySQL database you will be using a tool calles MySQL Dump, to do this you will type:
    1. mysqldump -u [username] -p[password] [dbname] | gzip > [location/name].sql.gzip
    2. the items in [ ] need to replaced and the brackets removed. Also please note there is no space between -p and your password
    3. This will create what is called a dump file of your database which will be gzipped for easier development.
  6. Now you need to get the file that was created and upload it to your new site via an SFTP or FTP client.
  7. After this enable shell access on your new server or location and access it
  8. First we need to decompress the .gzip file, to do this type:
  9. gzip -d [location/file].sql.gzip
  10. After this is completed the gzip file will dissapear and you will only have the sql file needed.
  11. Now all you need to do is import the file into your database, to do this type:
    1. mysql -u[username] -p[password] [dbname] < [location/file].sql
  12. Your import and transfer of your MySQL database is now complete.

————

Do you need any work performed on your database or on your web application? You can contact me at (619) 800-2678 or using the Quote Request form.

Upload Files From a Form

Hello guys,ξ I decided to do a post on how to upload files from a simple HTML form into your server. First, you will need to set up this form with the proper headings, please see code below.

<form enctype=”multipart/form-data” action=”uploads.php” method=”POST”>

Choose a file to upload: <input name=”uploadedfile” type=”file” /><br />

<input type=”submit” value=”Upload File” /> (Max Size is 2MB)

</form>

As you can see, there is a note stating that the maximum size can be of 2MB’s, you can change this in your php.ini file. Now, you will need to create your uploads.php file, which will receive the file and move it to your desired destination.

//File Upload

$target_path = “uploads/”; //Target Folder

$target_path = $target_path .$timestamp.’_’.basename( $_FILES[‘uploadedfile’][‘name’]);ξ //Final File Destination and name

if(move_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’], $target_path)) {

echo “The file “.basename( $_FILES[‘uploadedfile’][‘name’]).

” has been uploaded”;

} else{

echo “There was an error uploading the file, please try again!”; //If an error

}

As you can see, I have commented on the code so that it’s more clear to you, feel free to change the address to your desired location. And like always, please feel free to leave any comments, sugestions or questions below.

Thank You,

Gilberto Cortez