Standard Packages

Use the PEAR classes,

Secure programming

Check out the SecurePHP wiki.


Some examples of using regular expressions in PHP.

Replacing strings using a regex. Below removes a comment (starting with a hash mark) from a line.

    $line = preg_replace('/#.*/', '', $line);

To see whether a string conforms to a pattern, see below. In this case, the pattern must conform to a valid hostname.

    $pattern = "/^[a-z][a-z0-9-]{1,63}$/";
    if(preg_match($pattern, $name)) {
        return true;

To retrieve some values from a line:

    $line = "RX bytes:35949068 (34.2 MiB)  TX bytes:35949068 (34.2 MiB)";
    $matches = array();
    preg_match("/.*:([0-9]+) .*:([0-9]+).*/", $line, $matches);
    echo "Ouput was: $matches[1], $matches[2]\n";

Rounding off to a 0.05 piece

    $rounded = round($amount * 20)/20;

Default date

This is more of a MySQL issue, but apparently until version 5.1 of MySQL, the 'default' definition of a table column can't hold a function such as NOW(). For this, we'll have to set the current date and time from PHP:

  $query = "update logfile set message = $logmsg, creation_date = " . date('Y-m-d H:i:s');