Programming

Programming

Running PHP Script From Cron

Overview

Cron is a job based scheduler used in Unix type operating systems. It allows you to schedule tasks to be run at given intervals such as scheduling a php script to run weekly, every second day, hourly, every 3 minutes, weekends, and so on.
In this article, I will show how easy it is in running a php script from cron. It will also show you how you can run a php script via a url using wget.

Running PHP Script From Cron

I will show you 3 ways on running php script from cron which are:

  1. Running php script via command line in cron
  2. Running php script via php5-cgi in cron
  3. Running php script remotely via website url in cron

Running a php script usually requires the php script to have execute permissions set. Running PHP script from cron is usually a matter of specifying the file and as long as the script has execute permissions (i.e. chmod +x) then all should be good. Here are three ways I have found work very well.

Running PHP Script On Command Line From Cron

In order for the script to run correctly you should add the following to your php script. The informs the bash what type of script it is executing.

#!/usr/bin/php
<?php

//.. your code follows here

Next we add the entry into cron.

# you could output to a file by changing /dev/null to /some/file/to/save.log
*/10 * * * * /home/user/scripts/updatesomething.php > /dev/null

Note we didn’t need to execute the script via php (/usr/bin/php /path/to/script.php) since we added the header to the php script.

Running php script via php5-cgi in cron

To execute the php script from cron you need to have php5-cgi installed. You can install this on Debian use “apt-get install php5-cgi” or the equivalent command for your distribution of linux.

# PHP5-CGI: execute the php script every 2 minutes and send output to /dev/null
# you could output to a file by changing /dev/null to /some/file/to/save.txt
*/2* * * * php5-cgi -q /home/user/scripts/parselogs.php > /dev/null

Running php script via website url in cron

And lastly we will use wget from the cron to download a website url and thus, execute the url that the php script is located at. We do this in the cron to allow the url to be downloaded at set times. To use wget, you need to install it wget using “apt-get install wget” or the equivalent command for your distribution of linux.

# wget will visit the url but won't save the file. send it to /dev/null
# this executes the script as if you visited the link in your browser
0 * * * * wget -O /dev/null http://www.example.com/some_cron_script.php

And there we go, your php script will be run by cron on time, every time.

CSS Two Column Fluid Layout – Static Column With Elastic Fluid Column

Overview

Are you looking for some quick HTML code to create a two column table with one static column and an elastic or fluid column. It took me a while to figure out, especially since css is one of my weaker languages. So I have placed the code here to hopefully make your life easier when it comes to creating html static and liquid column layouts.
There are only two parts to achieve this and what you will find after creating the two pages (one css file and an html file) is a page that has a static right hand column of around 400px and a elastic, liquid left column (or main content) that will stretch to fit the width of the browser as you resize the window.

CSS Two Column Fluid Layout

Below is the css code used to create the two column table. The important part to take notice of is wrapper which has a 400px padding to the right. This allows the fixed right hand column to fit snug next to it without the right column dropping down below. Copy the below code into a separate css file (I named mine elastic.css) or include it inline in the same HTML file where the html code will be.
As you will see, there are some optional css parameters which are commented out. They are more for styling rather than being required. Use as needed.

body {
	font: 16px/24px Georgia, serif;
	color: #5A5A5A;
	margin: 0;
}

header, footer {
	/*padding: 30px 20px;  optional: add some padding to match the margins of the #wrapper */
	background: #555; /* optional: background colour */
	color: #F0F0F0;
}

#wrapper {
	padding-right: 400px; /* padding should be the total width of all right columns */
	/*margin: 0 20px;  optional: spacing to the side of our content and sidebars */
}

#content {
	float: left;
	width: 100%;
	min-width: 600px;
}

.sidebar {
	float: left;
	width: 400px;
	margin-right: -1000px;
	/*background: #DDD;  optional: background colour */
}

.sidebar .side-column {
	width: 200px;
	float: left;
	/*margin-left: 20px;  optional: add a small space between the columns as well as the content to the left */
}

footer {
	clear: left; /* clear the floating from the above content and sidebar this makes the footer appear correctly below */
}

HTML Code

Create your html file and paste the following code into it. If you decided to include the above css inline, then you will need to paste the above css code into the html code below.

<!DOCTYPE html>
<html>
<head>

<title></title>
<link rel="stylesheet" type="text/css" media="all" href="elastic.css" />

</head>
<body>
	<header><strong>Our Header</strong></header>
	<div id="wrapper">
		<div id="content">
			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam auctor interdum elit faucibus scelerisque. Curabitur eleifend orci eget ante egestas viverra ac nec mauris. Pellentesque et dolor et leo pellentesque sollicitudin vitae vel velit. Phasellus ullamcorper sapien in sapien fermentum viverra. Sed dignissim est nec risus elementum molestie. Morbi placerat pharetra massa vitae aliquam. Curabitur laoreet suscipit leo, sit amet lacinia dolor placerat eu. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla facilisi. Nulla lacinia, ante ac dignissim viverra, nunc orci rhoncus odio, porttitor aliquet orci massa non lorem.
		</div>
		<div class="sidebar">
			<div class="side-column">
				Sed ornare sollicitudin nisi, in tristique quam laoreet non. Nullam semper, turpis et pulvinar pulvinar, quam dui consequat mi, ac aliquet arcu nunc id massa. Vivamus aliquam odio eget neque auctor tempus sollicitudin dui malesuada. Suspendisse tincidunt eleifend pellentesque.
			</div>
			<div class="side-column">
				Phasellus arcu nulla, pulvinar et cursus id, venenatis ac augue. Sed vitae erat in ante tristique cursus at non ante. Ut auctor metus at neque consectetur pulvinar. Morbi et mauris odio. Nulla viverra vulputate leo, vitae porta augue aliquam ac. Praesent ut nisi velit.
			</div>
		</div>
	</div>
	<footer><strong>Our footer</strong></footer>

</body>
</html>

After having created your two files, a css file and a html file, you can open the html file to see the result. You will notice that there are two columns in the html file, one being static/fixed width to the right hand side and the main content being liquid and is resized as the browser window is resized. It is a great way to make the most of your web browser window space and is rather simple to use (once you have the code samples).

PHP Get Mime Type From File Extension

Overview

Whenever you need to determine the mime-type of a file you should generally look at the file extension. Below is a pretty straight forward function that will return the mime-type of a file based on its file extension. Note! this is not a guaranteed way to determine the mime-type since people can easily fake the file extension. All you need to do is pass the php mime function a filename and it will try figure out what the mime type is.

PHP Get Mime Type From File Extension

Here is the function to retrieve the mime type of a file based on the file extension. See here for a list of mime-types.

<?php

function get_mime_type($file)
{

	// our list of mime types
	$mime_types = array(
		"pdf"=>"application/pdf"
		,"exe"=>"application/octet-stream"
		,"zip"=>"application/zip"
		,"docx"=>"application/msword"
		,"doc"=>"application/msword"
		,"xls"=>"application/vnd.ms-excel"
		,"ppt"=>"application/vnd.ms-powerpoint"
		,"gif"=>"image/gif"
		,"png"=>"image/png"
		,"jpeg"=>"image/jpg"
		,"jpg"=>"image/jpg"
		,"mp3"=>"audio/mpeg"
		,"wav"=>"audio/x-wav"
		,"mpeg"=>"video/mpeg"
		,"mpg"=>"video/mpeg"
		,"mpe"=>"video/mpeg"
		,"mov"=>"video/quicktime"
		,"avi"=>"video/x-msvideo"
		,"3gp"=>"video/3gpp"
		,"css"=>"text/css"
		,"jsc"=>"application/javascript"
		,"js"=>"application/javascript"
		,"php"=>"text/html"
		,"htm"=>"text/html"
		,"html"=>"text/html"
	);

	$extension = strtolower(end(explode('.',$file)));

	return $mime_types[$extension];
}

?>

Usage Examples

Here are a couple of ways to use this function.

<?php

// simple calls to fetch mime type of a file
echo get_mime_type('example.doc'); // displays "application/msword"
echo get_mime_type('picture.jpg'); // displays "image/jpg"
echo get_mime_type('Harry_Potter.mov'); // displays "video/quicktime"

Advanced Example

This example is slightly more advanced. It will set the http header image/jpg and output the image file. It can be used for displaying an image from a php script.

<?php

$mime = get_mime_type('my_image_file.jpg'); // this will return "image/jpg"
header("Content-Type: $mime");
echo file_get_contents('my_image_file.jpg'); // output the image to the browser
?>

Regex Reverse Match And Replace All But Specified Characters

Overview

We can use regular expressions to specify a list characters we want to either strip out of a string or replace them with other characters however this article is aimed more on how to do a regex reverse match and replace (also knows as a negative replace) where we specify the characters we DO NOT want to be stripped out which can be very useful for sanitising and cleaning out strings and prevent MySQL injections or cross-site scripting attacks. In other words we replace everything but the string specified.

Sounds simple enough yet I found it ever so difficult on how to perform this which is why I am posting it here to save others the time.

Regex Reverse Match

The below examples use the regular expression pattern /[^a-zA-Z0-9\s]/ which basically is just specifying a list of characters (being upper and lower case letters, numbers and spaces). But the big difference is the ^ (caret symbol) is inside the square brackets which tells the regular expression that it is a negative search. ie, match and strip all but the ones listed.

Remember… if we wanted to remove the list of characters specified by the expression’s pattern, then we simply exclude the ^ which mean the resulting pattern to include a list of characters would look like so: /[a-zA-Z0-9]/.

Secondly the second parameter is and empty string which will tell the function to replace the string with nothing.

Note! that if the ^ (caret) was outside the square brackets it would then specify matches at the beginning of a sentence. Just as a $ (dollar symbol) at the end of the sentence would specify matches at the end of the sentence. In this case, the ^ (caret) is inside which denotes an exclusion of characters.

PHP Reverse Replace

<?php

/* our string we will be working on */
$str = "A string - with, awful characters$@!.";
/* use php's preg_replace to execute the regular expression and echo the result */
echo preg_replace( '/[^a-zA-Z0-9\s]/', '', $str );
/* the output from the above will be "A string with awful characters" */

?>

Javascript Reverse Replace

<script type="text/javascript">

/* our string we will be working on */
var str = 'A string - with, awful characters$@!.';
/* use  javascript's replace() function to execute the regular expression and then store the result */
var str = str.replace(/[^a-zA-Z0-9\s]/g,'');
/* the variable `str` from the above will be "A string with awful characters" - all nasty characters are removed */

</script>

Perl Ping Script To Ping Remote Server Or Website

Overivew

Below is a perl script which will allow you to ping a remote server. The article is a follow up article to my php ping script article. This article is similar in that we will also be pinging a remote website to see it if up and running, however this time we will be using perl’s Net module.

Perl Ping Script To Ping Remote Server Or Website

Here is a surprisingly simple perl code snippet to perform a perl ping request to check if a remote server or website is up. It creates a new Net::Ping object and then sends pings the server. We can optionally specify a port to see if a specific port is responding on the server which can be very useful if we want to know if a service is still up and running such as MySQL or Apache.

Perl Ping Specific Port

By using the perl ping script to ping a specific port, we can test wether a service on the server is up and running. For example, port 3306 would test for MySQL, 80 and 443 would test the webserver and 21 would test FTP.

A Perl Ping Script can be very useful and it can be used to make sure a website or server is up and can make our lives easier if we are monitoring multiple servers.

#!/usr/bin/perl -w

use Net::Ping;

# Host can be either an IP or domain name
my $host = "www.google.com";
#optionally specify a timeout in seconds (Defaults to 5 if not set)
my $timeout = 10;

# Create a new ping object
$p = Net::Ping->new("icmp");

# Optionally specify a port number (Defaults to echo port is not used)
$p->port_number("80");

# perform the ping
if( $p->ping($host, $timeout) )
{
        print "Host ".$host." is aliven";
}
else
{
        print "Warning: ".$host." appears to be down or icmp packets are blocked by their servern";
}

# close our ping handle
$p->close();

Conclusion

In the above example, we ping port 80. This will test if the website is active. As stated above, changing from port 80 to 3306 for example, would then test for an active MySQL service running.

Validate IP Address PHP And Javascript Examples

Overview

Below is a similar post to my other post on validate email addresses example except in this post we will validate an IP address instead of an email address. I have also provided simple and straight forward code snippets for Javascript and PHP. It uses a regular expression to test if the string passed to is a check the IP address is valid.

Validate IP Address

Validate IP Address

Validate IP Address PHP And Javascript Examples

The two types of IP Address Validation we will cover are:

I have included both PHP and Javascript Email Validation Examples. It works perfectly for me and hope it will save you hours of time trying to find it out for yourself. Please let me know in the comments if you have any issues.

Validate IP Address In PHP With preg_match()

<?php

/* The IP to test (this IP is valid) */
$str = "100.150.200.250";
/* use php's preg_match to execute the regular expression and store the result - which is either `0` for no match or `1` for a match */
$bValidIP = preg_match( '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $str );

?>

Validate IP Address In Javascript With test()

<script type="text/javascript">

/* The IP to test (this IP is valid) */
var str = "100.150.200.250";
/* The regular expression pattern */
var pattern = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/g;
/* use  javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(str);

</script>

Conclusion

Not much explaining I can do. Essentially there are two methods to validate IP address. First is validate IP in PHP and the second is how to validate IP address in javascript.

PHP Implode Array Key Value – Array Keys To String

Overview

In this tutorial, I will show how you can quickly and easily convert array keys, into a string. The method I use will convert array key values into an array without using foreach() function.

The idea of this code snippet will allow you to convert this:

<?php

$array = (
    'John' => 'John is a common name',
    'Mark' => 'Mark is eating a sandwich',
    'Sarah' => 'Sarah does not like Mondays',
);

Into this:

<?php

$names = 'John, Mark, Sarah';

PHP Implode Array Key Value – Array Keys To String

In PHP there is a great function for converting a PHP Array into a string (and visa versa) using the function implode(). These functions work well on the values of the array, however we are trying to convert he array keys. Luckily in PHP there is a function called array_keys() which will return a list of array keys from the array. Combining these two functions, we can easily convert the keys of an array into a string. Using php implode array key value will easily convert your array’s keys into a string.

Note that as this function converts the array keys into a string rather than the array values. As such, the array passed to the calling function should be an associative array.

The PHP Function

Here is the function used to convert the array keys into a string. If you want to learn how the function works, then view the explanation here.

<?php

// our simple yet effective implode array key function
function implodeArrayKeys($array) {
	return implode(", ",array_keys($array));
}

?>

How the above function works

This is the long winded version of this function explaining how the above implode array keys function works. You should use the above function as the function below is more for information purposes.

<?php

function implodeArrayKeys($array)
{
	// first we get the array keys using array_keys() PHP function
	$keys = array_keys($vars);

	// now join the keys into a string and separate using a comma
	$string = implode(", ",$keys);

	// and return the result
	return $string;
}

?>

And voila, it’s as easy as that.

CSS Padding vs Margin – Whats the Difference?

CSS Padding vs Margin – Whats the Difference?

When cutting up a design into html, you will need to recreate the design in html as accurately as possible. Positioning the elements correctly in html (not to mention, that dreaded cross browser support) can be tricky and having the elements laid out accurately can be the difference between a good looking website and a great looking website. To achieve this you will need to add a bit of div padding or div margins in order to get a div tag aligned into the correct place.

What is the difference between CSS Padding vs Margin

You may wonder what the differences between padding in html and margins in html really are. To give an analogy, think of a cardboard box (that represents your div tag). Now you want to place something inside the box, lets say a vase (in this case, the vase represents the contents inside the div tag, such as text, images or other web content). Now to position the vase correctly inside the box, we would add some newspaper “padding” into the box to hold the contents of the in its positions. The more padding you add, the less space there is in the box for the vase to move.

Now html margins is more like the space around the cardboard box. The more margins you add around the box, the further away it would space other boxes from itself. Larger margins means more space around the box. If you have no space (or html margins), then other boxes will be positioned right next to it.

When to use CSS Margin and CSS Padding

If you wanted to position the contents inside of a div (or any html tag) you will use padding (or newspaper as our previous analogy would depict). However if you wanted to position the div tag (which includes its contents inside), you will use margins.

That is a bit of a long winded description, but hopefully that will correctly explain what the differences are between html padding and margins.

Summary

Basically, when it comes to padding vs margins, your margins are just the space around an element and padding is the space inside an element. Padding being the space inside and Margin being the space around the outside.

Convert String To Array And Array To String PHP

Overview

Arrays are used very often in PHP and at times you will need to convert a string into an array as well as converting an array into a string. PHP has two functions to achieve this and I will give an example of each one.

Simple use cases are splitting a string of names into an array containing all the names. Also converting an array of names, into a string which can be displayed to the user.

Convert String To Array And Array To String PHP

I will show you two ways to convert a string into an array, and a method to convert an array into a string.

  • explode()convert string to an array using a single delimiter
  • preg_split()convert string to an array using regex (more flexible and powerful)
  • implode()convert array to a string

explode()

Convert string to array using explode().

Converts a string into an array. String is split by each delimiter specified by the first parameter passed to the function. If you need to split a string into an array split by a single delimiter, then this method is ideal. If you need to use many delimiters or to split the string using a regex delimiter, then see preg_split() example below.

<?php

/* our string we are going to split (explode()) into an array */
$str = "Split:This:Into:An:Array:Please";
/* $arr will now be an array with the value of array("Split","This","Into","An","Array","Please"); */
$arr = explode(":",$str);

?>

preg_split()

Convert string to array using preg_split().

If you need to split a string into an array using regex, then take a look at the example below. It gives you the ability to convert a string into an array, however it also brings the power and flexibility of regex.

Using preg_split() allows you to split up a string at multiple delimiters. Take the string Tim, Sarah,Albert and Sue. In this case, we need to split the string up by “,” as well as ” and “.

<?php

/* our string we are going to split (preg_split()) into an array */
$str = "Tim, Sarah,Albert and Sue";

/* $arr will now be an array with the value of array("Tim", "Sarah", "Albert", "Sue"); */
$names = preg_split('/(,{1}[\s]?|\sand\s)+/', $str);

?>

implode()

Convert array to string using implode().

Convert an array into a string. Each Element of the array is glued together by the delimiter specified by the first parameter. For example, this is useful if you have an array of names that you want to convert to string to be displayed on a webpage.

<?php

/* our array we are going to glue together (implode()) into a string */
$arr = array("Glue","This","Into","A","String","Please");
/* $str will now be a string with the value "Glue This Into A String Please" */
$str = implode(" ",$arr); /* Note we glued it together with a space */

?>

And that is all there is to it.

Conclusion

While explode offers simple ways to convert string to an array, it lacks the power of preg_split() which allows you to specify the delimiter as a regex. However preg_split has more of an performance overhead as it has to process the regex.

2D Sprite Animation Tutorial

What are sprite animations?

A sprite animation is basically a large image which contains a whole bunch of smaller images. Think of it as a film strip where each frame is the next piece of animation in the sequence. The idea of sprites is that you only need to load one image and it will contain all the smaller images needed to create the animation. You simply position the background position of the sprite and it will appear to animate the sprite. For more information on sprites, check out the css button sprite tutorial.

End Result Demonstration


Above is the finished example of a flame sprite and it is what this tutorial will show you. As you can see it appears as an animation, however we simply move the background position of the larger image to create the illusion of movement.

Why should you use sprites?

Before images and css items can be displayed on your webpage, your browser must request the item such as javascript files, images, css files, etc. Each request takes time and your browser must wait for a response and then download the file for it to be displayed. So in short, the less items means less time to request and download items, meaning less time to load a page. So using sprites will increase the speed at which your website loads.

Flame Ball Sprite

2D Sprite Animation Tutorial

Above is the large flame sprite image I am using to create the sprite animation for this tutorial. We use javascript to move the background position of the sprite image. In the below example, we do this every 100ms. To achieve smooth animation, we would need to achieve 25 frames per second, however this would increase the size of the sprite image, so we will do it a time frames per second.

Now for the code to get this all working

CSS Code

<style type="text/css">

#flameanimation {
	/* our flame sprite png */
	background: url(http://www.example.com/images/flamesprite.png);
	width: 512px;
	height: 512px;
}

</style>

Javascript Code

Here is a quick javascript function to move the background position of the sprite animation to the next frame. We start at frame 1 and for each frame of animation we move 512px to the left since each frame is 512px wide by 512px high. Moving the background image positions every frame creates the illusion of movement, just as a movie is made up of 25 or 29 frames in a second.

<script type='text/javascript'>

$(document).ready(function(){
	// call the next() function every 100 ms.
	setInterval(next, 100);
});

// first frame of animation
var frame = 1;

// move the sprite animation to the next frame
//	i.e. move background position to the next image in the sequence
function next()
{
	// Set the position of the sprite image 512px more to the left on each frame.
	var left = 512 * frame;
	// top stays 0 since all the images have Y positioned at 0
	var top = 0;
	document.getElementById('flameanimation').style.backgroundPosition = '-'+left+'px -'+top+'px'; 

	frame++;
}

</script>

HTML Code

Next we create the div tag where the sprite animation will be applied to.

<div id="flameanimation" title="Sprite Animation"></div>

Now as the javascript next() function runs, it will move the background image to the left which will create the illusion of animation.

flame sprite image obtained from http://forum.unity3d.com/threads/60284-Free-2d-sprite-animations.