PHP Function Friday: date

I think the date function is extremely useful.  It gives your programs an awareness of WHEN they are.  You can do some pretty cool things like calculate this date from that date, make a calendar, or store information about when an action was taken.

Function and Syntax

string date(string $format  [, int $timestamp  ])

Manual Entry

http://php.net/manual/en/function.date.php

Notes and Use

There are two variables you can pass to the date function: the string format, and the timestamp.  What are those?  The string format uses various characters to define how the string the function returns will be formatted.  The table for which characters mean what is on the PHP Manual Page.  The timestamp is a Unix timestamp for a specific date/time.

Other Functions Referenced in Examples

Examples

Output Today’s Date and Time

This should just simply output today’s date.  I did a few formats based on January 1, 2009 at 4:52:39 PM.

echo date("Y-m-d H:i:s"); /* Should output '2009-01-01 16:52:39'.  Common programming format*/
echo date("F n, Y at g:m:s A") /* Should output 'January 1, 2009 at 4:52:39 PM'.*/

Put a Message on Your Website Every Monday

Do you hate Mondays?  Let everyone know.  This script checks to see if it’s Monday and then outputs a message if it is.  That ‘w’ in the date function is a numeric representation of the day of the week.  For instance: Wednesday is 3 and Sunday is 0.

if(date("w") == 1) {
   echo "Ugh.  It's Monday."
}

Examples Elsewhere on this Site:

Holiday Notices

Conclusion

Date functions are extremely useful when trying to figure out when you are (or better stated: when your program tries to figure out when it is).  Using date and time functions allow you to create a lot of automation in your scripts.  Have you got any useful implementations on this function?

PHP Function Friday: include

Including files makes it really easy to NOT duplicate code. It’s great for creating headers and footers for websites, or using it in the inverse: make the header and footer in one file, and include the content.  You can also store site configuration files, functions, and repeating content, etc.

Function and Syntax

include(<file path>);

Manual Entry

http://php.net/manual/en/function.include.php

Notes and Use

Includes are a great way to include the same code to many different PHP files.  I find this the most useful for storing variables and functions across an entire website.  The other great way to use this function is to include repetitive code that needs to be outside of a function scope – for example: including form layouts across multiple pages.  I like to use the same include for both my add and edit pages on a form sometimes.

Examples

Storing Site-Wide Variables

This is stored in the file ‘configuration.php’:

$blog_name = "jtGraphic.net";
$blog_description = "Ramblings of an Internet Addict";

This is another PHP file where you’re calling the include – call it whatever you want.  I’ll call mine ‘main.php’:

include("configuration.php");
echo $blog_name."<br />";
echo $blog_description;

This is another PHP file somewhere else on the site – maybe inside the /content/ directory.  Call it whatever you want.  I’ll call mine ‘content.php’:

include("../configuration.php");
echo $blog_name."<br />";
echo $blog_description;

Both ‘main.php’ and ‘content.php’ will echo out the same information because you included the same file at the beginning of each.

Website Header and Footer

I find that another extremely powerful use of includes is to build your header and footer for your website.  In this example, we’re going to dynamically set the title variable in the main content page and call it inside the include.  This is how I build some of my simpler sites.  By the way, this isn’t HTML standards compliant.  It’s just an example.

We’ll call this file ‘header.php’

<html>
   <head>
      <title>jtGraphic.net <?php echo $page_title; ?></title>
   </head>
   <body>
/*snip*/

We’ll call this next file ‘footer.php’;

//snip
      <div> &copy; James Thompson and jtGraphic.net </div>
   <body>
</html>

Now that we have our header and footer, we can make some more pages:

We’ll call this one ‘content_1.php’:

$page_title = "Some Title";
include("header.php");
//content here
include("footer.php");

We’ll call the next one ‘content_2.php’:

$page_title = "Some Other Title";
include("header.php");
//content here
include("footer.php");

When accessing ‘content_1.php’ and ‘content_2.php’ you should get everything you put in ‘header.php’ and ‘footer.php’, but the title should be what you defined in the content files.  This is a really rudimentary example, but it is VERY useful.

Conclusion

So, remember: whenever you have a set of code that is duplicated you can probably deal with it through custom functions or includes.  Don’t duplicate the code!  If you have your own examples, feel free to link them up below!

PHP Function Friday: function

So, I’ve decided to start including a new post every Friday – kind of as a discipline thing. I’m going to write a post on a PHP function every Friday. I’m not just going to regurgitate the post in the official PHP manual, but I’m going to list my experience with it along with some creative ways to use it.

With out any further adieu, I’m posting on the first official building block (which isn’t technically a function, but I digress) ‘function’:

PHP Function and Syntax

function <function name>(<parameters>) {
   /*add code here*/
}

PHP Manual Entry

Check here for version information, or anything I may have missed:

http://www.php.net/manual/en/functions.user-defined.php

Notes and Use

This is great for building blocks of code that you repeat a lot.  I like to use it when duplicating XML/HTML code, such as links or form elements, which I will outline below.  Functions, both custom and built in, are the primary building blocks of a good program.  Everything else is just procedural.

Also, on a side note: PHP Coding Standards is a good read if you’re really geeky.

An important thing to keep in mind about making custom functions is that someone has probably already made it if it doesn’t already exist in the built in functions for PHP.  Feel free to jump online and see if someone has already made a function to do what you’re trying to do.  I like to use the site HotScripts.com, which has both free and commercial PHP scripts available.  Chances are: if I need it, they have it.  It saves me a ton of time.

Note in the examples that I precede the function with some explanation of what it does, the author, etc.  This isn’t needed, but it’s a REALLY good habit.

Other Functions Referenced in Examples

Examples

Here’s the meat.  Let’s make some stuff work.

Creating Image Links

/*
 *  Author: James Thompson, jtGraphic.net
 *
 *  Description
 *  ------------------------------------
 *  This function is for displaying image links in HTML.  It's less typing,
 *  and easier to remember what needs to be slashed out.  An image
 *  with the same name as the file name of the page you're linking to needs to
 *  be placed on the server in the same path as the internal variable
 *  '$image_path' and the same extension as '$image_ext'.
 *
 *  Arguments
 *  ------------------------------------
 *  $url - URL of the link
 *  $extra_tag_html - this is any extra HTML, like class, id, or style
 *
 */

/* Build the function. */

	function create_html_link($name, $extra_tag_html) {
		/* Define internal variables. */
			$image_path = "images/";
			$image_ext   = ".jpg";

		/* Output the HTML. */
			echo
				"<a href="".$name.".php" ".$extra_tag_html.">
					<img src="".$image_path.$name.$image_ext."" />
				</a>";
	}

/* Execute the function. */

	create_html_link("home", "class="normal_link"");
	create_html_link("about", "class="normal_link"");
	create_html_link("contact", "class="normal_link"");

Calculate the Number of Days Since Some other Date

/*
 *  Author: James Thompson, jtGraphic.net
 *
 *  Description
 *  ------------------------------------
 *  Simple.  This calculates the number of days since X date.
 *
 *  Arguments
 *  ------------------------------------
 *  $date - the date in this format: 'YYYY-MM-DD HH:MM:SS'
 *
 */

/* Build the function. */

	function num_days_since($date) {
		/* Do some time math. */
			$date = strtotime($date);
			$now = time();
			$difference = $now - $date;
			$days = $difference / 86400;

		/* Output the Value. */
			return $days;
	}

/* Execute the function. */

	/* Should return 0 */
		echo num_days_since(date("Y-m-d H:i:s"));
	/* Someone's birthday at 6:02:55AM on Oct 23, 1974 */
		echo num_days_since("1974-10-23 06:02:55");
	/* Since Jan 1, 2009 - no need for time */
		echo num_days_since("2009-01-01");

Examples Elsewhere on this Site:

Holiday Notices

Conclusion

So that’s the basics.  Functions can be very powerful in reducing the code on your websites.  If you’d like to see some more custom functions, check out my Tidbit Tuesdays on PHP If you have questions, let me know in the comments.

Goals vs. Resolutions

measureGoals and resolutions are not the same thing.  Let’s look at their definitions as advertised via dictionary.com:

goal

–noun
1. the result or achievement toward which effort is directed; aim; end.
2. the terminal point in a race.

res⋅o⋅lu⋅tion

–noun
1. a formal expression of opinion or intention made, usually after voting, by a formal organization, a legislature, a club, or other group. Compare concurrent resolution, joint resolution.
2. a resolve or determination: to make a firm resolution to do something.
3. the act of resolving or determining upon an action or course of action, method, procedure, etc.
4. a solution, accommodation, or settling of a problem, controversy, etc.

What’s the difference?

When you resolve to do something, you are setting up an action that you will carry out without measurable results.  For example: “I will exercise more this year,” “I will lose weight,” “I will spend more time at home,” etc., etc.  A goal is the vessel by which you take a resolution and define a measurable outcome.

What this means to me:

Every new year, I define a set of goals for the year, both personally, and for my business.  I express those goals for my business through an annual review of the business plan – a document defining my finite goals for the year, next three years, ten years, and life of the company.  I define my personal goals here on this blog.  All of the goals I set for myself follow a specific format.

Formatting a Goal

I use a simple acronym for defining my goals: SMART.  Smart stands for:

  • Simple
  • Measurable
  • Attainable
  • Realistic
  • Timelined

For instance, looking at my previous post: My Goals for 2009, we can pick out the goal: “Put $10,000 into my IRA.”  This goal is simple because I only need to do one thing.  Tracking it isn’t complicated.  It is measurable.  Each dollar I put in is a measurable unit.  It’s attainable.  I’m pretty sure I can do this if I hold myself to it.  It’s realistic.  I’m not putting more than I make into my IRA.  It has a timeline, because these are my 2009 goals, I have until Dec. 31, 2009 to complete them.

Following Through

Goals are only useful if you follow through.  I like to set goals far enough in advance and broad enough that if I fall short for a couple days, I can recover.  I like to make “thermometers” to track how close I am to acheiving goals as well.  I can organize all of my thermometers into a dashboard of sorts and rate myself on my progress.  I can find places I fall short and work on improving those areas.

I hope this helps you turn your resolutions into goals and your goals into results.

A review of 2008.

Here are some of the more popular blog posts that I made in 2008:

Hands down, the most popular post I made was How to Make Fire in Photoshop.

In March, I made a controversial post about Macs, PCs, and Linux.  I should probably do a follow up on this.

I found a solution to my Outlook / Google Calendar synchronization issues.  Actually Google found a solution.  Thanks Google.

I listed my top ten free applications.  I plan to do another version of this post in 2009.

I made a few submissions to shirt.woot derbies, but never won.  I have no problem admitting that the competition over there is pretty stiff, and the technical ability of some of the artists surpasses my own by quite a bit.

In December, I started doing contests for shirt.woot shirts.  I’ll probably change this up in the future to offer other things.  This just seemed like a great place to start.

I know I also did some things wrong.

By far the biggest thing I regret doing in 2008 was taking a break from blogging from May to September.  I think that really hurt my readership, and I’m going to try and refrain from doing that at all this year.  My blog also lacked focus.  I’m still having trouble breaking my topics apart.  Right now I think my lack of focus leaves readers wondering what I’m talking about half the time.  I’m really passionate about Woot, but a lot of internet marketers probably don’t care, and when I’m talking about internet marketing and programming, Wooters probably get bored.  Interesting perplexity.  I will try to address this in 2009 as well.

I have some pretty exciting plans for 2009 that I will follow up on later.

Saving Bandwidth with Google Ajax Libraries API

The News

I first heard about the new Google AJAX Libraries API from Jeremy Schoemaker’s blog.  He mentions using it to reduce WordPress bandwidth, but really it can be used to reduce bandwidth in most AJAX based web development environments.

The Exciting Part

I persoanlly use prototype the most, and I’m extremely excited that I can use their libraries instead of uploading my own for each site.  I’m especially excited that calling specific version numbers is possible.  This makes upgrading a code set extremely simple, especially if you call the code version as a variable at the beginning of your code.

Realistically your javascript code is probably one of the lightest weight parts of your code, but every little bit helps, especially if you’re serving a large amount of users every month.

Optional Settings

Script Compression

I think one of the greatest optional settings for all of the scripts you can load is compression.  It’s not available for all of the APIs, but it is for most.  What it does is remove all of the whitespace from the API to reduce file size for the end user – increasing speed.  If you mix that with something like the javascript compiling on Google Chrome and you’ll have lightning fast AJAX applications.

No CSS

You can optionally remove the CSS from the scripts you’re remotly loading, which allows you to do one of three things: load the default CSS, load your own CSS, or not load the CSS at all.

Resources

WordPress.org: Google AJAX Libraries API Plugin – This plugin uses the GALA whereever possible in your WordPress installation.

Google AJAX APIs Blog – This is a great place to go if this really iterests you and you’ll be using this code regularly.  They’re always adding new scripts to the API, so if you don’t see the one you want yet, keep an eye on their blog.

Google Image Search Gets Upgraded

google_logoGoogle image search has always been a great tool for finding images of things, but it has never been great for really dialing down what you want based on the image composition.  They’ve recently added the ability to dial down your search by image type, which is great for finding specific things that you want.  For instance: I can search for line drawings of vermont.  Interestingly that search brings up a lot of maps.  Maybe in the future, they will add “maps” as a criteria.

Comparison

Google image search still isn’t as robust as something like iStockPhoto, but I think that is probably the culprit of some sort of technical difference in their systems (i.e. Google is indexing images and iStockPhoto is all user submitted images).  Because iStockPhoto has user submitted entries, they can enter meta data that Google just can’t derive from just the image.

Capabilities

Right now, you can filter image searches by news content, faces, clip art, line drawings, and photo content.  They are using photo recognition and search data to add additional meta data to the images.  For instance, the news content option checks the surrounding text around the images for meta data that pertains to news.  They can use photo recognition algorithms for recognizing facial structures in the images.

The Future?

I’m hoping maybe someday they will add features similar to iStockPhoto like color recognition and content layout.  Color layout is something that I’ve been looking forward to for a while now.  It’d make it really easy to pick up images that go with a specific theme in a website design or something to that effect.

Mac vs. PC vs. Windows vs. Linux vs. Huh?

Alright. I’ve finally decided to break down the pros and cons of Macs, PCs, Linux, Windows, etc. First off, I’d like to say that none of these platforms are apples to apples. Each one has advantages and disadvantages. There are also some interesting dynamics to some of the rivalries that some people just don’t think about. Every side in this debate has its elitist fanatics, which is fine by me. I like to play neutral. Each platform has its benefits and drawbacks. Finding the right combination of benefits and drawbacks is what will ultimately satisfy end users.

Macs

Macs are great stable products. For those of you that say they never freeze… you’re full of it. They do freeze, just like any other computer. They are probably LESS likely to freeze than something like Linux running on a top-of-the-line laptop, but fundamentally, you can expect the to freeze up periodically like ANY electronic device.

Macs run so well because the hardware and software are developed by the same company. This lends itself to a great end user experience, but winds up much like AOL (don’t get me started). Users are confined to the user experience outlined by apple, unless the occasional developer comes along and expands the experience (go Adobe!).

Unfortunately software is less prevalent on Macs for a few reasons: the first being the cost of the developers kit. Developing on the native Mac platform costs developers money, which doesn’t foster the kind of interest you see in other communities, such as the Linux community. The secondary reason software is less prevalent on Macs is simply a function of market share. Many developers just don’t see the right ROI from the Apple platform.

The function of market share that stifles development on the Mac platform also makes it less lucrative for hackers and other malicious deviants to develop harmful software targeted at Mac users. This helps increase stability on the platform, allowing for a better user experience. Trust me. If Apple had as much of a market share as Microsoft, they would have just as many problems with malicious software.

Overall, Macs are a great hardware / software combination, not unlike a cell phone or game console. Due to the lack of software available on the platform, they aren’t great for large business environments or niche users, especially in the accounting and legal fields.

PCs

As far as I’m concerned, a PC is just hardware. It’s a collection of standards that collectively make a “PC.” Windows, Linux, and yes Mac OS X (albeit glitchy) can all run on these systems. The debate between Macs and PCs is somewhat superficial in that it’s not apples to apples. It’s apples to potatoes. They’re not even in the same food group. Macs are essentially made up of the same standards based hardware that PCs are, but the scope of the hardware is much narrower and tested much more thoroughly to work with Apple operating systems.

Because the PC is an open platform, development is much more prevalent. Operating systems optimized for the open PC environment are much more flexible and consumers have more choice over where they would like to purchase their hardware. As a consumer, I can chose to buy hardware from Dell, HP, Gateway, or build a machine myself. If I want a Mac, I get one made by Apple. Sure, I can buy it from a reseller, but Apple made and distributed it.

Windows

Windows is a great operating system – despite what some may say. Windows XP is a great, stable operating system. Windows Vista, although it had a rough start, is coming along nicely. I like some of the new features in Vista, such as live switching to Administrator, the new performance monitor, and their integrated indexing / search. Now that driver support has gotten much better, Vista has my stamp of approval for home users. I almost trust it enough for businesses, but not just yet. As a general rule, I don’t recommend something for business until 18 to 24 months out.

Now this is where people tend to over generalize. Microsoft doesn’t compete directly with Apple – in that they don’t create hardware for Windows. I think that is an anti-trust thing, but I’m not sure. Microsoft actually benefits from some of the recent changes with OS X Leopard. When people run Boot Camp, they must purchase a copy of Windows to run on it. Microsoft still collects those revenues. I’d love to try out a an Apple running OS X Leopard with Boot Camp and Windows Vista, but alas I’m still too poor.

Linux

Oh Linux. This is probably the operating system with the most elitists (look in the comments), the most distributions, and the most bugs. It’s still not quite user friendly enough for home use, although Ubuntu comes close. Driver support sucks too. How is it that Linux thrives so well then? It’s free. It’s open. When configured correctly, it’s the most stable operating system for ultra specific applications.

To be honest, I’m not a huge fan of Linux, because when ever I try to do something it’s like pulling teeth. I usually try to do the “learn by immersion” thing every once in a while, but end up switching back to Windows because something just becomes impossible. That being said, I understand that it has some huge benefits. I use it for my web servers. It makes a great platform for Oracle and MySQL. It’s also great for creating specific machines that complete unique tasks on an on-going basis. I have one customer that has a machine that just checks an email box periodically and prints out what ever it receives (don’t even get me started on the paper waste thing).

Conclusion

Basically I think comparing all of the aforementioned is like comparing apples, potatoes, steak, and air. They’re all food, but after that, they all have benefits and drawbacks, but fundamentally they’re completely different. Please shoot holes this theory. Why is one better than the other?

How To: Fire in Photoshop

Fire Tutorial 01Create an image the size of what you need. In this case, we’ll create a 500x500px image, and fill the background red (ff0000) (or any other base color I guess).

Create a yellow (ffff00) shape in the form that you’d like to make your fire. We’ll use a “JT” graphic in this case. Make sure that you size and place it in a way that will leave room for the flames. You don’t have to use a specific shape if you’re just looking for fireballs or something. Make sure the shape is rasterized by right clicking on the layer and clicking “Rasterize Shape” or “Rasterize Type.” Depending on your version of Photoshop and the type of shape you’re using, this may vary.

Fire Tutorial 02Use the wave distort function to start working the shape:

  • Click Filter > Distort > Wave.
  • Set your scale to 20% for both horizontal and vertical.
  • Set your wavelength and amplitude to Min: 16 and Max 32.
  • Run the wave filter again with the min/max set to 8/16 and 4/8.

Fire Tutorial 03This is the part that might take a bit of skill. You can completely skip it, but it doesn’t look as real. You need to work the fire upwards and wisp it a bit with the liquify filter (Filter > Liquify).

Run the wave filter again with min/max at 2/4 four times.

It’s good to do multiple layers in this way if you’re planning on making an object look like it’s burning, because you can but layers in front of and behind the object. You can also use blend modes to get cool effects. Throughout the rest of the tutorial, I’ll speak as if I’m working on a single layer, but the final product at the end of this tutorial was done with two layers.

Run the 2/4 wave filter one more time on the layer(s).

Now the good stuff…

Hide all layers except the background. Set your foreground and background to red(ff0000) and yellow(ffff00) in your color picker.

Fire Tutorial 04Render some difference clouds (Filter > Render > Difference Clouds) about 10 times. Make sure you end on red/yellow, not green/black, unless that’s what you want.

Select the layer outline of one of the hidden layer(s) (Cntrl + Click; it doesn’t need to be visible).

Copy the difference cloud pattern with the outline generated by the hidden layer, and paste it to a new layer.

Give the new layer an inner shadow through blending options (right click the layer and click “Blending Options”), but change the blend mode of the shadow to normal and make the shadow color yellow (ffff00). Give it an opacity of 50%. If you’ve created multiple layers of fire, do this for each layer.

Do some cleaning. You can remove the layer with difference clouds (background), as well as the yellow “outline” layer(s).

Fire Tutorial 05

Rasterize the blend modes of any layers. I’ve found that the easiest way to do this is create a new layer (Layer > New > Layer), place it directly below the layer you want to rasterize the blend modes on and merge them (Click on the higher layer and merge down: Cntrl+E).

Create a layer and fill it red (ff0000). Place the layer UNDER the fire layer(s).

With one of the two blended layers and the red layer visible, select a color range (Select > Color Range), sampling the fully red area. Invert the selection (Select > Inverse) and copy from the “fire” layer and paste the new layer. Do this for all of the fire layers if you’ve done multiples.
Fire Tutorial 06Fire Tutorial 07Fill the red background with any color you’d like. I think black looks nice (left).

With some experimenting on the blending modes of the layers, and adding the original image shape, I was able to come up with this (right). I put the less “worked” fire image in front of the original shape, and the more “worked” image behind it.

Let me know what you think, but especially let me know if there is a better way to do it.

-JKT