PHP Tip, time and dates

If you find yourself working on a project that deals with dates – for example a calendar or an accounting package – you may need to determine the time at the start of the current week. While there are several ways to do this, the following one-liner will give the necessary value:

$result = mktime(0, 0, 0, date(“m”), date(“d”), date(“Y”)) – ((strftime(“%u”) == 7) ? 0 : (86400 * strftime(“%u”)));

With such a complex statement, a little explanation is in order. Let’s start with strftime(“%u”). This expression gives the current day of the week as an integer in the range of 1 to 7, with 1 representing Monday and 7 representing Sunday, e.g. on Thursday strftime(“%u”) would return 4. This format adheres to an ISO standard, but is awkward to those of us who consider Sunday to be the first day of the week.

We use the current position in the week to determine how many days have elapsed since the most recent Sunday (if today is a Sunday, that value is 0; if today is Wednesday, that value is 3, and so on). We can then subtract that many days – at 86400 seconds apiece – from the timestamp for midnight of the current day. The result is the timestamp for midnight on the first day of this week.

Captain Discipline

About 90 fifth-graders piled into the airliner I was flying, on their way home from a school trip.

Once we were in the air, and the crew began serving drinks, I could hear them pleading with the children to settle down and let the other passengers get some sleep.

No amount of reasoning seemed to help, until I thought of the solution that actually worked.

I picked up the PA mike in the cockpit and announced,

“Children, this is the captain speaking. Don’t make me stop this airplane and come back there!”

PHP Tip, output HTTP headers

By default, the PHP binary will output HTTP headers when you run a PHP script from the command line. While this can be useful if you’re trying to debug a script which sends custom headers, the headers are often unnecessary at the shell. To suppress them, specify the -q flag to the `php` command.

Vice President Pride

Tom was so excited about his promotion to Vice President of the company he worked for and kept bragging about it to his wife for weeks on end.

Finally she couldn’t take it any longer, and told him, “Listen, it means nothing, they even have a vice president of peas at the grocery store!”

“Really?” he said. Not sure if this was true or not, Tom decided to call the grocery store.

A clerk answers and Tom says, “Can I please talk to the Vice President of peas?”

The clerk replies, “Canned or frozen?”

PHP Tip using opendir() and readdir()

Sometimes you may require a list of all of the files in a directory. Such a list can be built using the opendir() and readdir() functions:

<?php
$targetdir = “/var/tmp”;
$files = array();
$directory = opendir($targetdir);
while($filename = readdir($directory)){
#ignore . and ..
if(strlen($filename) > 2){
array_push($files, $filename);
}
}
?>

Upon execution, $files will be an array of filenames (basename only, with no path). If your directory contains files whose names are one or two characters long, you’ll need to replace the strlen() test with a comparison against the literals ‘.’ and ‘..’ in order to avoid adding the current and parent directory names to the array.

PHP Tip, using crypt()

If you need to keep track of users’ passwords for authentication – for example, if members have to login to your site – consider storing their password in an encrypted format instead of plaintext. This way, if your database somehow becomes compromised, the passwords for your user accounts are still somewhat safe.

One way to accomplish this is to run each newly created user’s password through PHP’s crypt() function and store the result:

$password = crypt($_POST[password]);

When the user attempts to login, crypt() the password they provide and compare it against the stored encrypted value. If they match, the password provided by the user was valid.

Impressive Dinner

A young man called his mother and announced excitedly that he had just met the woman of his dreams. Now what should he do?

His mother had an idea: “Why don’t you send her flowers, and on the card invite her to your apartment for a home-cooked meal?”

He thought this was a great strategy, and a week later, the woman came to dinner. His mother called the next day to see how things had gone.

“I was totally humiliated,” he moaned. “She insisted on washing the dishes.”

“What’s wrong with that?” asked his mother.

“We hadn’t started eating yet.”

PHP Tip, using heredoc

If you need to print out a large amount of text or HTML, consider using heredoc notation instead of numerous echo statements. For example, the following code:

echo “This is a test, and this is line 1”;
echo “This is a test, and this is line 2”;
echo “This is a test, and this is line 3”;
echo “This is a test, and this is line 4”;
echo “This is a test, and this is line 5”;

…could be replaced by:

echo <<<EOT
This is a test, and this is line 1
This is a test, and this is line 2
This is a test, and this is line 3
This is a test, and this is line 4
This is a test, and this is line 5
EOT;

You can also insert variables into a heredoc echo:

$username = ‘Foobar’;

echo <<<EOT
<p><font face=’Verdana, Arial’ size=’2′>Hello, $username!</font></p>
<p><font face=’Verdana, Arial’ size=’2′>Welcome to the Members’ Area.</p>
EOT;

Using this method to print out large amounts of text is also substantially faster than calling the echo or print statements over and over again. You can save both keystrokes (when coding) and processor time (when executing) by using heredoc notation.

Doctor's Writing

Did you hear about the doctor who wrote out a prescription in the usual doctor’s fashion?

The patient used it for two years as a railroad pass.

Twice it got him into Radio City Music Hall, and once into Yankee Stadium.

It came in handy as a letter from his employer to the cashier to increase his salary.

And to top it off, his daughter played it on the piano and won a scholarship to the Curtis Music Conservatory.

PHP Tip, generic form mailer

Ever wanted to create a generic web form handler, which can email you the results from all of your site’s forms, similar to the infamous FormMail.cgi? If you have multiple forms and find yourself without the time to write a handler for each one, try using the following script:

<?php
#generic form mailer
while(list($key, $val) = each($_POST)){
if(is_array($val)){
foreach($val as $element)
$body .= “$key: $elementn”;
}
else
$body .= “$key: $valn”;
}
mail(“you@example.com”, “Subject”, $body, “From: you@example.com”);
echo “Thank you! Your submission has been received.”;
?>

This script will take all fields submitted and list them, with both the field name and the submitted value, in an email. For example, if your form contained three fields called name, email, and phonenumber, when submitted, you would be emailed the following:

name: John Doe
email: jdoe@example.com
phonenumber: 555-1212

This generic form mailer is also savvy enough to deal with inbound posted arrays, if you have several form fields with the same name. Suppose your form contained the following HTML:

<input type=”checkbox” name=”hobbies[]” value=”Computers”>Computers
<input type=”checkbox” name=”hobbies[]” value=”Fishing”>Fishing
<input type=”checkbox” name=”hobbies[]” value=”Hiking”>Hiking

If a visitor selected all three checkboxes and submitted the form, you’d receive an email containing:

hobbies: Computers
hobbies: Fishing
hobbies: Hiking

Using a generic form handler can save you a great deal of time, at the expense of “pretty” formatting for the resulting emails. If you’re willing to sacrifice the attractive formatting possible by writing a specific handler for every form on your site, you can literally set all of your forms to post to this script.