Category Archives: Software Development

This category contains all my posts about software development. Tutorials, solutions to problems I’ve met, interesting things I’ve stumbled over, code samples, stuff I don’t want to forget, et cetera.

Excel: Function for nslookup in worksheet

Just a copy of a function I found in a blog post for doing nslookup calls in a worksheet, in case I need it again in the future. I’ve changed the return value for failing lookups to a blank string, “”, rather than “NotFound”, but otherwise it’s unchanged.

Usage, given an IP in cell A1, to get the hostname: =NSLookup(A1; 2)

Public Function NSLookup(lookupVal As String, Optional addressOpt As Integer) As String
   Const NAME_LOOKUP = 2
   Const AUTO_DETECT = 0
   'Skip everything if the field is blank
  If lookupVal <> "" Then
        Dim oFSO As Object, oShell As Object, oTempFile As Object
        Dim sLine As String, sFilename As String
        Dim intFound As Integer
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        Set oShell = CreateObject("Wscript.Shell")
        'Handle the addresOpt operand
       'Regular Expressions are used to complete a substring match for an IP Address
       'If an IP Address is found, a DNS Name Lookup will be forced
       If addressOpt = AUTO_DETECT Then
            ipLookup = FindIP(lookupVal)
            If ipLookup = "" Then
                addressOpt = ADDRESS_LOOKUP
                addressOpt = NAME_LOOKUP
                lookupVal = ipLookup
            End If
        'Do a regular expression substring match for an IP Address
       ElseIf addressOpt = NAME_LOOKUP Then
            lookupVal = FindIP(lookupVal)
        End If
        'Run the nslookup command
       sFilename = oFSO.GetTempName
        oShell.Run "cmd /c nslookup " & lookupVal & " > " & sFilename, 0, True
        Set oTempFile = oFSO.OpenTextFile(sFilename, 1)
        Do While oTempFile.AtEndOfStream <> True
            sLine = oTempFile.Readline
            cmdStr = cmdStr & Trim(sLine) & vbCrLf
        oFSO.DeleteFile (sFilename)
        'Process the result
       intFound = InStr(1, cmdStr, "Name:", vbTextCompare)
        If intFound = 0 Then
            NSLookup = ""
            Exit Function
        ElseIf intFound > 0 Then
            'TODO: Cleanup with RegEx
           If addressOpt = ADDRESS_LOOKUP Then
                loc1 = InStr(intFound, cmdStr, "Address:", vbTextCompare) + InStr(intFound, cmdStr, "Addresses:", vbTextCompare)
                loc2 = InStr(loc1, cmdStr, vbCrLf, vbTextCompare)
                nameStr = Trim(Mid(cmdStr, loc1 + 8, loc2 - loc1 - 8))
            ElseIf addressOpt = NAME_LOOKUP Then
                loc1 = InStr(intFound, cmdStr, "Name:", vbTextCompare)
                loc2 = InStr(loc1, cmdStr, vbCrLf, vbTextCompare)
                nameStr = Trim(Mid(cmdStr, loc1 + 5, loc2 - loc1 - 5))
            End If
        End If
        NSLookup = nameStr
        NSLookup = "N/A"
    End If
End Function

Function FindIP(strTest As String) As String
    Dim RegEx As Object
    Dim valid As Boolean
    Dim Matches As Object
    Dim i As Integer
    Set RegEx = CreateObject("VBScript.RegExp")
    RegEx.Pattern = "\b(?:\d{1,3}\.){3}\d{1,3}\b"
    valid = RegEx.test(strTest)
    If valid Then
        Set Matches = RegEx.Execute(strTest)
        FindIP = Matches(0)
        FindIP = ""
    End If
End Function


PHP: Stream a file line-by-line using a generator

This function will “stream” a file line-by-line, as a Generator.

Can be very useful if for example you need to process a big file, don’t want to read the whole thing into memory, but only process each line by itself.

function read($file)
    $fp = fopen($file, 'rb');

    while(($line = fgets($fp)) !== false)
        yield rtrim($line, "\r\n");


// Usage
foreach(read('') as $line)

CSS: Super simple design guides

Needed to see if I had lined some stuff up correctly on a website I’m making. Came up with this simple CSS to add two guides to the page that I can move around freely in the browser developer console (just nudge their position around to where I need them).

It’s really simple, but for some reason didn’t think of it until now…

html::after {
    content: "";
    height: 1px;
    width: 100%;
    background: red;
    position: fixed;
    left: 0;
    bottom: 5px; /* Change this to move the guide horizontally */
html::before {
    content: "";
    height: 100%;
    width: 1px;
    background: red;
    position: fixed;
    top: 0;
    right: 5px; /* Change this to move the guide vertically */

PHP: Delete directory recursively

function delete_directory($dir)
    if( ! file_exists($dir))

    $it = new RecursiveDirectoryIterator($dir);
    $it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($it as $file)

PHP test script for cross origin proxy target

Just a script I used as target during some testing of a cross origin proxy to make sure whatever I thought should go through actually went through.

<?php // test.php
$info = [
    'method' => $_SERVER['REQUEST_METHOD'],
    'cookie' => $_COOKIE,
    'get' => $_GET,
    'post' => $_POST,
    'input' => file_get_contents('php://input'),
    'headers' => getallheaders(),

header('Content-Type: application/json; charset=utf-8');
header('X-SomeHeader: Some value');

PHP: Easy Javascript compression with closure compiler

Here’s how to fairly easily compress/minify Javascript by using the Closure Compiler Service API.

More or less verbatim how I’m currently doing it over at in my script controller class, and so far it’s been working great. Just remember to cache the result on your server so that you’re not calling the API more than necessary. In my case it’s handled further up the chain by the parent class 🙂

header('Content-Type: text/javascript; charset=utf-8');

$files = ['foo.js', 'bar.js'];

$js = array_map('file_get_contents', $files);
$js = implode(PHP_EOL.PHP_EOL, $script);

$c = curl_init();
curl_setopt_array($ch, array
    CURLOPT_URL => '',
    CURLOPT_POSTFIELDS => http_build_query([
        'language' => 'ECMASCRIPT5',
        'output_info' => 'compiled_code',
        'output_format' => 'text',
        'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
        'js_code' => $js,

if(curl_exec($ch) === FALSE)
    http_response_code(500) and exit("// ERROR: ".curl_error($c));

if(curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD ) <= 1)
    echo $js;


Note that if the compilation fails for any reason, the response will be empty. In that case I’ve chosen to output the original Javascript instead so the site doesn’t suddenly break. To check what went wrong, you need to repeat the request, but output_info set to errors instead of inline=”true”>compiled_code.

See their API documentation for more information about the parameters.

PHP: Array key whitelist and blacklist

Keep forgetting… writing it down so I can stop googling it…

function whitelist(array $array, array $whitelist)
    return array_intersect_key($array, array_flip($whitelist));

$filtered = whitelist($array, ['good1', 'good2', ... ]);
function blacklist(array $array, array $blacklist)
    return array_diff_key($array, array_flip($blacklist));

$filtered = blacklist($array, ['bad1', 'bad2', ...]);