PHP: Convert IPv4 to IPv6

PHP: Convert IPv4 to IPv6

The following PHP function will help you easily convert IPv4(IP address version 4) to IPv6(IP address version 6).

The function will return false if the provided IP address is invalid else it will return the equivalent IPv6

function convert_ipv4_to_ipv6($ip)
{
    if (!filter_var($ip, FILTER_VALIDATE_IP)) {
        return false;
    }

    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        return $ip;
    }

    $bytes = array_map('dechex', explode('.', $ip));

    return vsprintf('0:0:0:0:0:ffff:%02s%02s:%02s%02s', $bytes);
}

PHP: Convert IPv4 to IPv6

Darken or lighten colors dynamically using PHP

Below is a snippet of the code and usage guide.

PHP Function

function colourBrightness($hex, $percent)
{
    // Work out if hash given
    $hash = '';
    if (stristr($hex, '#')) {
        $hex = str_replace('#', '', $hex);
        $hash = '#';
    }
    /// HEX TO RGB
    $rgb = [hexdec(substr($hex, 0, 2)), hexdec(substr($hex, 2, 2)), hexdec(substr($hex, 4, 2))];
    //// CALCULATE
    for ($i = 0; $i < 3; $i++) {
        // See if brighter or darker
        if ($percent > 0) {
            // Lighter
            $rgb[$i] = round($rgb[$i] * $percent) + round(255 * (1 - $percent));
        } else {
            // Darker
            $positivePercent = $percent - ($percent * 2);
            $rgb[$i] = round($rgb[$i] * (1 - $positivePercent)); // round($rgb[$i] * (1-$positivePercent));
        }
        // In case rounding up causes us to go to 256
        if ($rgb[$i] > 255) {
            $rgb[$i] = 255;
        }
    }
    //// RBG to Hex
    $hex = '';
    for ($i = 0; $i < 3; $i++) {
        // Convert the decimal digit to hex
        $hexDigit = dechex($rgb[$i]);
        // Add a leading zero if necessary
        if (strlen($hexDigit) == 1) {
            $hexDigit = "0" . $hexDigit;
        }
        // Append to the hex string
        $hex .= $hexDigit;
    }
    return $hash . $hex;
}

Function Usage

You do not have to give the color with the ‘#’ in front but if you do it will still return the new hex color with the ‘#’ auto-magically.

Lighten a color

$colour = '#ae64fe';
$brightness = 0.5; // 50% brighter
$newColour = colourBrightness($colour, $brightness);

Darken a color

$colour = '#ae64fe';
$brightness = -0.5; // 50% darker
$newColour = colourBrightness($colour, $brightness);
How to use MySQL to search in PHP serialized fields

How to use MySQL to search in PHP serialized fields

Well, first rule – you should not do this. But if there is good reason, consider using such query for searching in index-based arrays:

SELECT * FROM table WHERE your_field_here REGEXP '.*;s:[0-9]+:"your_value_here".*'

In case you have assoc array serialized you can use:

SELECT * FROM table WHERE your_field_here REGEXP '.*"array_key_here";s:[0-9]+:"your_value_here".*'

Of course it won’t be very fast but in small tables should be enough

Source:
http://www.blastar.biz/2013/11/28/how-to-use-mysql-to-search-in-php-serialized-fields/

How to use MySQL to search in PHP serialized fields

MySQL: Select records from today, this week and this month

Assuming your date column is an actual MySQL date column:

SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY score DESC;        
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY score DESC;

Source: http://stackoverflow.com/a/5293226/1794834

Verify Item Purchases with the Envato API

This article focuses on how to simply and efficiently converse with Envato’s API in order to verify the authors’ customers’ purchase codes in the author’s own applications. I talk through all the steps to set up this function, covering how to create the unique API key required, using the PHP cURL function and interpreting the output.

<?php
    function verify_envato_purchase_code($code_to_verify) {
    // Your Username
    $username = 'USERNAME';
      
    // Set API Key  
    $api_key = 'API KEY';
      
    // Open cURL channel
    $ch = curl_init();
       
    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, "http://marketplace.envato.com/api/edge/". $username ."/". $api_key ."/verify-purchase:". $code_to_verify .".json");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       
    // Decode returned JSON
    $output = json_decode(curl_exec($ch), true);
       
    // Close Channel
    curl_close($ch);
       
    // Return output
    return $output;
}
  
$purchase_key = 'PURCHASE KEY TO CHECK';
  
$purchase_data = verify_envato_purchase_code( $purchase_key );
  
if( isset($purchase_data['verify-purchase']['buyer']) ) {
      
    echo '<strong>Valid License Key!</strong><br>Details;<ul>';
    echo '<li>Item ID: ' . $purchase_data['verify-purchase']['item_id'] . '</li>';
    echo '<li>Item Name: ' . $purchase_data['verify-purchase']['item_name'] . '</li>';
    echo '<li>Buyer: ' . $purchase_data['verify-purchase']['buyer'] . '</li>';
    echo '<li>License: ' . $purchase_data['verify-purchase']['licence'] . '</li>';
    echo '<li>Created At: ' . $purchase_data['verify-purchase']['created_at'] . '</li>';
    echo '</ul>'; 
} else {
   echo 'Invalid license key.';
}
?>

Sources:
http://www.wpeka.com/verify-item-purchases-envato.html
http://hbt.io/verify-item-purchases-envato/

Verify hex color string

Verify hex color string
Verify hex color string

This PHP script checks if a string $color is a hex color or not. The second IF statement will add the pound symbol at the beginning if it is missing from the hex color value.

//Check for a hex color string '#c1c2b4'
if(preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid
{
	//Verified hex color
} 

//Check for a hex color string without hash 'c1c2b4'
elseif(preg_match('/^[a-f0-9]{6}$/i', $color)) //hex color is valid
{
	$fix_color = '#' . $color;
}

Source:
http://code.hyperspatial.com/250/verify-hex-color-string/

PHP: CHMOD a directory recursively

The script below loops over the specified directory and chmods its files, directories and subdirectories recursively.

<?php

  function chmodDirectory( $path = '.', $level = 0 ){  
  $ignore = array( 'cgi-bin', '.', '..' ); 
  $dh = @opendir( $path ); 
  while( false !== ( $file = readdir( $dh ) ) ){ // Loop through the directory 
  if( !in_array( $file, $ignore ) ){

        if( is_dir( "$path/$file" ) ){

          chmod("$path/$file",0755);

          chmodDirectory( "$path/$file", ($level+1));

        } else {

          chmod("path/$file",0644); // desired permission settings

        }//elseif 
	}//if in array 
	}//while 
	
	closedir( $dh ); 
	}//function
	chmodDirectory("the_directory/",0);

?> 

PHP: How to create unique short string IDs with PHP & MySQL

PHP: How to create unique short string IDs with PHP & MySQL

PHP: How to create unique short string IDs with PHP & MySQL

IDs are often numbers. Unfortunately there are only 10 digits to work with, so if you have a lot of records, IDs tend to get very lengthy. For computers that’s OK. But human beings like their IDs as short as possible. So how can we make IDs shorter? Well, we could borrow characters from the alphabet as have them pose as additional numbers…. Alphabet to the rescue!

I created this function a long time ago. Time to be nice and share.

More is Less – the ‘math’

The alphabet has 26 characters. That’s a lot more than 10 digits. If we also distinguish upper- and lowercase, and add digits to the bunch or the heck of it, we already have (26 x 2 + 10) 62 options we can use per position in the ID.

Now of course we can also add additional funny characters to ‘the bunch’ like – / * & # but those may cause problems in URLs and that’s our target audience for now.

OK so because there are roughly 6x more characters we will use per position, IDs will get muchshorter. We can just fit a lot more data in each position.

This is basically what url shortening services do like tinyurl, is.gd, or bit.ly. But similar IDs can also be found at youtube: http://www.youtube.com/watch?v=yzNjIBEdyww
(more…)

PHP: Convert string to variable?!

PHP: Convert string to variable?!

PHP: Convert string to variable?!

Problem:

$button0 = "candy";
$button1 = "pop";
$button2 = "nuts";
$button3 = "sugar";

$buttons = 4;
$counter = 0;
while ($counter < $buttons) {
$printbutton = "$"."button".$counter;
echo($printbutton."<br />"); // echos $button0 but not the value of $button0
$counter = $counter+1;
}

What happens is that $printbutton always prints $buttonx (where x = $count) but I want it to print candy or nuts or whatever $buttonx’s value is.

Solution:
(more…)

Check if website is available or down

Performs a cURL-Request to check, if a website exists / is online

//Cron job comand line: /usr/local/bin/php /home/USERNAME/site-monitor/monitor.php > /dev/null
ini_set('error_log','/home/USERNAME/site-monitor/downtime.log');

//returns true, if domain is availible, false if not
function isDomainAvailible($domain) {
	//check, if a valid url is provided
	if(!filter_var($domain, FILTER_VALIDATE_URL)) {
		return false;
	}
	//initialize curl
	$curlInit = curl_init($domain);
	curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
	curl_setopt($curlInit,CURLOPT_HEADER,true);
	curl_setopt($curlInit,CURLOPT_NOBODY,true);
	curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);
	//get answer
	$response = curl_exec($curlInit);
	curl_close($curlInit);
	if ($response) return true;
	return false;
}

if (!isDomainAvailible('http://www.example.com/updown.html')) {
	echo "Woops, nothing found there.";
	$message = 'Woops, Your site was down on '.date("Y-m-d H:i:s");
	$headers = 'From: admin@example.com';
	mail("admin@example.com", "Website is down", $message, $headers);
	error_log($message, 0);
}

Source:
http://css-tricks.com/snippets/php/check-if-website-is-available/