Apr
4
Find Time Between Two Dates in PHP
Posted by john in php, programing

Below is a quick PHP function that allows you to find the time between two dates. The dates must be in seconds from Unix Epoch.

if(!function_exists(timeBetween))
{
	function timeBetween($start_date,$end_date)
	{
		$diff = $end_date-$start_date;
 		$seconds = 0;
 		$hours   = 0;
 		$minutes = 0;

		if($diff % 86400 <= 0){$days = $diff / 86400;}  // 86,400 seconds in a day
		if($diff % 86400 > 0)
		{
			$rest = ($diff % 86400);
			$days = ($diff - $rest) / 86400;
     		if($rest % 3600 > 0)
			{
				$rest1 = ($rest % 3600);
				$hours = ($rest - $rest1) / 3600;
        		if($rest1 % 60 > 0)
				{
					$rest2 = ($rest1 % 60);
           		$minutes = ($rest1 - $rest2) / 60;
           		$seconds = $rest2;
        		}
        		else{$minutes = $rest1 / 60;}
     		}
     		else{$hours = $rest / 3600;}
		}

		if($days > 0){$days = $days.' days, ';}
		else{$days = false;}
		if($hours > 0){$hours = $hours.' hours, ';}
		else{$hours = false;}
		if($minutes > 0){$minutes = $minutes.' minutes, ';}
		else{$minutes = false;}
		$seconds = $seconds.' seconds'; // always be at least one second

		return $days.''.$hours.''.$minutes.''.$seconds;
	}
}

Usage Example:

$one_date = date("U");
$two_date = date("U", mktime(0,0,0,4,1,2008));
echo timeBetween($one_date, $two_date).'';
// displays "x days, x hours, x minutes, x seconds"



Feb
15
UPDATED: Strip Off Characters from String Using PHP (substr)
Posted by john in php, programing

substr_icon.jpgAlmost a year ago I wrote a quick article on how you can strip off characters using PHP’s built in function substr. But after reading it again, even I was not clear how it worked so how would it ever help anyone.

First, if you only want to pull on character from a string, it’s a lot easier to use the following:

$string = 'puppy';
echo $string[0]; // p
echo $string[1]; // u
echo $string[2]; // p ...and so on

Here’s the basic concept behind substr:
substr($string, start # [, length #]) - length is in brackets because it’s optional
Read the rest of this entry »



Feb
6
Alternate Background Colors Using PHP
Posted by john in javascript, php, programing

background_change.gifYou now can look in almost any website or web application where the background colors are alternating. This is a great (and easy) way to improve the user interface for the end users.

Here’s a quick explanation of what’s going on in the demo file below:

First we set the alternating backgrounds we want to use.

$bg1 = "#f5f5f5";
$bg2 = "#FFFFFF";

Then as we pass through a loop of some kind this code snip rotates the variable $bg to the background colors we set above:
$bg = ($i++ & 1) ? $bg1 : $bg2;

In the example files, we’ve added some javascript to the table
’s to add an additional hover effect as well as some styling to improve the look of the tables.

Demo | Source File

Comment if you have any questions or suggestions.



May
28
Does Bellsouth know My Twin Brother?
Posted by john in funny, mysql, pictures, programing

I was going to be a good Bellsouth customer and try out their new “free” personality test when I get this SQL error.

bellsouth_large.jpg
This can mean a whole heap of personal issues I’m going to have to deal with:

  1. I really do have a twin brother!
  2. I’m so common I get a SQL duplcate enty error. :(
  3. My friends at work won’t let me in, now Bellsouth’s database.

Thanks Bellsouth for boosting my self-asteam one more notch up!



Apr
25
PHP File Last Modified and Filesize (bytes to KB/MB)
Posted by john in php, programing

Here’s a quick snip of code to help you easily manage your files by finding out the time the file was created or modified and also the time of the file.

$file = 'image.jpg';

// FILE TIME
$filetime = filemtime($file); // displays in Seconds since the Unix Epoch
echo date("M j, Y", $filetime); // would display the file creation/modified date as Feb 3, 2007

// FILE SIZES
$filesize = filesize($file); // displays in bytes
$file_kb = round(($file / 1024), 2); // bytes to KB
$file_mb = round(($file / 1048576), 2); // bytes to MB
$file_gb = round(($file / 1073741824), 2); // bytes to GB
// PHP does funny thing for files larger than 2GB



Mar
29
Strip Off Characters from String Using PHP (substr)
Posted by john in php, programing

Here’s a quick way to strip off characters from a string using PHP’s function substr.

<?
$var = ‘05 Delete’;
$var = substr($var,0,2);
echo($var); // returns “05″
?>

If you wanted to strip off the characters from the end of a string, just change the “2″ to “-2″ and it will strip off the last two characters.



Mar
22
Turn 2D Array into a HTML Dropdown with PHP
Posted by john in php, programing

Just another quick way to automate the simple process of creating HTML selects with a function. This small function with also remember which value was selected by checking it against the $_POST value and adding a selected="SELECTED" to that option.

2 dimentional array:

$people_array = array(
   '1' => 'Bob',
   '2' => 'James',
   '3' => 'Jessi',
   '4' => 'Sam');

Just call this function either through a request(…) or just simply adding it to the file’s code:

function array2select($array, $post_field){
	foreach($array as $key => $value){
		if($post_field == $key){$selected = ' selected="SELECTED"';}
		echo ''.$value.'';
 		$selected = false;
	}
}

Then just add it where you want the select to do:

< select name="people" >
echo array2select($people_array,$people);
< /select >

This is pretty basic, but it should give you an idea on how arrays and functions can be used together to help speed up projects and automate these basic tasks.



Mar
21
Display Last.fm’s Recent Tracks on Web Site with PHP Function
Posted by john in music, php, programing

Being a very big music buff, I love being able to see what my music habits are. I’m currently using the most up-to-date version of Winamp, which does a good job of keep a history of what I listen to, but I wanted this info on the web for the world to see.

Fortunatly, Last.fm has this sweet software that “scrobbles” or sends your track data via a third part plugin to Winamp to their servers which out puts in return to a standard text file. (check out Last.fm anyway if you’re into music - it’s a cool way to meet people with similar music tastes.)

Just call up this function and echo it as followed.

// Program: recenttracks.php
// By: linein.org
// Date: 11.3.2006
// File format: timestamp,artist - track

// your last.fm username

function recenttracks($user)
{
// location on server where the cached file will be located (it must be absolute and the folder must have full (777) permission)
$cache = "$_SERVER[DOCUMENT_ROOT]/media/recenttracks.txt";

// sets played date using PHP date
$date_format = 'g:i a m.d.Y'; // 10:31 am 11.03.2006

// display styles
$track_num_style = 'font-family: arial; font-size: 10px; color: #666;';
$artist_style = 'font-family: arial; font-size: 11px; color: #fff;';
$track_style = 'font-family: arial; font-size: 11px; color: #fff;';
$date_style = 'font-family: arial; font-size:9px; color: #666;';
$dash_style = 'font-family: arial; font-size:9px; color: #999;';

// you could add here the ability to only cache ever 30 min or so, but I like it live
filemtime($cache);
$update = @file_get_contents("http://ws.audioscrobbler.com/1.0/user/$user/recenttracks.txt");
$f = fopen($cache, "w");
fwrite($f, $update);
fclose($f);

$cache = file_get_contents($cache);
$cache = str_replace( '–', '-', $cache ); // replaces en dash with regular dash (thanks MrSomeone - http://www.last.fm/user/MrSomeone/)
$cache = explode("\n", $cache);

$track_num = 1; // starting track number (you could change to count($cache) and count down)
foreach($cache as $data)
{
if(!empty($data))
{
$info = explode(",", $data, 2); // sperates date by only seperating at fist instance of a comma (since some artist/track have comma in their names

$played_time = $info[0];
$info_track = explode(" - ", $info[1]); // seperates artist and title

$artist = $info_track[0];
$title = $info_track[1];

$listingto .= ''.$track_num.')
'.$artist.'
-
'.$title.'
('.date("$date_format", $played_time).')

';
$track_num++; // adds 1 to track number
}
}
return $listingto;
}

(download as text)

Then once you’ve called the function:

$last_fm_username = 'linein_org';
$recent_tracks = recenttracks($last_fm_username);

Example with formating.

Feel free to change the function (especially the styles) to fit your needs, but please do give credit where it’s needed. I’m currently using a modified version to not only display these tracks, but to store them into a MySQL database which allows me to keep track of my music history. check it out here



Mar
21
MySQL Return Single Data or Single Array with PHP
Posted by john in mysql, php, programing

Quite a few times during projects I only want to find a single value from the database. But rather than setting up WHILE loop, I’ve been using a quick function that does two things perfectly.

Here’s the function:

// returns single result
function mysql_one_data($query)
{
   $one=mysql_query($query);
   $r=mysql_fetch_row($one);
   return($r[0]);
}

// returns single array
function mysql_one_array($query)
{
   $one=mysql_query($query) or die (mysql_error());
   $r=mysql_fetch_array($one);
   return($r);
}

Say for example I wanted just the date of a record. All I have to do is make sure to call the function and then do the following:

// single value
$date = mysql_one_data("SELECT date FROM records WHERE id='2' LIMIT 1");

// single array
$date_info = mysql_one_array("SELECT firstname, lastname, date FROM records WHERE id='2' LIMIT 1");

// you can then use the single $date_info array like
echo $date_info['firstname'].' '.$date_info['lastname'].' ('.$date_info['date'].')';

Just let me know if you have any questions about this.



Jan
29
USA State Array for HTML Select
Posted by john in php, programing

After coding for a while things no longer become “fun” to do over and over. One of those things for me is forms and particularly for this article a state drop down.

Below is an array of all the current states along with a quick example of how to use it. Read the rest of this entry »



« Previous Entries |