Faster Alternative to PHP’s Array Unique Function

Overview

Using PHP’s function array_unique() allows you to take an array of values and remove the duplicates leaving you with an array with unique values. This function works best most of the time, however if you find yourself trying to use array_unique on massive arrays, it may slow down quite a bit.

Instead of using array_unique to create a distinct array, there is another nifty array function that will speed things up called `array_flip()`. With this magic function, it swaps each of the array’s key with its value and since keys must be unique, then you will be left with the same result as if you had used array_unique()

Faster Alternative to PHP’s Array Unique Function

/* create our array of 4 elements with duplicate values */
$array = array('green','blue','orange','blue');

/* flip the array now we will have an array with unique keys
	array('green'=>0,'blue'=>1,'orange'=>2); */
$array = array_flip($array);

/* and then flip the array back to put the keys and values where they are meant to be leave us with array(0=>'green',1=>'blue',2=>'orange'); */
$array = array_flip($array);

Since we have now removed a number of elements the array keys may not be in sequence. For example we may be left with array(0=>’A’,2=>’B’,5=>’C’);. In some situations, this is not an issue, however if you rely on the array keys being in numerical sequence, you can one of two things to fix the array keys.

Fix array keys using array_merge()

Add the following after the array flip to sort out the array keys and put them back into sequence, i.e. 0, 1, 2, 3, …

$array = array('green','blue','orange','blue');
$array = array_flip($array);
$array = array_flip($array);

/* Use array_merge() to fix the keys */
$array = array_merge($array);

Second method using array_keys()

Note, this method of fixing the array keys is marginally faster than using the array_merge() method
You could also combine the last step to use array_keys – which at the time would be the flipped values. Then once you flip the values, the keys will be created in order.

$array = array('green','blue','orange','blue');
$array = array_flip($array);
/* Same as first example, except now we first extract array keys */
$array = array_keys($array);

Note: Thanks to yehosef for helping fix and improve the above code.

Conclusion

Easy as that! and can have a significant increase in performance on massive arrays over using array_unique.

Validate Email Addresses – Javascript and PHP Example

Overview – Validate Email Addresses – Javascript and PHP Example

In todays article I will show provide you with source code validate email addresses using either Javascript or PHP. It uses a regular expression to test if the string passed to is a valid email address and returns true or false in either case. It works well for me and will hopefully do the trick for you.

Javascript Example using the function: test()

<script type="text/javascript">

/* validate an email address */
function validateEmail( em ) {
	var pattern = /^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})(\.([a-z]{2,4}))*$/i;
	return (pattern.test(em)) ? true : false;
}

</script>

In order to use the javascript validate email address function, simply include the above function in your javascript or separate include file and then call it using

<script type="text/javascript">
var bValidEmail = validateEmail('somemail@example.com');
</script>

PHP Example using the function: preg_match()

<?php

/* validate an email address */
function validateEmail( $em ) {
	$pattern = '/^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})(\.([a-z]{2,4}))*$/i';
	return preg_match($pattern,$em) ? true : false;
}

?>

In order to use the php validate email address function, simply include the above function in your php or separate include file and then call it using

<?php
$bValidEmail = validateEmail('somemail@example.com');
?>

MySQL INSERT IGNORE – A MySQL Syntax Tip

Overview – MySQL INSERT IGNORE

In MySQL, when you perform a mysql insert query, it is very common to come across errors with one of the insert queries. Once an issue is encountered with a mysql insert, the rest of the mysql inserts will not be executed since the MySQL query won’t continue. This can be annoying since you will have to figure out which rows were inserted and which ones weren’t so you can manually insert the remaining rows.

Fortunately, you can use mysql insert ignore syntax to avoid this frustration by using the keyword ‘ignore’.

MySQL INSERT IGNORE

Consider the following mysql insert statement that would insert two records:

INSERT INTO `table` ('name','surname','email') VALUES ('Mark','Ringo','mark@example.com'),('Sarah','Ainsley','sarah@example.com');

If the first insert (mark ringo) had to fail for some reason, then Sarah would not be inserted UNLESS you add the word ‘ignore’ after mysql insert statement, making the above statement:

INSERT IGNORE INTO `table` .......

Now if the first entry fails, then Sarah will still get inserted. Pretty nifty eh’ and can save countless hours of frustration while trying to import partial records and missing rows from an incomplete mysql insert.

Use With Caution

Please use the mysql insert ignore with caution. Errors and warnings that creep up are there for a reason. MySQL INSERT IGNORE can save a lot of frustration and simplify inserting records however it can end up masking some issues that exist.

Get Total Directory Size In PHP

Overview – Get Total Directory Size In PHP

In my previous article called Get and Display Hard Disk Space Usage Using PHP I demonstrated how you can fetch and display the size of a hard disk as well as the free space and used space and display it to the user. While this works well it still doesn’t show how to get the size of a specific folder using PHP.

Get total directory size in PHP

Below I have created an example showing an alternate method to get total directory size in PHP. It makes use of the shell command du -sh (disk usage) and then uses a regular expression to fetch just the number of bytes out of the output generated by the du command.

<?php

// we need the full path to the folder we want to find the size of
//	below we result in a folder path of /var/www/mywebsite/html/files
$folder = $_SERVER['DOCUMENT_ROOT'].'/files';

// now prevent malicious attacks since we are executing a shell command
$folder = escapeshellcmd($folder);

// make sure this is a folder
if( ! is_dir($folder) )
{
	echo "$folder is not a folder.<br />";
}
// if we could find the pattern of our command du -s
else
{
	// we execute du (disk usage) to find out the folder size
	//	notice we use the execution operator (the key to the left of 1 on your keyboard)
	//	this is the same as the php function shell_exec()
	//	you can add the -h flaf to the below command to format the file size into MB, GB, etc.
	//		i.e. `du -sh $folder`;
	$output = `du -s $folder`;

	if( preg_match('/([0-9]+)(t.*)/',$output,$match) )
	{
		$size = $match[1];

		// $size will now hold the size of the folder
		echo "Folder $folder is $size bytes<br />";
	}
	else
	{
		// error
		// either we can't execute du -s command (such as windows users) or the folder doesn't exist
		echo "Error fetching folder size, are you on Linux? and can you execute commands?<br />";
	}
}

?>

MySQL DELAYED INSERT and MySQL DELAYED UPDATE

Overview

Performing MySQL queries on your websites or server can cause long delays in a page loading or script executing while the MySQL INSERT or MySQL UPDATE finishes executing. This causes long delays for the user or possibly delays the rest of a script from running until the MySQL query completes (or errors out). Generally the delay on mysql inserts or update is minimal however on large complex queries with lots of join across multiple tables and millions of rows of data (or badly indexed tables), there will be a significant pause while the query completes.

Solution to Long Queries

If there is no need for the user to see the result of the query, such as queries that are involved with logging statistics or building hidden reports, then it would be highly recommended to use mysql delayed insert or mysql delayed update syntax. Using MySQL DELAYED INSERT and MySQL DELAYED UPDATE to send the queries into the queue and run in the background allowing the page or script to continue executing. It is simple to use and can be implemented by adding the `delayed` keyword after INSERT or UPDATE command and the sql query will be queued by the MySQL server to be run in the background and the page while continue loading while the sql query is executed in the background as the example below shows:

MySQL DELAYED INSERT

MySQL Insert statements can be run in the background by using the following syntax:

INSERT DELAYED `some massive time consuming query`;

MySQL DELAYED UPDATE

MySQL Update statements can be run in the background by using the following syntax:

UPDATE DELAYED `some massive time consuming query`;

Conclusion

Now the page will continue to load while the MySQL server continues to execute the query which can drastically speed up page loading speeds or script execution times. Bear in mind that if the user needs to see the result, then you won’t be able to use mysql delayed inserts.

Display Disk Free Space Percentage In PHP

Overview – Display Disk Free Space Percentage In PHP

Have you ever needed a nice little progress bar on your website to display disk space free percentage? This can be handy if you would like to give your clients an indication on how much disk space free they have on their own virtually hosted website, or perhaps you need a simple web interface to keep an eye out on your server health. In any case, this progress bar will accurately show you how much disk space free and disk space usage on your server.

Checkout out a follow up article called showing an alternate way to determine the total size of a folder using php.

End Result – What This Article Will Achieve

Get Total Directory Size In PHP

Get Total Directory Size In PHP

Once you have copied and implemented the code shows in the 3 steps, you should have a tidy progress bar that will show you your disk usage on your server. Below is an image of what it should look like if you have followed the steps correctly.

 

Step 1 – PHP Code

Place this code into a PHP script inside the web directory of your choice. All three steps can be included into the same PHP file or seperated if requried.

<?php

/* get disk space free (in bytes) */
$df = disk_free_space("/var/www");
/* and get disk space total (in bytes)  */
$dt = disk_total_space("/var/www");
/* now we calculate the disk space used (in bytes) */
$du = $dt - $df;
/* percentage of disk used - this will be used to also set the width % of the progress bar */
$dp = sprintf('%.2f',($du / $dt) * 100);

/* and we formate the size from bytes to MB, GB, etc. */
$df = formatSize($df);
$du = formatSize($du);
$dt = formatSize($dt);

function formatSize( $bytes )
{
	$types = array( 'B', 'KB', 'MB', 'GB', 'TB' );
	for( $i = 0; $bytes >= 1024 && $i < ( count( $types ) -1 ); $bytes /= 1024, $i++ );
		return( round( $bytes, 2 ) . " " . $types[$i] );
}

?>

Step 2 – CSS Style Sheet

Place this code into a CSS style sheet inside the web directory of your choice. The CSS code can be included into the same PHP file created in step 1 or seperated into its own CSS file if required, however since it is executing php code to create the width of the element, it should not be placeed inside a separate css file.

<style type='text/css'>

.progress {
	border: 2px solid #5E96E4;
	height: 32px;
	width: 540px;
	margin: 30px auto;
}
.progress .prgbar {
	background: #A7C6FF;
	width: <?php echo $dp; ?>%;
	position: relative;
	height: 32px;
	z-index: 999;
}
.progress .prgtext {
	color: #286692;
	text-align: center;
	font-size: 13px;
	padding: 9px 0 0;
	width: 540px;
	position: absolute;
	z-index: 1000;
}
.progress .prginfo {
	margin: 3px 0;
}

</style>

Step 3 – HTML Code Including the Progress Bar

Place this code into an HTML file inside the web directory of your choice. The HTML code can be included into the same PHP file created in step 1 or seperated into its own file if required.

<div class='progress'>
	<div class='prgtext'><?php echo $dp; ?>% Disk Used</div>
	<div class='prgbar'></div>
	<div class='prginfo'>
		<span style='float: left;'><?php echo "$du of $dt used"; ?></span>
		<span style='float: right;'><?php echo "$df of $dt free"; ?></span>
		<span style='clear: both;'></span>
	</div>
</div>

Get Last Day Of Month MySQL And PHP

In order to get last day of month in mysql or php, you can use built in functions. As you will soon see below it is a rather straight foward task. I will show you two examples on how to get the last day of the month in mysql as well as php. In php you can use the date() function and in mysql we will make use of the last_day() method.

Get last day of the month PHP

PHP has a date function which returns a string representation of the date formatted according to the expression passed to it. So the simple way is to use the ‘t’ identifier in the date function which will return the last day of the month.

echo date('Y-m-t',strtotime('2014-01-12')); // echo's 2014-01-31
echo date('t M Y'); // echo's 31 Jul 2014

Get last day of month MySQL

MySQL has a function called last day that will return the last day of the date supplied to it. It can be the date of the current month or any other month.

SELECT last_day(CURDATE() - INTERVAL 1 MONTH) AS last_month;
SELECT last_day(CURDATE()) AS current_month; 
SELECT last_day(DATE('2014-03-12')) AS march_month

Conclusion

As you can see, getting the last day of the month is a simple task. If you get stuck, let me know in the comments.