PHP File-System Cache

I’m just sharing a couple of functions I created a while back to cache some resource-intensive processed dada for quick and easy access. This is pretty ideal for large amounts of data and it’s very simple to set up. The beauty of this is that you can store just about any data type – it doesn’t have to be a string.

Just setup the cache directory to have proper read/write permissions (preferably in a non-accessible from web directory). Then use the two functions.

Example usage:

// The 2nd argument, $hours is how long to retain data before getting new
$contents = get_cache('TEST_KEY', 24);
if ($contents === false) {
	// This is where you'd get data from an API, DB or whatever
	$contents = 'Just some example contents';
	set_cache('TEST_KEY', $contents);
}
echo $contents;
}

Code:

define('CACHE_DIR', 'cache/'); // Include trailing slash

function get_cache($key, $hours) {
	$file = CACHE_DIR . md5($key) . '.cache';
	if (!file_exists($file) || filemtime($file) < time() - $hours * 3600)
		return false;
	return unserialize(file_get_contents($file));
}

function set_cache($key, $value) {
	$file = CACHE_DIR . md5($key) . '.cache';
	file_put_contents($file, serialize($value));
}

HTML Optimizer & Compressor

Quite often I create an HTML file, possibly generated dynamically, that sees a ton of exposure. To save loading time and bandwidth, I optimize/compress the static files (HTML, CSS, and Javascript). I’ve found very good tools for packing Javascript and CSS, Dean Edwards’ packer and CSS Drive’s compressor respectively, but haven’t found a great tool for optimizing HTML. The following tool is something I whipped up in VB.net which simply removes whitespace and comments from HTML and tells you how much disk space you are saving. Careful, it could possibly mess up your javascript or anything else whitespace sensitive (pre tags, etc), but should do the job for most tasks. Admittedly this might be more convenient as a web application, and it wouldn’t take much, but I created it personally for my uses so I can use it offline as well.

Download: HTMLOptimizer.zip (7.92KB)

ASP File_Get_Contents and File_Put_Contents

As I've become more of a PHP developer than an ASP developer, one thing I've noticed is that it is 10x easier to read/write text files with PHP. Simply use file_get_contents() and be done. ASP isn't so nice. But it can be done, so I'm creating those for simplicity here:

<%
Function File_Get_Contents(strFile)
	' Remote File
	If Left(strFile, 7) = "http://" Or Left(strFile, 8) = "https://" Then
		Set objXML = Server.CreateObject("Microsoft.XMLHTTP")
		' Use this line if above errors
		'Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP")
		objXML.Open "GET", strFile, False
		objXML.Send()
		File_Get_Contents = objXML.ResponseText()
		Set objXML = Nothing
	' Local File
	Else
		Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
		Set objFile = objFSO.OpenTextFile(strFile, 1)
		File_Get_Contents = objFile.ReadAll()
		Set objFile = Nothing
		Set objFSO = Nothing
	End If
End Function

Function File_Put_Contents(strFile, strContents, blnAppend)
	If blnAppend Then
		intMode = 8
	Else
		intMode = 2
	End If
	Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
	Set objFile = objFSO.OpenTextFile(strFile, intMode, True)
	objFile.Write(strContents)
	Set objFile = Nothing
	Set objFSO = Nothing
End Function
%>

Of course this file_get_contents doesn't support remote URLs, but it can easily be added.

EDIT: I just added remote URL support.

How to access your cell phone voicemail from another phone


This is certainly no new news, but I’m fairly sure many aren’t aware of this simple feature.

Say you left your phone at home and you were expecting a call, but your friend remembered his phone — tough luck, right?  Nope (obviously, or I wouldn’t have made this post).

Here’s what you can do…just pick up any phone and do the following:

  1. Dial your 10-digit wireless number.
  2. Press the * key when you hear your personal greeting.
  3. Enter your personal passcode.
  4. Follow the voice prompts.

Free Web FLV Flash Player

I’ve used this product multiple times myself, so I thought it would be worthwhile posting it for anyone else looking for a web flash player. The great thing about it is it is very versatile, customizable, and FREE. The JW FLV Media player is suitable to handle FLV, MP4, MP3, AAC, JPG, PNG and GIF formats.

The player, which can play both audio and video, was written by Jeroen Wijering quite a while ago and became very successful. He has since ran with the success and co-founded Longtail Video.

A useful thing to do with this player is to download a copy onto your computer. You can then load FLV’s you’ve downloaded from Youtube, etc. into it and play them offline. This eliminates the need to install a bloated FLV player onto your PC (which likely isn’t a problem for most, but meh.).

To see the video player in action, check out these funny videos.

Classic ASP: More Efficient Database Recordset, GetRows() XoiseRecordset

I’ve created what I believe to be a more efficient recordset object for traversing rows returned from a database query. I implemented all methods/properties that I feel make sense to implement. There’s definite room for improvement, but it’s a good start. My reasoning for creating this is that I like the functionality of using recordsets (via Server.CreateObject("ADODB.Recordset")), but there is a HUGE drawback in that it is horrible on the database. The Server.CreateObject approach makes a database call every time a EOF, BOF, or a traversal method (ie. MoveNext, MovePrevious, etc.) is called.

My fix is to use the GetRows() method to return it as a multidimensional array and just implement my own class with the same (or similar) functionality. There is also an advantage to using this Recordset over just plain using the GetRows() method. I went ahead and implemented a way to extract the column names from the query, which allows you to grab the information using the column name, instead of the index of the array (ie. objRS("Column_Name")). You may also access the data using the column index if you prefer. Note that I haven’t implemented support for "SELECT * FROM Tbl…" syntax, so you’ll HAVE to use the index for this.

There is one main usage difference to note. Rather than opening the recordset with .Open SQL_String, Connection_Object, you must individually update the .Conn and .SQL properties. I’ll most likely change this if there is enough interest and I create a newer version. If I do that, I’ll most likely provide cache support.

Download: XoiseRecordset.zip (1.29KB)

Usage:

Retrieve Data:

  • objRS("Column_Name")
  • objRS.Item("ColumnName")
  • objRS.Row(0)

Implemented Methods/Properties:

  • Conn
  • SQL
  • EOF()
  • BOF()
  • MoveNext()
  • MoveFirst()
  • MoveFirst()
  • MoveLast()
  • Move()
  • GetRows()
  • RecordCount()
  • PageCount()
  • PageSize()
  • AbsolutePage()
  • AbsolutePosition()

How To: Create a Simple Visual “Loading” Effect

If you've got a script that takes a while to load and want to make your user aware that everything is alright, then this tool is for you. The idea is simple – display the message before the labor intensive part of the script runs, and then using CSS after the labor intensive part of the script, hide the message. If you're using a language that provides a buffer (ASP for instance), make sure you turn the buffer off first, or this won't have any effect. (eg. Response.Buffer = False) Example (See it in action):

<?php
ini_set('implicit_flush', 'on');

echo '<p id="loading_msg"><img src="http://img520.imageshack.us/img520/4950/loadingvp7.gif" alt="" style="vertical-align: middle;" /> Loading...</p>';

// Code that takes forever here, could of course be any language
sleep(5); // Only for demonstration

echo '<script type="text/javascript">
window.onload = init;

function init() {
	document.getElementById("loading_msg").style.display = "none";
}
</script>';
echo '<p>Woohoo, five seconds passed.</p>';

require_once('includes/trackers.inc.php');
?>

How to connect your laptop to the internet through your Motorola Razr

I wouldn’t say this is a web tool, but it could certainly come in handy for those who want to use web tools anywhere they can get a cell phone connection!

By now, I’m sure most people are aware that you can connect your laptop to the internet through your cell phone. However, if you’re like I was a couple of hours ago, you don’t know how. It’s really not too bad to do, unless you run into problems.

What you need:

  • Cell Phone
  • USB Cable (you can use bluetooth as well)
  • Not required, but nearly essential: Unlimited data plan (otherwise you’ll rack up HUGE charges)

Here’s a step-by-step for what I did:

  1. Disable EVDO on your phone. Basically, your phone constantly checks two different types of connections, and you’re disabling one of them.  By doing this, you shouldn’t see any difference in your phone’s connection, but you will be able to use your phone as a modem and you will actually get better battery life on your phone.  To disable EVDO, use this guide.
  2. Make sure your Phone is in “Modem/COM” mode. From the main menu, go to Settings -> Connection -> USB Settings. Make sure Default: is set to “Modem/COM.”
  3. Connect your cell phone to your laptop with the USB cable. Your computer should automatically recognize it and install the proper drivers. (Note: Make sure that whenever you do this, you plug it in the same USB port [otherwise it will want to install drivers for each port].)
  4. Open the Device Manager from the Control Panel. Under “Modems,” make sure that you see your phone there (it’ll say something with Motorola in it). If it’s not there, you’re missing some driver. Check out the guides and downloads at HackTheRazr.
  5. If you see your phone under “Modems,” you’re almost there! Follow the following steps to create a new network connection through your phone:
    • Create a new network connection (from the menu in the Network and Sharing Center in Vista or somewhere in the control panel in XP)
    • Choose “Set up a dial-up connection.”
    • For the dial-up phone number, put in #777. Leave the username & password blank. Give your connection name a name of whatever you want. Click connect.
    • BAM. You should be able to use the internet now.

Website Monitoring Service

I use Site24x7 for my website monitoring service – it’s nice because you can be notified via email and/or SMS whenever your site goes down. Sorry, it’s not free – I only use it because I signed up when they started and was grandfathered in. The website I’ve been working on has recently been having a lot of problems and I wanted to keep close tabs on it. This runs into a problem because Site24x7 only allows a maximum of 5 minute intervals for site requests.

A quick search on Google found HostTracker. It’s a handy web tool which does every Site24x7 can do (as far as I can tell). Better than that though, the 30 day trial allows up to 1 minute site request intervals…bingo! Very handy. The site is very easy to use and very helpful. I’d definitely recommend giving it a try.