Here are some examples/snippets to keep you moving on your projects or just to peak your interest.

Code Snippets/Examples

PHP/PostgreSQL and transactions

  • PHP 5.3
  • PostgreSQL 8.4.7

    According to the PHP manual, concatenating multiple queries into one string will cause them to run as one transaction. Very true, but I found that it will also cause you to run out of memory in situations where you have lots of statements. Do this instead:

    pg_query("BEGIN");
    pg_query(_INSERT_OR_UPDATE_1);
    pg_query(_INSERT_OR_UPDATE_2);
    pg_query(_INSERT_OR_UPDATE_3);
    pg_query("COMMIT");
    
    I wasn't truly scientific in my testing, but the amount of memory as reported by 'top' was dramatically less with this method, plus my transaction actually finished, so I'm confident that I'm on the right track.

    Recursive Directory Iteration

    So, you want to traverse a directory (and its subdirectories) in PHP5, huh? This should work for you.

    <?php
    
    $dir="/var/www/html/mysite/";
    
    $rdi = new RecursiveDirectoryIterator("$dir");
    foreach(new RecursiveIteratorIterator($rdi) as $f) {
       echo "$f -- {$f->getMTime()}\n";
       echo "$f -- {$f->getPathInfo()}\n";
    }
    
    /***
     * $f is an object of type SplFileInfo
     * @see http://www.php.net/~helly/php/ext/spl/classSplFileInfo.html
     ***/
    
    ?>
    

    If you just want a single directory without children, try this:

    Non-Recursive Directory Iteration

    <?php
    
    $dir="/var/www/html/mysite/";
    
    $di = new DirectoryIterator( $dir );
    foreach($di as $d ) {
        if (!$d->isDot()) {
            echo $d."\n";
        }
    }
    
    /***
     * @see http://us3.php.net/manual/en/class.directoryiterator.php
     ***/
    
    ?>
    

    SimpleXML and NameSpaces

    Namespaces are a PITA. However, if you know the document you are parsing, they aren't so bad.

    <?php
    
    $simple = simplexml_load_file('http://rss.news.yahoo.com/rss/topstories');
    
    foreach ($simple->channel->item as $i) {
    #   print_r($i);
        $my_media=array_shift($i->xpath('.//foo:my_media));
        print_r($my_media);
    }
    
    ?>
    
    

    HTTP Status Codes

    Short and Sweet - thanks Squid! - http://www.comfsm.fm/computing/squid/FAQ-6.html#ss6.8

    XARGS Fun

  • # -J _REPLACE_ lets you position where the args go
    ls |xargs -J _REPLACE_ -n 5 ./repeat _REPLACE_ foo
     
  • # -n structures how many to send to the command
    ls |xargs -n 5
     
  • # logging - send the command and args to be run:
    ls |xargs -t -n 10 ./repeat 2 > xargs.log
     
  • # limit args sent to command by bytes (command won't run if data exceeds the '-s' value of 2)
    poodlespring-lm:~ supertom$ ls | xargs -s 2 -t ./repeat 
    xargs: insufficient space for command

    Back to Code