6 Must have day to day PHP functions for sysadmins with examples

Yes this is another one of those lists. I find myself using these functions in some variant alot, when chucking together some quick PHP code. I’m putting them all on one page to make it easier to find them, less googling around or trawling through other source code from other projects to grab the functions.

1. Recursive rm

function recursive_rm( $path )
{
    /* open dir handel - return on fail */
    if( !$dir = @opendir( $path ))
    return ( FALSE );

    /* for each file in dir */
    while( ($file = readdir($dir)) !== FALSE )
    {
         /* if not special */
         if($file == '.' || $file == '..')
         continue;

          /* if cant delete path send path back round */
          if(!@unlink($path . "/" . $file))
          $this->recursive_rm( $path . "/" . $file );
    }

    /* close handel */
    closedir( $dir );

    /* rm base dir */
    @rmdir( $path );

return ( TRUE );
}

example usage is simply

recursive_rm("/path/to/delete");

2 . Convert number of seconds to human readable string

If you need to time how log a script takes to run or part of it, this function is a life saver

function secs_to_str($d)
{
    $periods = array( 'day'    => 86400,
                      'hour'   => 3600,
                      'minute' => 60,
                      'second' => 1 );
    $parts = array();
    foreach ( $periods as $name => $dur )
    {
        $div = floor( $d / $dur );
         if ( $div == 0 )
                continue;
         else if ( $div == 1 )
                $parts[] = $div . " " . $name;
         else
                $parts[] = $div . " " . $name . "s";
         $d %= $dur;
    }
    $last = array_pop( $parts );
    if ( empty( $parts ) )
        return $last;
    else
        return join( ', ', $parts ) . " and " . $last;
}

Example usage for this function would be as follows

$start_time = time();

// put your code here
sleep(rand(1,10)); // to give us some test data

$stop_time = time();
$seconds_taken = $stop_time - $start_time;

print( secs_to_str( $seconds_taken ) );

example output for this function

9 seconds
2 hours, 8 minutes and 55 seconds
1 day, 10 hours, 30 minutes and 19 seconds

3. MySQL fetch all rows into multi-dimensional arrray

It’s not always desirable to be working inside a ‘while( $row = mysql_fetch_assoc($qur))’ when you want to do stuff with a table full of data. What can be more flexible is to load the rows into memory as an array in PHP so we can come back to them, re order, filter, modify or what ever you like.

One word of warning however, if you are going to be load ‘alot’ of rows you could run into problems with the amount of memory your PHP code uses, or the time it takes to run. So use this when you feel it’s appropriate.

function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH)
{
  $got=array();
  mysql_data_seek($result, 0);
    while ($row = mysql_fetch_array($result, $numass)) {
        array_push($got, $row);
    }
  return $got;
}

Now after you have preformed the mysql_query() function instead of passing it into a while loop with mysql_fetch_array or similar you can use this function and get returned a multi-dimensional array.

Example MySQL table

mysql> select * from `my_table`;
+----+------------+-------------------+--------------+
| id | film       | staring           | release_date |
+----+------------+-------------------+--------------+
|  1 | Monsters   | Scoot McNairy     | 2010-10-29   |
|  2 | Saw 3D     | Tobin Bell        | 2010-10-29   |
|  3 | Due Date   | Robert Downey Jr. | 2010-11-05   |
|  4 | Jackass 3D | Johnny Knoxville  | 2010-11-05   |
+----+------------+-------------------+--------------+
4 rows in set (0.00 sec)

To return this table as an array

    $qur = mysql_query( "SELECT * FROM `my_table`" );
    $sql_array = mysql_fetch_rowsarr( $qur );

    print_r( $sql_array );

Giving us the following array

Array
(
    [0] => Array
        (
            [0] => 1
            [id] => 1
            [1] => Monsters
            [film] => Monsters
            [2] => Scoot McNairy
            [staring] => Scoot McNairy
            [3] => 2010-10-29
            [release_date] => 2010-10-29
        )

    [1] => Array
        (
            [0] => 2
            [id] => 2
            [1] => Saw 3D
            [film] => Saw 3D
            [2] => Tobin Bell
            [staring] => Tobin Bell
            [3] => 2010-10-29
            [release_date] => 2010-10-29
        )

    [2] => Array
        (
            [0] => 3
            [id] => 3
            [1] => Due Date
            [film] => Due Date
            [2] => Robert Downey Jr.
            [staring] => Robert Downey Jr.
            [3] => 2010-11-05
            [release_date] => 2010-11-05
        )

    [3] => Array
        (
            [0] => 4
            [id] => 4
            [1] => Jackass 3D
            [film] => Jackass 3D
            [2] => Johnny Knoxville
            [staring] => Johnny Knoxville
            [3] => 2010-11-05
            [release_date] => 2010-11-05
        )

)

If you want to return an array with only associative keys call the function with this additional arg

    $sql_array = mysql_fetch_rowsarr( $qur, MYSQL_ASSOC );

Enjoy.

4. Recursive in_array()

This next one is very useful when used with the above function mysql_fetch_rowsarr() if you need to check if a value exists somewhere in the array.

function recursive_in_array($needle, $haystack)
{
    foreach ($haystack as $stalk) {
        if ($needle == $stalk || (is_array($stalk) && recursive_in_array($needle, $stalk))) {
            return true;
        }
    }
    return false;
}

Using the example from 3. we can search the array and look for the release date ‘2010-11-05’

    if ( recursive_in_array( "2010-11-05", $sql_array ) )
    {
        print ( "Release date '2010-11-05' found!" );
    }

5. IPv6 regex with preg_match

IPv6 is coming, I hope you are all ready for it! This function should help you out when developing software that needs to be IPv6 aware.

function valid_ipv6_address( $ipv6 )
{
        $pattern1 = '([A-Fa-f0-9]{1,4}:){7}[A-Fa-f0-9]{1,4}';
        $pattern2 = '[A-Fa-f0-9]{1,4}::([A-Fa-f0-9]{1,4}:){0,5}[A-Fa-f0-9]{1,4}';
        $pattern3 = '([A-Fa-f0-9]{1,4}:){2}:([A-Fa-f0-9]{1,4}:){0,4}[A-Fa-f0-9]{1,4}';
        $pattern4 = '([A-Fa-f0-9]{1,4}:){3}:([A-Fa-f0-9]{1,4}:){0,3}[A-Fa-f0-9]{1,4}';
        $pattern5 = '([A-Fa-f0-9]{1,4}:){4}:([A-Fa-f0-9]{1,4}:){0,2}[A-Fa-f0-9]{1,4}';
        $pattern6 = '([A-Fa-f0-9]{1,4}:){5}:([A-Fa-f0-9]{1,4}:){0,1}[A-Fa-f0-9]{1,4}';
        $pattern7 = '([A-Fa-f0-9]{1,4}:){6}:[A-Fa-f0-9]{1,4}';

        $full = "/^($pattern1)$|^($pattern2)$|^($pattern3)$|^($pattern4)$|^($pattern5)$|^($pattern6)$|^($pattern7)$/";

        if(!preg_match($full, $ipv6))
        return (0); // is not a valid IPv6 Address

    return (1);
}

Basic example usage of this function

$addr6 = "2001:2d12:c4fe:5afe::1";
if ( valid_ipv6_address( $addr6 ) )
{
    printf ( "%s is a valid IPv6 Address!n", $addr6 );
}
else
{
    printf ( "%s is *NOT* a valid IPv6 Address!n", $addr6 );
}

$addr6 = "4d4x:3daz:rdc2:23sd::1";
if ( valid_ipv6_address( $addr6 ) )
{
    printf ( "%s is a valid IPv6 Address!n", $addr6 );
}
else
{
    printf ( "%s is *NOT* a valid IPv6 Address!n", $addr6 );
}

Gives us this output

2001:2d12:c4fe:5afe::1 is a valid IPv6 Address!
4d4x:3daz:rdc2:23sd::1 is *NOT* a valid IPv6 Address!

6. Check if IPv4 address is from a private range.

This function is very handy if you need to allow or stop people from submitting private address spaces into you application. It has many uses.

function ip_is_private($ip)
{
        $pri_addrs = array(
                          '10.0.0.0|10.255.255.255',
                          '172.16.0.0|172.31.255.255',
                          '192.168.0.0|192.168.255.255',
                          '169.254.0.0|169.254.255.255',
                          '127.0.0.0|127.255.255.255'
                         );

        $long_ip = ip2long($ip);
        if($long_ip != -1) {

            foreach($pri_addrs AS $pri_addr)
            {
                list($start, $end) = explode('|', $pri_addr);

                 // IF IS PRIVATE
                 if($long_ip >= ip2long($start) && $long_ip <= ip2long($end))
                 return (TRUE);
            }
    }

return (FALSE);
}

Example of this function being used

$ip_address1 = "10.4.200.1";
$ip_address2 = "192.168.0.2";
$ip_address3 = "213.224.100.43";

if ( ip_is_private ( $ip_address1 ) )
{
    printf ( "%s is from a private address rangen", $ip_address1 );
}
else
{
    printf ( "%s is *NOT* from a private address rangen", $ip_address1 );
}

if ( ip_is_private ( $ip_address2 ) )
{
    printf ( "%s is from a private address rangen", $ip_address2 );
}
else
{
    printf ( "%s is *NOT* from a private address rangen", $ip_address2 );
}

if ( ip_is_private ( $ip_address3 ) )
{
    printf ( "%s is from a private address rangen", $ip_address3 );
}
else
{
    printf ( "%s is *NOT* from a private address rangen", $ip_address3 );
}

Which gives us this output

10.4.200.1 is from a private address range
192.168.0.2 is from a private address range
213.224.100.43 is *NOT* from a private address range

That’s all I’m posting for now, but stay tuned there will be more functions like this to come!

You may also like...