PHP script to send test emails on a schedule to make sure you are able to receive email

Ever wondered if your email was actually working? I’ve had numerous people over the past few years wonder the same thing. Ideally you would use a consistent, dependable email service provider (think Gmail, Hotmail, Yahoo!, etc.). But sometimes that isn’t an option. If you think you might be receiving email intermittently or not at all, feel free to use this script to send test emails to yourself on a regular basis. If you get the test emails, you know at least someone can get to you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
 
// Set this to your timezone
date_default_timezone_set('America/New_York');
 
// Start at 8:00 AM (24-hour time)
$startTime = mktime(8, 0, 0);
 
// End at 5:00 PM (24-hour time)
$endTime = mktime(17, 0, 0);
 
 
$currentTime = time();
 
// Do not send the email if it is outside of the allowed hours
if($currentTime < $startTime || $currentTime > $endTime)
{
	print('Not sending an email after hours.');
	die();
}
 
// Get the current day of the week as an index (0=Sunday, 6=Saturday)
$dayOfWeek = date('w');
 
// Do not send the email on weekends
if($dayOfWeek == 0 || $dayOfWeek == 6)
{
	print('Not sending an email on the weekends.');
	die();
}
 
// Info of person to receive the tests
define('TO_EMAIL',		'me@test.com');
define('TO_NAME',		'John Doe');
 
// Info of person sending the tests
define('FROM_EMAIL',	'webmaster@serversendingtests.com');
define('FROM_NAME',	'Email Tester');
 
// Example: 8:00 am on 1 Nov 2010
$subject = 'Test: ' . date('g:i a \o\n j M Y');
 
$message = 'This email was automatically generated. Please send an email to yourusername@youremailprovider.com if you would like to disable these automated tests.';
 
$result = mail(TO_NAME . ' <' . TO_EMAIL . '>', $subject, $message, 'From: ' . FROM_NAME . ' <' . FROM_EMAIL . '>');
var_dump($result);

And finally, setup a cron job that runs on a regular basis (every 15 minutes in this case):

*/15 	* 	* 	* 	* 	wget http://myserver.com/path/to/script.php

I realize that you could do some of the scheduling being done in the PHP script in the cron job definition, but I wanted to have more control over that for future features (think pulling schedules from a database for a multi-user environment).

Share

Shorten URLs with Zend Framework and bit.ly

This function uses version 3.0 of the bit.ly API. You’ll need to register for an account with them if you don’t already have one. Then you can retrieve your API key and begin using it immediately.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function bitlyShorten($url)
{
	$client = new Zend_Http_Client('http://api.bit.ly/v3/shorten');
 
	$client->setParameterGet(array(
		'longUrl' => $url,
		'login' => 'xyz',
		'apiKey' => 'xyz'
	));
 
	$response = $client->request();
 
	if($response->isSuccessful())
	{
		$response = Zend_Json::decode($response->getBody());
 
		if($response['status_code'] == 200)
		{
			return $response['data']['url'];
		}
	}
 
	return (false);
}

Example:

1
2
$myLongUrl = 'http://www.jeremyglover.com/blog/';
$myShortUrl = bitlyShorten($myLongUrl);
Share

Force Zend Framework to use the index controller by default

Maze

Everyone wants pretty URLs these days—both for convenience and to optimize for search engines. So having URLs with unnecessary information is a major no-no. Over the past year I’ve been slowly absorbing the Zend Framework and its MVC pattern. Historically, projects I created required the user to specify the index controller like so:


http://www.mysite.com/index/page

…where “index” is the controller and “page” is the action. Since almost all people will be using the index controller, why is it in the URL? Want to get rid of it? Add the following to your application.ini file in the production section:


# Routes
resources.router.routes.default.route = /:action
resources.router.routes.default.defaults.controller = index
resources.router.routes.default.defaults.action = index

Now your application will use the index controller by default so your URLs will be even prettier:


http://www.mysite.com/page

But wait! What if you need to access a different controller? Maybe an admin controller (or module)? Add this beneath the previous addition:


resources.router.routes.admin.route = /admin/:action
resources.router.routes.admin.defaults.controller = admin
resources.router.routes.admin.defaults.action = index

The downside, of course, is that for each additional controller you create, you’ll need to add these three lines to your application.ini file. Luckily for me, I don’t anticipate having very many controllers.

While this technique may seem obvious, I couldn’t find it anywhere on Google. So, if you’re successfully doing this some other way, please share in the comments.

More on the Zend Framework Router

Share

Caching With Zend Framework Using Zend_Cache

Cheeks Blowing

Today I taught myself how to use Zend_Cache and implemented it within 20 minutes. It’s super easy and very effective. Take a look at the code sample below and you’ll be up and running in no time.

 

Step 1: Setup the Cache
{code type=php}
$frontendOptions = array(
‘lifetime’ => 180, // Cache for 3 minutes
‘automatic_serialization’ => true
);

$backendOptions = array(‘cache_dir’ => dirname(__FILE__) . ‘/cache/’);

$cache = Zend_Cache::factory(
‘Core’,
‘File’,
$frontendOptions,
$backendOptions);
{/code}

Step 2: Use the Cache
{code type=php}
$data = null;
if(!$data = $cache->load(‘data’))
{
$service = new Service(API_KEY);
$result = $service->generateReport();
$data = $service->getReport();
$cache->save($data, ‘data’);
}
else
{
print(“Cache Hit!”);
}
{/code}

The page load time went from about 9 seconds to 0.5 seconds! 18x faster and it only took a few lines of code. Awesome.

My main motivation for caching the data ($data in the code example) was actually to reduce the load on the web service which provides the data. We have a good relationship with the company providing the service but there’s a good chance they would become annoyed if we hammered their system to get the exact same data over and over. The load time improvement was a good side effect, though!

For more information on Zend_Cache which comes with the Zend Framework, check out the reference guide and API documentation.

Share

Easy Way to Convert UTC to Current Timezone in PHP


$utc_time = "2009-01-12 21:28:21"; // As pulled from the database
date_default_timezone_set("America/New_York"); // Set to Eastern time (automatically handles daylight savings time)

// Here's the secret: add a Z (for zulu) to the end of your UTC date/time string
$utc_time .= "Z";

// Now convert to the current timezone
$cur_date = strftime("%G-%m-%d %H:%M:%S", strtotime($utc_time)); // Format as YYYY-MM-DD HH:MM:SS


The result: 2009-01-12 16:28:21

How do you handle this? Let me know in the comments.

Share