|
Saturday, 24 March 2007
A simple little function to calculate whether a specified year is a leap year or not:
function isleapyear($year = '') {
if (empty($year)) {
$year = date('Y');
}
$year = (int) $year;
if ($year % 4 == 0) {
if ($year % 100 == 0) {
return ($year % 400 == 0);
} else {
return true;
}
} else {
return false;
}
}
The algorithm applied above, translated to everyday language, is something like this:
If the year is divisible by 100, then it’s not, unless the year is divisible by 400, when it is. Otherwise, if the year is divisible by 4, then it is. Otherwise, it’s not.
Did you get all that? I know, it’s probably easier to understand by looking at the code.
Monday, 15 January 2007
A good way to improve the security of your website administration login is to restrict the input field length for the username and password to something reasonable. This is commonly done with the “maxlength” attribute in HTML:
<input type="text" name="username" value="" size="30" maxlength="30" />
<input type="password" name="password" value="" size="30" maxlength="30" />
Read more >>
Saturday, 28 October 2006
Most websites have “contact forms”, which allow customers to get in touch with the website owners, without the owners necessarily having to reveal their contact email address. The customer typically fills in their name, email address and some message text. When the customer submits the contact form for processing, the server software then constructs an email message and sends it to the website administrator or owner.
Read more >>
Saturday, 14 October 2006
It’s only recently that I discovered the PHP function fgetcsv(), which offers a quick and powerful way of handling CSV data, such as that exported by Excel and other spreadsheets.
Using fgetcsv(), the process of reading in a CSV file and printing the results in a HTML table is as simple as this:
$fp = fopen('test.csv', 'r') or die('cannot open file');
echo "<table>\n";
while ($line = fgetcsv($fp, 4096)) {
$max = count($line);
echo "<tr>\n";
for ($i = 0; $i < $max; $i++) {
echo "<td>{$line[$i]}</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
fclose($fp) or die('cannot close file');
The real power of fgetcsv() is that it automatically handles the double quotes and any embedded commas which may be present in the source data.
Wednesday, 20 September 2006
Here’s a simple way to strip all whitespace from a string in PHP, which is useful for properly trimming any user input:
function realtrim($mixed) {
if (is_array($mixed)) {
return array_map('realtrim', $mixed);
}
if (strlen($mixed) > 0) {
$mixed = trim(preg_replace('/[\s]+/', ' ', $mixed));
}
return $mixed;
}
The above function will strip all multiple spaces, tabs, line feeds and carriage returns. It also has the capability to accept an array as input, making it particularly suitable for web forms.
|