PHP notes

3 May 2024

This is some PHP specific scripts that I have found useful. All my Laravel relevant notes can be seen here: Laravel notes.

Colors

Converting hex color codes into RGB in PHP

You can convert hex color codes easily into RGB with the sscanf-function like this:
$hex = #ff9900;
list($r, $g, $b) = sscanf($hex, #%02x%02x%02x);
echo $hex -> $r $g $b;
The script above will give the following output:
#ff9900 -> 255 153 0

Encryption

Two-way encryption

StackOverflow - Two-way encryption in PHP.

IP address

Find IP location

I found this snippet on StackOverflow, which gives you the location based on an IP address. The script uses the service ipinfo.io.
$ curl ipinfo.io/8.8.8.8
{
    ip: 8.8.8.8,
    hostname: google-public-dns-a.google.com,
    loc: 37.385999999999996,-122.0838,
    org: AS15169 Google Inc.,
    city: Mountain View,
    region: CA,
    country: US,
    phone: 650
}
Here's the PHP example:
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents(http://ipinfo.io/{$ip}/json));
echo $details->city; // Mountain View

Regular expressions

Even though this isn't really PHP-specific I regularly use expressions in PHP.

Validating hex color codes with regular expression

I have used the following regular expression for validating hex color codes:
/#([a-fA-F0-9]{3}){1,2}\b/
The regular expression validates both hex color codes with 3 and 6 characters after the #.

Running Python from PHP

ob_start();
passthru('python3 kekscript.py');
$output = ob_get_clean();
$output = str_replace(\r\n, , $output);
This runs the script “kekscript.py” and saves the output to the variable output.

Remember Python can be run inline, so you can write
python -c print('kek'); print('lol')
This means that your PHP script can write your Python script directly. SImply change the input to the passthru-function to an inline script instead.

You might also enjoy

Getting title tag and meta tags from a website using PHP

Getting title tag and meta tags from a website using PHP

Published 2024-05-14

PHP

Web development

Learn how to easily webscrape title and meta tags from a website using simple PHP commands.

Read the post →
The Seven Restful Controller Actions in Laravel

The Seven Restful Controller Actions in Laravel

Published 2024-05-05 — Updated 2024-05-16

Laravel

PHP

Web development

The seven RESTful actions and how you could implement them in Laravel

Read the post →
Simplifying Your Code with Advanced Operators in PHP

Simplifying Your Code with Advanced Operators in PHP

Published 2024-05-05

PHP

Web development

Ready to write PHP code like a pro? Learn how to use advanced operators to make your code more concise and readable, and take your skills to the next level.

Read the post →