Tag Archives: Snippet

PHP: Validating flexible/incomplete date time strings

Need to validate some datetime strings, that may or may not be incomplete. Might be for example just a year and a month, while the rest is unknown.

Noting it here in case I need it again. And in case someone else needs it, knows a more efficient/cleaner way, or sees a flaw…

function flexi_time($value): bool
{
    $valid = preg_match('/^(?<year>\d{4})(?:-(?<month>\d{2})(?:-(?<day>\d{2})(?:[ T](?<hour>\d{2}):(?<min>\d{2})(?::(?<sec>\d{2}))?)?)?)?$/', $value, $matches);
   
    if( ! $valid)
        return false;

    extract($matches);

    // Check month
    if($month ?? null AND ! between($month, 1, 12))
        return false;

    // Check date
    if($day ?? null AND ! checkdate($month, $day, $year))
        return false;

    // Check hour
    if($hour ?? null AND ! between($hour, 0, 23))
        return false;

    // Check minute
    if($min ?? null AND ! between($min, 0, 59))
        return false;

    // Check second
    if($sec ?? null AND ! between($sec, 0, 59))
        return false;

    return true;
}

function between($value, $min, $max): bool
{
    return $value >= $min && $value <= $max;
}

Test

$dates = [
    'foo', // Invalid
    '17', // Invalid
    '2017',
    '2017-01',
    '2017-13', // Invalid month
    '2017-01-17',
    '2017-02-31', // Invalid date
    '2017-01-17 20', // Invalid hour without minutes
    '2017-01-17 20:00',
    '2017-01-17T20:00', // Both space and T allowed as separator
    '2017-01-17 20:00:10',
    '2017-01-17 25:00:10', // Invalid hour
    '2017-01-17 20:70:70', // Invalid minute
    '2017-01-17 20:10:70', // Invalid second
];
print_r(array_filter($dates, 'flexi_time'));
Array
(
    [2] => 2017
    [3] => 2017-01
    [5] => 2017-01-17
    [8] => 2017-01-17 20:00
    [9] => 2017-01-17T20:00
    [10] => 2017-01-17 20:00:10
)

PHP: Convert RGB to hex and back

Just another note to self, in case I need it again:

/**
 * #rrggbb or #rgb to [r, g, b]
 */

function hex2rgb(string $hex): array
{
    $hex = ltrim($hex, '#');

    if(strlen($hex) == 3)
        return [
            hexdec($hex[0].$hex[0]),
            hexdec($hex[1].$hex[1]),
            hexdec($hex[2].$hex[2]),
        ];
    else
        return [
            hexdec($hex[0].$hex[1]),
            hexdec($hex[2].$hex[3]),
            hexdec($hex[4].$hex[5]),
        ];
}


/**
 * [r, g, b] to #rrggbb
 */

function rgb2hex(array $rgb): string
{
    return '#'
        . sprintf('%02x', $rgb[0])
        . sprintf('%02x', $rgb[1])
        . sprintf('%02x', $rgb[2]);
}

MySQL tables for continent names, country names and their ISO-3166 codes

Map of the world Here is a MySQL table containing continent names, country names and their ISO-3166 codes.

Needed one a while ago, but the ones I found were either kind of lacking or kind of old. So I made one myself by converting a datafile on Wikipedia into the format I wanted. Used some regular expressions and manual corrections. Later I also went through newsletters with Updates on ISO 3166. Hopefully I got it all right, and hopefully it can save you and others some time as well.

I have also subscribed to their updates and try to follow up when they change anything.

If you find any mistakes or updates I’ve missed, please let me know 🙂

Continue reading MySQL tables for continent names, country names and their ISO-3166 codes

PHP: What’s a valid JavaScript identifier (or function name)?

After another reply to a question I’ve had on StackOverflow for a while, I decided that I perhaps should add another level of security to my method of providing JSONP from PHP. The way I did it before, I didn’t do any checking on the provided callback. This means that someone could technically put whatever they wanted in there, including malicious code. So, therefore it might be a good idea to check if the callback, which should be a function name, actually is a valid function name. But,

Continue reading PHP: What’s a valid JavaScript identifier (or function name)?

SQL for listing all WordPress tags

When writing a post I sometimes find it difficult to choose what I should tag it with. I try reuse tags I already have to prevent a total mess, and sometimes I just don’t really remember what tags I have used so far. When writing a post in WordPress you can get a list of the most used ones, but once in a while I write a post on subject I haven’t written a lot about. So, instead of going to the Post Tags page and look through all the pages of tags, I decided to just connect to my blog database and run a query.

Continue reading SQL for listing all WordPress tags

PHP Tutorial: PayPal Instant Payment Notification (IPN)

Got a letterIn a previous post I tried to give an introduction on how to get started with PayPal Payment Data Transfers (PDT). PDT is very handy in several cases, but you can’t always rely on it since it requires the user to return to your page after doing the payment. That will often happen, but it’s not guaranteed to happen. If you for example want to mark an order in your system as paid or something like that, you most likely want to use PayPal Instant Payment Notifications (IPN) in addition to PDT.

Instant Payment Notification (IPN) is a message service that notifies you of events related to PayPal transactions. You can use it to automate back-office and administrative functions, such as fulfilling orders, tracking customers, and providing status and other information related to a transaction. — PayPal

Once again the documentation, tutorials and code samples I found on this was a bit all over the place. Sort of messy and outdated. So, once again I decided to do my own thing and just follow the steps required and implement them myself. And since the tutorial on PDT turned out to be a bit of a success, I decided to share this too. Hopefully it can make the lives of fellow developers easier 🙂

Continue reading PHP Tutorial: PayPal Instant Payment Notification (IPN)