Archive for the ‘PHP’ Category

Sending html e-mails opens a whole can of worms on the many ways e-mail can be viewed. There is also no guarantee your e-mail will look as intended.

Instead of linking to a remote css file that may be blocked, or prompt the user with a scary ‘prevented external content to load’ error message, we can use PHP to pull the file directly. This adheres to the DRY principle and keeps the code base clean.

Use the file_get_contents function in place of linking a style sheet via an html style element.

I would also recommend a try/catch block in case the file_get_contents command fails.


In head section:

<style type="text/css" media="screen">
	<!-- we do this to embed the file contents into the e-mail.
	<?php echo file_get_contents("../common/css/blueprint/screen.css"); ?>

Read Full Post »

Not really a big deal, but could save resources on larger arrays. Is also a clean code practice to avoid awkward traversing array and assigning to ‘itself’ from what is essentially a sub routine.

Does it really matter? Likely not. Using the below script on my 2.66 Core i7 with 8gigs of ram passing by reference is roughly 3-4 times faster. At 100000 array key value pairs the difference is still in microseconds (less than half a millisecond).

More information here: http://php.net/manual/en/language.references.pass.php


// want to loop over an array
$an_array = array();

// lets populate it with random values
for ($i=0; $i < 100000; $i++) { 
	$an_array[$i] = md5(uniqid(uniqid("",true),true));

// start

// now lets maniuplate the 'old' way
foreach ($an_array as $key => $value) {
	// this modifies the value at the index using the array and key
	$an_array[$key] = "ref original array and key";


// lets do it the 'new' way, notice we are passing &
foreach ($an_array as $key => &$value) {
	// $value is a reference to the $an_array[$key]
	$value = "changes source array";
// finish


Sample Executions

Object Pass reference
445 123
455 122
443 122
452 119
446 129

*Note* times in microseconds

Read Full Post »

This month’s date range

I noticed that many people search for ‘this month’s date range’. The trick lies in knowing which month you want to go to and that mktime can automatically find the end of the month by passing 0 into the day field.

Well in no short order here it is:

// casting as date object, otherwise it returns a unix timestamp
$first_of_this_month = date('m/d/y',mktime(0,0,0,date('m'),1,date('y')));
$end_of_this_month = date('m/d/y',mktime(0,0,0,date('m')+1,0,date('y')));

// if run on 4/01/11
// outputs
// string(8) "04/01/11"
// string(8) "04/30/11"

Read Full Post »

Older Posts »

%d bloggers like this: