Header image alt text

Sexy To Hay has his Say

Life Sux – than it gets worse!

PHP Tips, register_globals

Posted by Clovis on June 30, 2005
Posted in PHP Tips 

Do you have scripts which suddenly stopped working after you upgraded your PHP version? Chances are, the scripts assumed that register_globals was on (the default for quite awhile) and now that register_globals is disabled by default, the scripts no longer recognize incoming post/get/cookie variables. Add the following lines to your scripts to get them functioning again:

extract($_REQUEST);

extract($_COOKIE);

PHP Tip, using sizeof() or count()

Posted by Clovis on June 29, 2005
Posted in PHP Tips 

If you need to determine the number of elements in an array, you can use either sizeof() or count():

<?
$foo = array(“one”, “two”, “three”);
echo count($foo); //will output 3
echo sizeof($foo); // will output 3
?>

PHP Tip, time and dates

Posted by Clovis on June 28, 2005
Posted in PHP Tips 

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.

PHP Tip, output HTTP headers

Posted by Clovis on June 27, 2005
Posted in PHP Tips 

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.

PHP Tip using opendir() and readdir()

Posted by Clovis on June 25, 2005
Posted in PHP Tips 

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()

Posted by Clovis on June 24, 2005
Posted in PHP Tips 

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.

PHP Tip, using heredoc

Posted by Clovis on June 23, 2005
Posted in PHP Tips 

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.

PHP Tip, generic form mailer

Posted by Clovis on June 22, 2005
Posted in PHP Tips 

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.

PHP Tips building web forms

Posted by Clovis on June 21, 2005
Posted in PHP Tips 

Sometimes when building web forms, you may need to collect multiple values for a single field. Perhaps you have a form which gives a list of common hobbies, and visitors can check all hobbies which interest them. But how do you get PHP to realize that the user has made multiple selections? All you need to do is append square brackets to the end of the field name in your HTML.

For example,

<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 selects all three checkboxes, when the form is posted, your script will have an array named $_POST[hobbies] which contains the three hobbies as its elements.

PHP Tip using flush()

Posted by Clovis on June 20, 2005
Posted in PHP Tips 

You may have noticed that scripts which take a long time to execute often display nothing but a blank “loading” page in the web browser until they finish running. If you find yourself in this situation with a script you’ve written, it’s possible to make the script output incrementally. To do this, use the flush() command. flush() will force the script to send any data in the output buffer to the browser immediately, instead of waiting until execution terminates.

For example, suppose you have a newsletter with several thousand subscribers and because each message contains a unique unsubscription link, the mails must be sent to one recipient at a time. Unfortunately, your script takes upwards of 10 minutes to run, and you’re never sure how far along it is until the entire thing finishes. This can be solved by adding flush() into the loop, to print out a realtime status message after every 100 emails:

<?
$result = mysql_query(‘SELECT DISTINCT email FROM newsletter_subscribers’, $db);
while($myrow = mysql_fetch_array($result)){
$body = ” … body plus unsubscription link would go here … “;
mail($myrow[email], ‘This Month’s Newsletter’, $body, ‘From: newsletter@example.com’);
if($tick % 100 == 0){
echo “$tick messages have been sent…<br>”;
flush();
}
}
?>

Once you use flush() a few times, you’ll start finding more and more places where it comes in handy!