Skip to content

Instantly share code, notes, and snippets.

@lt
lt / uuid4.php
Last active May 15, 2020 09:00
PHP Fast UUIDv4
function uuid4(): string
{
return bin2hex(
// 18 bytes encodes to 36 bytes. 32 for UUID + 4 for hyphens.
// Bitwise AND to mask where static bits will be set
// Mask and set UUID specific bits
// In 00112233-4455-m677-n899-aabbccddeeff, m (4 bits) = version (4), n (2 bits) = variant (2)
// 00 11 22 33 -4 45 5- m6 77 -n 89 9- aa bb cc dd ee ff
(random_bytes(18) & "\xff\xff\xff\xff\x0f\xff\xf0\x0f\xff\x03\xff\xf0\xff\xff\xff\xff\xff\xff") |
@lt
lt / sniff.php
Created December 9, 2016 16:41
Minimal PHP packet sniffer
<?php declare(strict_types=1);
$socket = socket_create(AF_INET, SOCK_RAW, SOL_TCP);
if (!$socket) {
$errorCode = socket_last_error();
throw new \RuntimeException(socket_strerror($errorCode), $errorCode);
}
const IP_HDR = 'Cversion_ihl/Ctos/ntot_len/nid/nfrag_off/Cttl/Cprotocol/ncheck/Nsaddr/Ndaddr/';
@lt
lt / json_decode_class.php
Last active September 19, 2019 15:06
Decode JSON into a specific class
<?php
function deep_copy_and_validate_object($source, $destination)
{
$reflectionClass = new \ReflectionClass($destination);
foreach ($reflectionClass->getProperties() as $reflectionProperty) {
$propertyName = $reflectionProperty->getName();
if (property_exists($source, $propertyName)) {
$propertyValue = $source->$propertyName;

Keybase proof

I hereby claim:

  • I am lt on github.
  • I am lt (https://keybase.io/lt) on keybase.
  • I have a public key whose fingerprint is 6A4D B222 AA19 7E6E 63D0 4DF4 493D B208 C886 9F3B

To claim this, I am signing this object:

@lt
lt / DependencyResolver.php
Last active September 19, 2019 15:07
Class to perform a Topological Sort based on the nodes of a Directed Acyclic Graph representing dependencies.
<?php
/**
* Directed acyclic graph based dependency resolver.
*
* Class DependencyResolver
*/
class DependencyResolver {
/**
* Internal map of outgoing edges for each node.
@lt
lt / gist:4162568
Created November 28, 2012 17:07 — forked from nikic/gist:4162505
Regex to validate (IPv4) CIDR notation (with capture)
Repeating patterns, matches 0-255 in each octet, followed by /0-32
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/(3[0-2]|[1-2]?[0-9])\b
Using subpatterns to achieve the same thing.
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?1)\.(?1)\.(?1)/(3[0-2]|[1-2]?[0-9])\b
@lt
lt / gzip_static
Created November 2, 2012 15:51
gzip new or modified files in the "static" directory.
#!/bin/sh
for file in $(find static -type f ! -name *.gz); do
if [ ! -e $file.gz ] || [ $file -nt $file.gz ]; then
gzip -9 -n -c -v $file > $file.gz
touch $file.gz -r $file
fi
done