PHP: Return a random element from an array

Getting a random element from a PHP array is a multi-step process and I often forget the syntax. Here is a simple function that will return a random element from the provided array.

function random_elem(array $arr) {
    $key = array_rand($arr);
    $ret = $arr[$key];

    return $ret;
}
Tags:
Leave A Reply

Mustache is a very simple and powerful templating language

I am late to the game learning about the Mustache templating language. It is very mature, and has support for all of the languages I care about: Perl, PHP, and Javascript. I am mainly focused on using it in Javascript as it is a great way to format raw data you get via JSON into something more human consumable like HTML.

It's incredibly easy to implement and get started with. A single include loads the entire zero-dependency library. As of v4.2.0 the library is tiny, clocking in at only 25k. Once loaded Mustache.render(template_str, data_obj) gets you a formatted string. A big selling point is the ease of installation and use. You can be up and running with Mustache.js in less than 5 minutes.

<script src="/js/mustache.min.js"></script>
var data = { name: "Jason", animal: "Kitten" };
var str  = Mustache.render("<p>Hello {{name}}, I hear you like {{animal}}s</p>", data);

I liked it so much I wrote up a Mustache sandbox to allow me to play around with the templating system live. The template syntax is a little archaic, but it is workable.

Note: They even have Arduino support, which I need to test.

Tags:
Leave A Reply

PHP: Simplify sending a JSON object to browsers

I can never remember the correct MIME type for JSON so I wrote this wrapper function to simplify sending JSON to a browser.

// Convert a PHP data structure to JSON and send it to the browser
function json_output($obj) {
    $output = json_encode($obj, JSON_INVALID_UTF8_SUBSTITUTE);

    // http://tools.ietf.org/html/rfc4627
    header('Content-type: application/json');
    print $output;
    exit;
}
Tags:
Leave A Reply

Perl: Search and replace a string across your entire code base

I need to rename a function anywhere it is found in my code base. This requires going through every file and directory recursively, and checking each file. Using the Linux find command we can find all the files and then hand the search and replace off to Perl. Easy peasy.

find codebase/ -type f -exec perl -pi -E 's/foo/bar/g' {} +

or using fd instead:

fd . codebase/ --type f --exec-batch -pi -E 's/foo/bar/g' {}
Tags:
Leave A Reply

Linux: Testing for x86_64-v3

Modern Linux distributions are starting to require x86_64-v3 capable CPUs to run. If you do not have a CPU modern enough you may not be able to install certain versions of Linux. To test if your hardware is capable you can run the following command:

/usr/lib64/ld-linux-x86-64.so.2 --help

Basically any CPU made after 2015 will be fine.

Tags:
Leave A Reply

PHP: Only start a session when it's needed

I use sessions on my sites for user authentication. Calling session_start() initiates a session and allows me to check if the user is logged in or not. However, calling session_start() creates a new session for every hit on your site: bots, unauthenticated users, etc. This can lead to an excess of session files on your filesystem.

A better way is to explicitly call start_session() when your user logs in. On your other pages you can check if the user has the appropriate session cookie and start a session only when it's needed.

function start_session_if_exists() {
    if (isset($_COOKIE[session_name()]) && session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
}

This will avoid creating a session for every hit on your site.

Tags:
Leave A Reply

CSS: Selecting text made easy

You can apply the user-select CSS property to an element to control how it handles selecting text for copy and paste. This allows you to limit selecting text, or make it automatic. If you use the all property, anytime a user clicks on that element the text is automatically selected. This can be useful for keys or codes where the user is expected to copy and paste the text.

.click_select { user-select: all; }

Example:

Click me!

Tags:
Leave A Reply

Linux: Find all the text files in a directory

I need to find all the text files in a given directory for potential clean up. There is not a super easy way to find only text files, but I came up with a hacky solution:

# Using `fd` (new hotness)
fd . /tmp/ --exec file {} + | grep -P ":.*text" | cut -d: -f1

# Using old school `find` (old and busted)
find /tmp/ -exec file {} + | grep -P ":.*text" | cut -d: -f1

These rely on the file command to determine what the filetype is.

Tags:
Leave A Reply

Javascript: Copy string to clipboard

I needed a modern way to copy a string to the clipboard in JavaScript. Claude.ai helped me come up with this:

// With async/await
async function copyToClipboard(text) {
    try {
        await navigator.clipboard.writeText(text);
        console.log('Copied to clipboard');
    } catch (err) {
        console.error('Failed to copy: ', err);
    }
}

Then you simply call it with a string

copyToClipboard("Hello world");
Tags:
Leave A Reply

Rocky 10 package versions

RedHat Enterprise Linux/Rocky 10 has these versions of packages:

Package Version
Apache 2.4.63
GCC 14.2.1
Git 2.47.1
Kernel 6.12
MariaDB 10.11.11
OpenSSH 9.9p1
Perl 5.40.2
PHP 8.3.19
Vim 9.1.83
Tags:
Leave A Reply

Javascript: Returning data from an AJAX call

Javascript is by it's nature asynchronous, which makes returning data from an AJAX call complicated. Modern Javascript uses the concept of a "promise" to allow you to run code after an asynchronous call competes. This is similar to using a callback function, but it reads cleaner. JQuery implements this type of call with the then() function. A simple example is as follows:

function getData() {
    return $.ajax({
        url: '/api/data'
    });
}

// Usage
getData().then(function(data) {
    console.log(data);
});
Tags:
Leave A Reply

PHP: Generate secure password hashes from the CLI

The password_hash() function in PHP is excellent for storing passwords securely. In order to generate password to store in a database or config file I like to generate passwords from the CLI. This has the risk of storing the password in your bash history. This command prompts you for the password on the fly and protects your history.

php -r 'echo "Password: "; $pwd = trim(fgets(STDIN)); echo password_hash($pwd, PASSWORD_DEFAULT) . "\n";'
Tags:
Leave A Reply

Vim: Insert a line of characters

I need an 80 character divider of text in Vim. I can never remember the sequence so I'm writing it down:

80i/<ESC>

Will generate:

////////////////////////////////////////////////////////////////////////////////
Tags:
Leave A Reply

Comparing 32bit and 64bit performance on low end micro-controllers

Testing 32bit vs 64bit PRNGs on a 32bit ESP32-C3 I'm seeing:

PRNG Iterations per second Output Bits Bytes per second
pcg32 487802 32 1951266.7 b/s
xoroshiro64** 516023 32 2050966.7 b/s
xoshiro256+ 487808 64 3878726.7 b/s
xoshiro512++ 441735 64 3514373.3 b/s
splitmix64 462290 64 3677033.3 b/s
pcg64 416297 64 3313060.0 b/s

Very little difference on PRNGs that use 64bit operations vs 32bit operations. Even on limited hardware like this it makes sense to use a 64bit PRNG because you get more bytes per cycle.

Tags:
Leave A Reply

Vim: Convert your syntax highlighted text into HTML

Vim is my code editor of choice as it has great features, excellent syntax highlighting, and a robust plug-in infrastructure. I'm very used to look and feel of Vim. If you want to share some of your code online, converting things to HTML can be problematic. Luckily Vim has a built in code to HTML converter:

:TOhtml

Simply run the :TOhtml command in an open text file and your buffer will be redrawn in HTML which you can then save. Here is a quick sample of my pcg32.pl script converted to HTML.

Tags:
Leave A Reply