Code Snippets
Small useful code fractions in PHP
This is a collection of smaller code snippets in PHP to solve some problems.
- Gmail address normalization: recognize name variations belonging to same account
- Highlight PHP code
- Display pagination links
- IP addresses: Anonymize addresses
- IP addresses: Pad IPv4 addresses to the same width
- Math functions
- Get file extension
Gmail Address Normalization
An email address from Google's Gmail can be transformed in various ways into different looking email addresses while still going to the same account. A Gmail user can do the following to have multiple email addresses:
- Using a plus address: gmail+test@gmail.com is really gmail@gmail.com
- Changing the host to
googlemail.com
; gmail@googlemail.com is gmail@gmail.com - Adding additional dots to the name: g.mail@gmail.com still goes to gmail@gmail.com
To see which Gmail email addresses belong to the same account, run them through
gmail_id()
and verify if any of the results are equal.
$mail_part = explode('@', strtolower($mail));
if ($mail_part[1] !== 'gmail.com' && $mail_part[1] !== 'googlemail.com') {
return $mail;
}
$plus_position = strpos($mail_part[0], '+');
if ($plus_position !== false) {
$mail_part[0] = substr($mail_part[0], 0, $plus_position);
}
return str_replace('.', '', $mail_part[0]) . '@gmail.com';
}
echo gmail_id('gm.Ail@gmail.com'); // gmail@gmail.com
echo gmail_id('gmail+test@gmail.com'); // gmail@gmail.com
Other email addresses are returned unmodified.
Note: Do not store the email addresses in this transformed form—it's unexpected to the user to receive mails with a modified address and will cause issues, e.g. for password reset procedures. Additionally, Gmail accounts are registered with whatever dots the user supplied; sending an email to the dot-less version of the address will still work, but Gmail will point this difference out to the user.
Highlight PHP Code
This highlights some PHP code, without the need of the wrapping <?php and ?> tags. (This very function is used on this page.) The result is HTML-compliant.$code = highlight_string('<?php ' . $text . '?>', true);
if (substr($code, 86, 2) !== '<s') {
return '<span style="color: #0000BB">' . substr($code, 79, -57);
}
return substr($code, 86, -57);
}
If you are using PHP 4, you will have to change the numbers 79 and -57 as
highlight_string()
uses the tag <font>
(instead of <span>
) prior to PHP 5.
Anonymize IP Addresses
The following is a function that allows you to show parts of an IP address in a partially anonymized form. It will output an IP address like 178.162.87.50 as 178.162.76.xx.$last_dot = strrpos($ip, '.') + 1;
return substr($ip, 0, $last_dot)
. str_repeat('x', strlen($ip) - $last_dot);
}
echo anonymize_ip('12.34.56.123'); // "12.34.56.xxx"
$last_colon = strrpos($ip, ':') + 1;
return substr($ip, 0, $last_colon)
. str_repeat('x', strlen($ip) - $last_colon);
}
Pad IP Addresses
Pads IPv4 addresses with 0's so that all groups of the address have three digits. This is useful for display purposes as all IP addresses will have the same length, e.g. to make entries in logs align.return implode('.', array_map(function ($entry) {
return str_pad($entry, 3, '0', STR_PAD_LEFT);
}, explode('.', $ip)));
}
echo pad_ip('1.234.56.78'); // 001.234.056.078
Round to First Significant Digits
Function to round a number with many decimals to the first few. For example, if you want to display the difference between two timestamps with microsecond precision, you may want to round the number to the first few digits like "0.00037 s" or "0.06 s" rather than showing "0.000374924 s".By default, the first two non-zero digits are shown after the decimal point, as determined by
$added_digits
. You can change it to 1 or something else to change how many non-zero
digits are shown.
$added_digits = 2;
if ($difference >= 1 || $difference <= -1) {
return $added_digits;
}
preg_match('~.*\.(0*)[^0]~', $difference, $matches);
if (isset($matches[1])) {
return strlen($matches[1]) + $added_digits;
}
return $added_digits;
}
function proper_round($difference) {
return round($difference, proper_precision($difference));
}
echo proper_round(32.9437); // 32.94
echo proper_round(-0.0369); // -0.037
echo proper_round(2.00000); // 2
Ensure That a Parameter is Always Even or Odd
Ensures that a parameter is always odd or even by adding or subtracting 1 to the
number when necessary. get_odd()
adds 1 to even numbers and get_even()
subtracts 1 to odd numbers.
How it works: get_odd()
makes sure that the last bit of the number is a 1,
since numbers whose binary representation end with 0 are even numbers. Similarly, with a few
additional bit flips, get_even()
ensures that the last bit of a number is a 0.
return $n | 1;
}
return ~(~$n | 1);
}
echo get_even(-8) . ', ' . get_odd(-8); // -8, -7
echo get_even(24.9) . ', ' . get_odd(24.9); // 24, 25
If you need to specify whether the functions should add or subtract 1 to make numbers even or
odd, you could use the alternate functions provided below (click on link below to show).
Both functions below add 1 when a "correction" is needed; replace the +
in those
functions with a -
to make them subtract instead when necessary.
Change a Number's Sign
Changing a positive number into a negative and vice versa can be done in one line:return (0 - $in);
}
echo flip_sign('-2.'); // outputs 2
echo flip_sign(0); // outputs 0
If you are using values which cannot be interpreted as numeric values (e.g.
change_pol('abc')
), 0 will be returned. Even at an
error_reporting level of E_ALL, no
error is outputted for any scalar input.
Get File Extension
Detects the file extension from a given string. This function returns the text following the last dot of the file name, so more complicated file extensions such as.tar.gz
are
only returned as ".gz".
$last_dot = strrpos($file, '.');
if ($last_dot !== false) {
return strtolower(substr($file, $last_dot + 1));
}
return 'file';
}
echo file_ext('PAGE.HTML'); // "html"
echo file_ext('config'); // "file"