Real World Unix Timestamp Examples

Overview

Unix timestamps are extremely useful and can be used across my different programming languages and platforms. I will outline a couple programming languages that support timestamps.

  • PHPconvert timestamps to date in php
  • MysQLview example on how you can query timestamps from a MySQL Database
  • Javascriptthe Date() function in Javascript can use timestamps
  • Perlthe time() function in Perl can handle unix timestamps
  • Linuxreturn current timestamp in linux

Real World Unix Timestamp Examples

PHP

In PHP, you can convert a unix timestamp to a real time by using the php date() function. date() allows you to convert a timestamp that is supplied as the second parameter or if the second parameter is left out, it will convert the current timestamp to date.

<?php

/* this would display a time of 23 May 2011 17:12:pm */
echo date('d F Y H:i:a',1306134726);
/* and this would display the current time in the same format as above */
echo date('d F Y H:i:a');

?>

The way the date is displayed is controlled by the flags passed to the function. Here we used the flags ‘d’, ‘F’, ‘Y’, ‘H’, ‘i’ and ‘A’. For a complete list of flags and to see a complete description of this function, visit http://php.net/manual/en/function.date.php.
The PHP function time(), strtotime() and mktime() all return the current unix timestamp. If you wanted to, you can also get a time stamp 24 hours from now by using the following code.

<?php

/* get tomorrows timestamp */
$tomorrow = time() + (24 * 60 * 60);

/* or you can use strtotime to convert a natural string into a timestamp */
$tomorrow = strtotime('+24 hours');

/* and this will create a timestamp based on the date and time variables */
$timestamp = mktime($hour,$min,$sec,$month,$day,$year);

?>

MySQL

If you have a table that contains a column with a unix timestamp in it, you can convert it using the query below. It will return a column that contains rows of easy to read date and times.

SELECT FROM_UNIXTIME(column_name) AS real_time FROM `table_name`;

Javascript

Javascript has a function called ‘Date()’ which allows you to use timestamps in javascript. Remember that since javascript is client side code (i.e. runs on the persons browser), the date shown is their own computer time, not the server time. To get the current timestamp in javascript, simple use

<script type="text/javascript">

/* get the current timestamp */
var timestamp = +new Date();

</script>

You can also convert a timestamp to a date by using the following javascript date functions.

<script type="text/javascript">

/* create a new date as of the current date */
var date = new Date();
/* you can also create a new date and pass a timestamp to create the date as of the timestamp */
var another_date = new Date(1306482441);

var day  = date.getDate(); // get the day that date relates to
day = day < 10 ? '0' + day : day; // add a 0 if less that 10
var month = date.getMonth() + 1; // returns month as 0 - 11
var year = date.getFullYear(); // 4 digit year (eg. 2011)
var hour = date.getHours(); // get hours
hour = hour<10?'0'+hour:hour; // pad with a 0
var minute = date.getMinutes(); // and minutes
minute = minute<10?'0'+minute:minute; // pad with 0
var second = date.getSeconds(); // get seconds
second = second<10?'0'+second:second; // pad with 0

</script>

Perl

In order to retrieve the current timestamp in Perl, you can make use of the time() function which is the same as PHP.

my $timestamp = time();

Linux

Using the ‘date’ command in linux will print out the date specified by the parameters passed to it. We will use the %s flag to tell it to print the seconds passed since ‘1970-01-01 00:00:00 UTC’ (i.e. it will print out the current timestamp).

date +%s

Specify Favicon.png In Html

Overview

Favicons are the tiny icons that usually appear next to the url in your browser. Favicons add a nice flair to your site and they are typically easy to implement.

specify favicon.png in html

Image showing an example of a favicon in showing in google chrome

Compatibility

For compatibility with all browsers stick with .ico is the way to go, however png favicons are support by most modern browsers. You can also specify both a favicon.png and favicon.ico in your html code to ensure complete compatibility.

Specify Favicon.png In Html

To specify favicon.png in html all you need to do is include the following line in the head of your html.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="icon" type="image/png" href="http://www.thecave.info/favicon.png" />
  </head>

Why use favicon.png

I have found that is it usually easier to save an image as a png as opposed to ico. Additionally, a png can be smaller than ico. There are other websites that will allow you to upload an image and convert it to an ico should you wish to have both a ico and png version of your favion.

Overlay HTML Over Flash Object

Overview

When building websites that use HTML and Flash, you may find that the flash movie appears above all of your other content such as drop down menus, div boxes and shadow-boxes. It can happen even when you manually enter in the z-index of those elements.

A Note About Z-Index Layering

The z-index of an item determines the layer an item will be rendered on. The higher the z-index number, the closer to the top layer an item will appear. So an item with a z-index of 10 will appear in front of an item with a z-index of 9.

Setting The Z-Index Of An Item

<style>

.your-item {
    z-index: 1000; /* or what whatever number you like */
}
</style>

Overlay HTML Over Flash Object

It can be very frustrating when flash appears above html content and menu. The reason this occurs is that DHTML uses layers to decide which elements stack in front of others. Just as a stack of cards are layered on top of each other. Content like Java or Flash that is embedded into the page ignores the layer order and is by default rendered on the highest layer of the page.

Older browsers are still stuck with this issue but luckily most modern browsers these days have the ability to layer the embedded content along with the rest of your elements. All you need to do to overlay html over flash object is to set the `WMODE` parameter to `transparent` and now it will obey your layering order which is controlled by the swf’s z-index. Other values for WMODE are ‘window’ (default), ‘opaque’, or ‘transparent’.

I will show you two ways on how to enable WMODE when embedding flash in your website.

1st option – Inline Embedding

To set the `WMODE` you need to set it in two place which I have highlighted yellow in the below example.

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="380" height="190" id="YourFlashMovie" align="middle">
	<param name="allowScriptAccess" value="sameDomain" />
	<param name="allowFullScreen" value="false" />
	<param name="movie" value="AS3_File_Upload2.swf" />
	<param name="quality" value="high" />
	<param name="wmode" value="transparent" />
	<param name="bgcolor" value="#333333" />
	<embed src="YourFlashMovie.swf" quality="high" wmode="transparent" bgcolor="#333333" width="380" height="190" name="YourFlashMovie" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>

Now all you need to do is place the flash movie where you want it and optionally set z-index to override the layer it appears on.

2nd option – swfobject (javascript include function)

Alternatively, you can use swfobject and specify similar parameters to acheive the same effect. Swfobject is a javascript file available free from http://code.google.com/p/swfobject/ and can be used to simplify the process of embedding flash into your website.

After downloading the swfobject.js from google code, include it into your page using.

<script type="text/javascript" src="swfobject.js"></script>

And then execute the function as shown below but ensure that you set the param to include `WMODE` as highlighted yellow.

<script type="text/javascript">

var flashvars = {};
var params = {wmode:'transparent'};
var attributes = {};

// divContainer is the div block that will then hold the embedded flash object.
swfobject.embedSWF("flashFile.swf", "divContainer", "300", "120", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

</script>

Prevent Menu From Appearing Behind Flash Object

Once you have completed the above, you can now change the order/layer the flash appears in your page. Your flash object should now obey the layer ordering and setting the z-index on both your flash object and menu should do the trick

Remember: The higher the number, the higher the layer. Higher layers appear on top of lower layers.

<style>

#YourFlashMovie {
    z-index: 1000; /* or what whatever number you like */
}

.yourMenuContainer {
    z-index: 1001; /* or any number as long as it is higher then #YourFlashMovie */
}

Specify Sitemap In Robots.txt

Overview

When creating a new website, or updating an existing website, you need to tell google and other search engines where your sitemap is located. You can submit a sitemap to google using Google’s webmaster tools. A more convenient way is to Specify a Sitemap In Robots.txt file. The robots.txt file is located in the root of your web folder. Search engines generally access and adhere to information in your robots.txt. However this is not guaranteed. Specifying the location of your sitemap.xml in your robots.txt file is done by adding a single line to your existing robots.txt file. If you don’t have a robots.txt file you can create a new robots.txt file and then add the line as shown below.

Specify Sitemap In Robots.txt

Sitemap: http://example.com/sitemap_location.xml

It will now tell Google and other search engines where your sitemap is located on your website. The sitemap listed here can be either your full sitemap or even a top level sitemap that links to all your other sitemaps (if you have more than one sitemap.xml file).

Full Robots.txt Example

User-agent: *
Allow: /
Disallow: /example-folder/
Disallow: /another-folder/

Sitemap: http://www.example.com/sitemap.xml.gz

Interesting Facts About Unix Timestamps

Here are a couple of facts surrounding unix timestamps you may find interesting. A couple of these are tips I discovered and a couple found browsing the internet. If you are not sure what a timestamp is, then read this article on What Is A Unix Timestamp And Why Is It Useful

  • On January 19, 2038, the Unix Time Stamp will cease to work due to a 32-bit overflow. This will result in websites crashing if they are still using 32-bit cpu’s. Before this moment millions of applications will need to either adopt a new convention for time stamps or be migrated to 64-bit systems which will buy the time stamp a “bit” more time.
  • At 03:33:20 UTC on May 18, 2033, the Unix time reaches 2,000,000,000 seconds, the second billennium.
  • At 23:31:30 UTC on February 13, 2009, the Unix time number reached 1,234,567,890 seconds.
  • At 01:58:31 UTC on March 18, 2005, the Unix time number reached 1,111,111,111.
  • At 01:46:40 UTC on September 9, 2001, the Unix billennium (Unix time number 1,000,000,000) was celebrated.
  • At 00:37:33 UTC on July 21, 2069, the Unix time will represent the first 10 digits of pi, 3141592653. (This coincides with the 100th anniversary of the first manned Moon landing, occurring between the times of touchdown and the first moon walk.)
  • At 09:06:49 UTC on Jun 16, 2034, the Unix time reaches 2,034,061,609 seconds and thus matches the current time to the hour (2034061609) when displayed as YYYYMMDDHH.

Check If Linux OS Is 64 Bit or 32 Bit

Overview – How To Check If Linux OS Is 64 Bit or 32 Bit

If you have ever needed to know if you have 32 bit or 64 bit linux installed, there are a number of simple ways to find this out of which I will show you two ways.

Note that if your cpu architecture is a 64 bit cpu, then you are able to install either 32 bit or 64 bit versions of Linux (or any operating system for that matter). However if your cpu architecture is 32 bit, then you are only able to use the 32 bit version of linux. It should also be noted that you are will not be able to install 64 bit applications on a computer with a 64 bit cpu if the linux operating system is running a 32 bit version of linux.

First Method to check if linux os is 64 bit or 32 bit

In your linux shell, type the following:

getconf LONG_BIT

It will return either 32 if you have the 32 bit installated or 64 for 64 bit versions.

Second Method to check if linux os is 64 bit or 32 bit

In your linux shell, type the following:

uname -m

If it returns x86_64 then you have the 64 bit variation and if you see i686 (or even i586, i386, etc.).

64 bit Hardware Support

If you need to see if your cpu architecture supports 64 bit

cat /proc/cpuinfo

Faster Alternative to PHP’s Array Unique Function

Overview

Using PHP’s function array_unique() allows you to take an array of values and remove the duplicates leaving you with an array with unique values. This function works best most of the time, however if you find yourself trying to use array_unique on massive arrays, it may slow down quite a bit.

Instead of using array_unique to create a distinct array, there is another nifty array function that will speed things up called `array_flip()`. With this magic function, it swaps each of the array’s key with its value and since keys must be unique, then you will be left with the same result as if you had used array_unique()

Faster Alternative to PHP’s Array Unique Function

/* create our array of 4 elements with duplicate values */
$array = array('green','blue','orange','blue');

/* flip the array now we will have an array with unique keys
	array('green'=>0,'blue'=>1,'orange'=>2); */
$array = array_flip($array);

/* and then flip the array back to put the keys and values where they are meant to be leave us with array(0=>'green',1=>'blue',2=>'orange'); */
$array = array_flip($array);

Since we have now removed a number of elements the array keys may not be in sequence. For example we may be left with array(0=>’A’,2=>’B’,5=>’C’);. In some situations, this is not an issue, however if you rely on the array keys being in numerical sequence, you can one of two things to fix the array keys.

Fix array keys using array_merge()

Add the following after the array flip to sort out the array keys and put them back into sequence, i.e. 0, 1, 2, 3, …

$array = array('green','blue','orange','blue');
$array = array_flip($array);
$array = array_flip($array);

/* Use array_merge() to fix the keys */
$array = array_merge($array);

Second method using array_keys()

Note, this method of fixing the array keys is marginally faster than using the array_merge() method
You could also combine the last step to use array_keys – which at the time would be the flipped values. Then once you flip the values, the keys will be created in order.

$array = array('green','blue','orange','blue');
$array = array_flip($array);
/* Same as first example, except now we first extract array keys */
$array = array_keys($array);

Note: Thanks to yehosef for helping fix and improve the above code.

Conclusion

Easy as that! and can have a significant increase in performance on massive arrays over using array_unique.

Validate Email Addresses – Javascript and PHP Example

Overview – Validate Email Addresses – Javascript and PHP Example

In todays article I will show provide you with source code validate email addresses using either Javascript or PHP. It uses a regular expression to test if the string passed to is a valid email address and returns true or false in either case. It works well for me and will hopefully do the trick for you.

Javascript Example using the function: test()

<script type="text/javascript">

/* validate an email address */
function validateEmail( em ) {
	var pattern = /^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})(\.([a-z]{2,4}))*$/i;
	return (pattern.test(em)) ? true : false;
}

</script>

In order to use the javascript validate email address function, simply include the above function in your javascript or separate include file and then call it using

<script type="text/javascript">
var bValidEmail = validateEmail('somemail@example.com');
</script>

PHP Example using the function: preg_match()

<?php

/* validate an email address */
function validateEmail( $em ) {
	$pattern = '/^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})(\.([a-z]{2,4}))*$/i';
	return preg_match($pattern,$em) ? true : false;
}

?>

In order to use the php validate email address function, simply include the above function in your php or separate include file and then call it using

<?php
$bValidEmail = validateEmail('somemail@example.com');
?>

MySQL INSERT IGNORE – A MySQL Syntax Tip

Overview – MySQL INSERT IGNORE

In MySQL, when you perform a mysql insert query, it is very common to come across errors with one of the insert queries. Once an issue is encountered with a mysql insert, the rest of the mysql inserts will not be executed since the MySQL query won’t continue. This can be annoying since you will have to figure out which rows were inserted and which ones weren’t so you can manually insert the remaining rows.

Fortunately, you can use mysql insert ignore syntax to avoid this frustration by using the keyword ‘ignore’.

MySQL INSERT IGNORE

Consider the following mysql insert statement that would insert two records:

INSERT INTO `table` ('name','surname','email') VALUES ('Mark','Ringo','mark@example.com'),('Sarah','Ainsley','sarah@example.com');

If the first insert (mark ringo) had to fail for some reason, then Sarah would not be inserted UNLESS you add the word ‘ignore’ after mysql insert statement, making the above statement:

INSERT IGNORE INTO `table` .......

Now if the first entry fails, then Sarah will still get inserted. Pretty nifty eh’ and can save countless hours of frustration while trying to import partial records and missing rows from an incomplete mysql insert.

Use With Caution

Please use the mysql insert ignore with caution. Errors and warnings that creep up are there for a reason. MySQL INSERT IGNORE can save a lot of frustration and simplify inserting records however it can end up masking some issues that exist.

Get Total Directory Size In PHP

Overview – Get Total Directory Size In PHP

In my previous article called Get and Display Hard Disk Space Usage Using PHP I demonstrated how you can fetch and display the size of a hard disk as well as the free space and used space and display it to the user. While this works well it still doesn’t show how to get the size of a specific folder using PHP.

Get total directory size in PHP

Below I have created an example showing an alternate method to get total directory size in PHP. It makes use of the shell command du -sh (disk usage) and then uses a regular expression to fetch just the number of bytes out of the output generated by the du command.

<?php

// we need the full path to the folder we want to find the size of
//	below we result in a folder path of /var/www/mywebsite/html/files
$folder = $_SERVER['DOCUMENT_ROOT'].'/files';

// now prevent malicious attacks since we are executing a shell command
$folder = escapeshellcmd($folder);

// make sure this is a folder
if( ! is_dir($folder) )
{
	echo "$folder is not a folder.<br />";
}
// if we could find the pattern of our command du -s
else
{
	// we execute du (disk usage) to find out the folder size
	//	notice we use the execution operator (the key to the left of 1 on your keyboard)
	//	this is the same as the php function shell_exec()
	//	you can add the -h flaf to the below command to format the file size into MB, GB, etc.
	//		i.e. `du -sh $folder`;
	$output = `du -s $folder`;

	if( preg_match('/([0-9]+)(t.*)/',$output,$match) )
	{
		$size = $match[1];

		// $size will now hold the size of the folder
		echo "Folder $folder is $size bytes<br />";
	}
	else
	{
		// error
		// either we can't execute du -s command (such as windows users) or the folder doesn't exist
		echo "Error fetching folder size, are you on Linux? and can you execute commands?<br />";
	}
}

?>