A faster object in_array() for PHP 5

This is a fast and effective way of find an object in an array.

As of PHP v5.2.2 objects do not have a default response to being cast to (string). To make this tutorial work with newer PHP builds, use spl_object_hash() in place of string casting.

Introduction

When a new object is created in PHP it is assigned an internal numeric id value. The only way to destroy an object (thereby deleting its internal id) is to unset() or nullify (=NULL) all references to the object from within the script. It follows that when an object is destroyed, PHP will fill the lowest id available for the next object. For example: if objects with ids 4, 5 and 6 exist – by destroying 5, the next two objects created in PHP will have id 5 and then id 7!

These rules can be exploited to provide a much faster object in_array()!

Theory

Comparison of multidimensional objects will almost always be more processor intensive than string comparison. It occurred to me that a great deal of time could be saved by identifying objects in an array as strings. However, conventional approaches using serialize() tend to exacerbate the problem further as the function itself is quite slow. The following is the proposed function with a demo on how it could be implemented.


/***
	The proposed object_in_array function.
	***/
	function object_in_array($needle, $haystack) {
		/***
		Arguments:
			(object) $needle - The object being searched for.
			(array) $haystack - The array containing objects.
		***/
		$stringArray = array_map(create_function('$in','return (string)$in;'),$haystack);
		$objectString = (string)$needle;
		return in_array($objectString,$stringArray,TRUE);
	
	}
	
	/***
	Prepare an object needle.
	***/
	$needleObject = new stdClass;
	
	/***
	Prepare a sample array including the
	needleObject.
	***/
	$objectArray = array(
		new stdClass,
		new stdClass,
		new stdClass,
		$needleObject
	); 
	
	/***
	Uncomment the block  below to perform
	an analysis of a much larger array.
	***/
	
	/*
	for($i=0;$i < 50000;$i++) {
		$objectArray[] = new stdClass;
	}
	$objectArray[] = $needleObject;
	*/
	
	/***
	Start time-stamp
	***/
	$timeStamp = get_micro_time();
	
	/***
	NOTE: The print() function is included
	in the time analysis as it doesn't contribute
	much to the overal time required.
	***/  
	print(object_in_array($needleObject,$objectArray) ? "Found!n" : "Not found!n");
	
	/***
	End time-stamp and display.
	***/
	$timeStamp = round(get_micro_time() - $timeStamp,6);
	print("Search duration: $timeStamp ms");
	
	/***
	Auxillary timing function. Sorry,
	I can't remember where I got this function
	from or I would credit the author! Google it :-p
	***/
	function get_micro_time() {
		list($microSec, $sec) = explode(" ", microtime());
		return ((float)$microSec + (float)$sec);
	}

The above can be further optimised (clean-up the temporary array, etc.) but serves to show how the array can be copied, recast and used as a search reference for objects. Modification of the above to use the conventional in_array() or foreach() looping drastically increases the duration of the search! With very little modification to the code, the function could even return the object directly and retain the same array processing speed.

A footnote…

I had previously toyed with the idea of using a single array, casting the objects to strings and storing these as the key for each item (then using array_key_exists() ). If you’re not too worried about using the array keys / don’t use them to store useful data, this latter method can be ten-fold faster than the above example!

Google Syntax Highlighter background-colour bugfix

I found the background for each line of code wasn’t expanding to fit the scroll-area properly when a wide piece of code was being viewed. This has been declared as an official bug and the workaround suggested by brucknerite works nicely.
I have made a few tweaks to his fix so that it displays properly on WordPress. I’ve attached the culprit files to the end of this post.

Download files

shcore.js – upload to /scripts
syntaxhighlighter.css – upload to /styles

* Having troubling getting shCore.js to compress using DEP. It’s probably just a simple syntax niggle, so I will investigate this when I’m less busy!

Write console text to a file (Windows cmd.exe)

Writing directly from the Windows command line to a file might not be something you need to do very often. The famous black and white console is better suited to serving system commands and file operations than being a stand-in for notepad. However, it is sometimes useful to have the option of writing multiple lines of text to a file directly from the trusty prompt.

Method One

This is suitable for creating/overwriting a file with multiple lines of text.

copy con SOME_FILE.txt
Type your text here
You can even have multiple lines!

When finished, press CTRL+Z to confirm your action (or CTRL+C to cancel) and ENTER.

If you want to append some text instead of overwriting it completely, follow as above but using:

copy SOME_FILE.txt + con

Method Two

Open up the command prompt and type:

echo SOME TEXT > SOME_FILE.txt

This method creates/overwrites SOME_FILE.txt with the text you entered before the >. It is only suitable for entering a single line of text into a file.

As with method one, it possible to append text using >> instead of > in the command.

The Easter bunny needs… BLOOD!

That dreaded time of the year has rolled around again! The merriment of the new year stretches back in the vastness of time and examinations fester themselves in thought, like some kind of unstoppable malignant force. With your future dependant on the outcome of sadistically timetabled exams, it is no wonder students gorge themselves on chocolate over Easter…

The blog still has pitifully low content, I am resolving this by drafting several C.I.Y projects, hacks and the like. Hopefully I’ll have some of them in a fit state to post this week, but if coursework and revision prove overwhelming – I might roll them back to next week and do a proper bit of quality control 😉

In the mean time, be careful over this *dangerously stressful* period (hehe!) and remember, don’t let the bunny bite!

Teeths… I has them!

Fixing Google Syntax Highlighter for WordPress

After installing the aforementioned plugin, I soon discovered the CSS was not being implemented correctly! It turned out that in my particular version of WordPress, the default style.css file contained ‘more specific’ CSS properties than the plugin. This lead to the highlighted code looking weirdness… so I fixed it!

This is a 30 second hack – open the default style.css file and search: html>body .entry ul and html>body .entry li removing the html>body part from each.

Open the ‘SyntaxHighlighter.css’ file for the plugin and change the the .dp-highlighter ol li.alt entry to look like this:

.dp-highlighter ol li.alt
{
	background-color: #fff;
	border-top: 0px;
	border-bottom: 0px;
}

Spoof your network adapter MAC address under Windows

Overriding (or spoofing) your NIC / network adapter MAC address can be immensely useful for a number of reasons when using your PC on a large network. In essence you’re creating a new identity for your box and any limitations associated with your previous MAC will no longer affect you! This tutorial will introduce some of the currently existing programs that can automate MAC address spoofing for you, as well as the necessary registry modifications to perform the task manually.

I came across MadMACs some time ago and it has become an invaluable part of my portable network security. Recently I’ve been looking to see what else is out there and found Mac MakeUp which provides a number of advanced features (integration with Wireshark, IP networking options, etc.) and has a straightforward graphical interface.

Both programs have been tested thoroughly and work a treat, but if you feel the only way to do a job properly is to do it yourself, then here is the step by step to DIY MAC spoofage:

  1. Click Start->Run and enter ‘regedt32’ (no ‘ marks) to start up the registry editor.
  2. Find the key:
    HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControl
    Class{4D36E972-E325-11CE-BFC1-08002bE10318}

    and you should have a list of 4 digit subkeys (0000, 0001, 0002 etc.)
  3. Leaving the registry editor window open, go to Start->Run and enter ‘cmd /k net config rdr’ (no ‘ marks).
  4. The console should list your PC and network details. Right click the start of the text next to NetBT_tcpip (the bit that looks like: {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}) and right click->select ‘Mark’. Drag over the whole text (as shown in the brackets previously) and then press CTRL+C to copy to the clipboard.
  5. Go back to the registry editor and click on the first subkey (i.e. 0000).
  6. Click menu Edit->Find (or press CTRL+F). Paste in the text from the console and click ‘Find next’.
  7. It should return a result very quickly (if not – you’ve done something wrong!).
  8. Right click anywhere on the right hand side pane apart from on one of the listed items and choose ‘New->String’. Give the value the name ‘NetworkAddress’ (case sensitive, no ‘ marks) then simply double click it and enter a new MAC address!
  9. Reboot your machine and enjoy!

For more information, check this Wikipedia article on MAC addresses.

Download videos from ALL flash streaming video sites

You read the title correctly, this tutorial will show you how to download videos from any site that hosts FLV streaming videos (e.g. veoh, youtube etc.) what’s more, you don’t need to use any annoying 3rd party software!

  1. If you’re not using Firefox, download and install it.
  2. Find the video you want to download using Firefox. For example, from veoh.com. BUT DON’T WATCH IT YET!

    download_flv_1.jpg

  3. Open a new tab and type ‘about:cache’ (excluding ‘ marks) into your Firefox address bar.

    download_flv_2.jpg

  4. Copy the path (text) from next to ‘Cache Directory’ and paste it into your address bar. You should get a page like the one below.

    download_flv_3.jpg

  5. This is where it can get a little bit tricky, not too hard though 🙂 To make things easier it might be a good idea to clear your Firefox cache (click ‘Tools->Clear Private Data’ and make sure that ‘Cache’ is ticked). Go back to the tab showing your cache information and click refresh (or press F5).
  6. Now click on the video in the first tab and it should start to load. While it is doing this, switch back to your cache view and click refresh – the list of links/files should be growing! Keep clicking refresh (or tapping F5) until the list stops growing.
  7. If you look at the second column in the cache view, it will show the size of each file in the cache. Once the list has stopped growing, you should see most of the file sizes stay constant – except for one! This will be your video file.

    download_flv_4.jpg

  8. Switch back to the site containing the video (e.g. veoh) and wait for the video to load completely.
  9. Click on the cache view tab again and (without refreshing) right click and choose ‘Save link as…’ on the cache file that was growing in size.
  10. Rename the file to something useful and include .flv at the end of the file (like ‘panda_sneezes.flv’). You can now watch this video from your desktop with an FLV player.

There you have it, 10 steps to download flash videos streaming videos from any site.

Fixing printer lockups under Windows

If you’re like me and depend upon being able to print documents on the go, Windows can sometimes be very unaccommodating! One of my main problems is printer service lockup if I lose my connection to the printer (accidentally unplugging the USB cable for
example). When this happens, no matter how many times I try to cancel the frozen print job it just won’t go away – preventing any more documents from being printed out! Fortunately… I have a rapid solution at hand.
Three easy steps:

  1. Ctrl + Alt + Del, bring up task manager.
    printer_fix_1.jpg
  2. Select ‘spoolsv.exe’ from the processes list and click End Process.
    printer_fix_2.jpg
  3. Use either File->Run in task manager (or Start->Run from the taskbar) and enter ‘spoolsv.exe’.
    printer_fix_3.jpg

This is a dirty (but effective) way of forcing the print spool server to reboot. You should see the document queue clear within a minute or so and then you will be able to send new documents to your printer.

Accessing private properties in PHP 5 objects

With the introduction of PHP 5 comes the ability to define class properties and methods in a more traditional style to C++ and other popular OOP languages. The three major distinctions are Public (designated by default), Private and Protected.

Demonstration:

class TestClass {

 	public $VarA = 'I am public!';
 	private $VarB = 'I am private!';
 	protected $VarC = 'I am protected!';

}

$NewInstance = new TestClass;

print($NewInstance->VarA); /* No problem */
// print($NewInstance->VarB); /* Error */
// print($NewInstance->VarC); /* Error */

$NewInstance is initiated as an instance of TestClass. $VarA can be easily accessed using $NewInstance->VarA, however trying to access VarB and VarC in the same manner will generate an error as they are designated inaccessable outside the current class (or sublcasses in the case of VarC). It is sometimes necessary to access Private and Protected object variables and this can be achieved very easily using just one line of code:

 	var_dump( (array) $NewInstance );

This will generate a dump containing a list of all object properties, including private and protected variables. Each will have an assigned key that follows the pattern of:

[“?class name?private property name”] = PRIVATE PROPERTIES
[“?*?protected property name”] = PROTECTED PROPERTIES

By type-casting to an array, the object properties are forcibly revealed in the same way you can reduce an object to a string using serialize().