PHP: Disable output buffering for the CLI

When writing a PHP application that's going to be run from the CLI often you will want to disable output buffering. With output buffering enabled you will not see any output until your terminal buffer (usually 1k or 4k) fills up . This is accomplished with the following PHP code at the beginning of your script:

ob_get_flush();
Leave A Reply

CentOS: Multiple static IPV6 addresses

I needed to apply multiple static IPV6 addresses to a single interface under Fedora/CentOS. To do this you'll need to add an IPV6ADDR_SECONDARIES line to your /etc/sysconfig/network-scripts/ifcfg-eth0 so that it looks like this:

IPV6_DEFAULTGW=2001:db8::1
IPV6_AUTOCONF=no
IPV6ADDR=2001:db8::50/64
IPV6ADDR_SECONDARIES="2001:db8::40/64 2001:db8::30/64"

Note: Addresses are added in reverse order. Outbound traffic will use the last secondary IP added.

Leave A Reply

PHP: IPV6 reverse DNS entries

Reverse DNS (PTR) entries in IPV6 are different than their IPV4 counterparts. To create an IPV6 reverse entry, you have to: fully expand the address, reverse it, and add a period between each character.

For example: 2001:db8::60 reverses to 0.6.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.

I wrote a simple PHP function to handle this for me:

function ipv6_ptr($ip_str) {
    $hex = unpack("H*hex", inet_pton($ip_str));
    $str = strrev($hex['hex']);
    $p   = str_split($str);
    $ret = join(".",$p);

    return $ret;
}
Leave A Reply

Books of 2016

List of books I read in 2016, also see the list of 2015. The date indicated denotes the date I started reading the book.

2016-01-08- Avenue of Mysteries - 460 pages
2016-01-22 - The Girl on the Train - 323 pages
2016-02-01 - Star Wars: The Force Awakens - 260 pages

Leave A Reply

Raspberry Pi: SD Card comparison

Jeff Geerling posted a great speed comparison of SD cards. Good break down of what to buy next time you're buying SD cards for your Raspberry Pi.

Short version: buy either the Samsung EVO+ or SanDisk Extreme SD cards.

Leave A Reply

KVM: Passing a port from your public NATd IP to an internal VM host

If you're using KVM's "default" network to provide NAT to your VMs you may want to map certain inbound ports to a specific VM. Using these iptables commands and destination NAT you will be able to connect to your VMs using a single outward facing IP.

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -t nat -A PREROUTING -p tcp --dport 2222 -j DNAT --to 192.168.122.32:22
Leave A Reply

NFS: List exported filesystems

If you want to list what filesystems are exported via NFS on a remote host use this command:

showmount -e 192.168.1.12

You should get output like this:

Export list for 192.168.1.12:
/volume1/multimedia 192.168.1.0/24
/volume1/sales 192.168.1.0/24
/volume2/users 192.168.1.0/24
Leave A Reply

SSH: Batch mode for SSH/SCP scripting

SSH is great for scripting file transfers between two trusted hosts when you're using SSH keys. If you are using SSH keys to automate SSH commands you will want to make sure your SSH commands are using BatchMode. With BatchMode enabled the SSH connection will fail immediately if the key is rejected, instead of failing back to a password prompt. This will prevent your scripts from "hanging" while it waits for you to type a password.

ssh -o BatchMode=true user@domain.com
scp -q -o BatchMode=true user@domain.com:/tmp/
Leave A Reply

PHP: is_exception()

I have an object in PHP that I need to check if it is an exception and act appropriately. Surprisingly PHP does not have an is_exception() function built in so I had to write my own:

function is_exception($obj,$strict = false) {
    if (!is_object($obj)) {
        return false;
    }

    // It's some type of exception
    if ($obj instanceof Exception) {
        if (!$strict) {
            return true;
        // It's a raw exception
        } elseif (get_class($obj) === "Exception") {
            return true;
        }
    }

    return false;
}

If you pass true as the second parameter it will only return true if it's a raw exception and not an inherited exception.

Leave A Reply

PHP: Relative path between two directories

I need to calculate the relative path between two directories such that:

$a = "/one/two/three/four/";
$b = "/one/two/";

$a to $b has a relative path of ../../ and $b to $a has a relative path of three/four/. This function solves that problem very simply:

// Borrowed from http://php.net/manual/en/function.realpath.php#105876 and cleaned up
function relativePath($from, $to, $ps = DIRECTORY_SEPARATOR) {
    $arFrom = explode($ps, rtrim($from, $ps));
    $arTo   = explode($ps, rtrim($to, $ps));

    while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0])) {
        array_shift($arFrom);
        array_shift($arTo);
    }

    return str_pad("", count($arFrom) * 3, '..' . $ps) . implode($ps, $arTo);
}
Leave A Reply

Perl: Natural Sort

I have a array with a bunch of names like vlan-1, vlan100, vlan34 which do not sort appropriately using Perl's standard sort() function. Sort::Naturally to the rescue! I didn't want to install an entire module for one sort operation, and require a dependency, so I ripped out just the natural sort function and included that in my script.

sub nsort {
    my($cmp, $lc);
    return @_ if @_ < 2;   # Just to be CLEVER.

    my($x, $i);  # scratch vars

    map
        $_->[0],

    sort {
        # Uses $i as the index variable, $x as the result.
        $x = 0;
        $i = 1;

        while($i < @$a and $i < @$b) {
            last if ($x = ($a->[$i] cmp $b->[$i])); # lexicographic
            ++$i;

            last if ($x = ($a->[$i] <=> $b->[$i])); # numeric
            ++$i;
        }

        $x || (@$a <=> @$b) || ($a->[0] cmp $b->[0]);
    }

    map {
        my @bit = ($x = defined($_) ? $_ : '');

        if($x =~ m/^[+-]?(?=\d|\.\d)\d*(?:\.\d*)?(?:[Ee](?:[+-]?\d+))?\z/s) {
            # It's entirely purely numeric, so treat it specially:
            push @bit, '', $x;
        } else {
            # Consume the string.
            while(length $x) {
                push @bit, ($x =~ s/^(\D+)//s) ? lc($1) : '';
                push @bit, ($x =~ s/^(\d+)//s) ?    $1  :  0;
            }
        }

        \@bit;
    }
    @_;
}

This is a slightly more portable version rather than maintaining the Sort::Naturally dependency.

Leave A Reply

Bash: Use previous expression parameters

I was running a bash command similar to this:

perl /var/www/scott/perl/test/scott.pl --size 10 --file /tmp/output.txt

and afterwards I wanted to make a small change to that script. Rather than typing out the full path you can use some Bash history expansion and do this instead:

vim !:1

If you use !: followed by a number, Bash will replace that with the Xth (starting at zero) parameter from the previous command.

Leave A Reply

Reddit: Pinky and the Brain theory

Mind Blown!

The Idea is, that Pinky is in fact, a genius who lives with the insane Brain to keep him in check and to make sure he doesn't do anything too dangerous. There is a good amount of evidence to support this in the show.

We see a few examples, starting with the introduction song. There is a line that goes, "One is a genius, the other is insane, pinky and the brain." We already see a few hints from this. During the course of the show, there is never a question that pinky is not insane. An imbecile? Most certainly, but we never have a reason to believe he is insane. On the other hand, Brain is clearly insane - he is constantly trying to devise ways to take over the world. If Brain is infact insane, this leaves pinky to be, well, the genius

The biggest piece of evidence however, comes from an episode where Brain creates a machine to make Pinky smart. Pinky steps into it and begins to massively outsmart Brain - winning game shows, correcting him, and at the end of the episode - He shows how Brain's machine is inherently flawed and doesn't work at all. Almost immediately afterwords he returns to his bumbling self.

The begs the obvious question - if the machine never worked, how was Pinky so smart, and able to actually point out this design error? Simple, he is infact the genius.

Finally, there's the fact that Brain's inventions almost never work - they blow up in his face, and when they do work, they are sabotaged by none other than Pinky.

There's several more examples within the show, but when you look at the whole it becomes very convincing, that Brain is in fact being watched by Pinky, who is playing off the whole affair.

Borrowed from Ginnex on Reddit.com

Leave A Reply

SQLite: Case insensitive search

If you want to search a field in SQLite you might use a query like this:

SELECT MyID FROM Table WHERE Name = 'Doolis';

This performs a case-sensitive search on the Name field. If you want to search the name field in a case-insensitive manner do this:

SELECT MyID FROM Table WHERE Name = 'Doolis' COLLATE NOCASE;
Leave A Reply

Linux: Fedora 22 major package versions

Fedora 22 has been released and I gathered the versions of some core packages:

Package Version
Perl 5.20.2
PHP 5.6.9
Vim 7.4.640
Apache 2.4.12
Kernel 4.0.4
Leave A Reply