Category Archives: Programming

Programming hints, tips, setups and tutorials

jQuery: How to Check if an Element has Class ‘X’ or ‘Y’ Programming 15 MAR 2015

If you find yourself needing to check whether or not a particular HTML element has a specific class currently assigned to it, you’ll be pleased to know that the awesome jQuery javascript library has you covered with their ever so useful .hasClass function.

This function determines whether any of the matched elements are assigned the given class, returning true if the searched for class is in fact assigned to an element – regardless of whether or not that element has more than one class assigned to it. (Remember, HTML allows elements may have more than one class assigned to them – separated by a space in HTML notation.)

An example:

<div id="mydiv" class="foo bar"></div>
$( "#mydiv" ).hasClass( "foo" ); //returns true
$( "#mydiv" ).hasClass( "quu" ); //returns false

In other words, no need for splitting an element’s class attribute and then looping through the strings just to see if a particular class exists any more!

a lady with class - audrey hepburn

jquery logo

Related Link: https://api.jquery.com/hasclass/

PHP: Return Random Element in Array Programming 06 AUG 2014

A quick and easy PHP code snippet to return a random element from a given array:

$items = array('yellow','green','red');
echo $items[array_rand($items)];

All the hard work is being done by the native array_rand php function. Essentially, array_rand picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

Here is an example picking out two random elements from an array:

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";

Quick and easy.

php-banner-strip

Related Link: http://php.net/manual/en/function.array-rand.php

PHP: How to Create a Thumbnail from a Video file on an Ubuntu Linux Apache Webserver Programming 26 NOV 2013

green php elephants - elephpantsThanks to the powerful command line ffmpeg package and PHP’s ability to execute server commands through shell_exec, generating a thumbnail image from a given video file becomes a snap!

First, install the ffmpeg package onto your Ubuntu server with:

sudo apt-get install ffmpeg

Once installed, we can then turn our attention to the PHP script that will be doing the slog work. Essentially it uses ffmpeg to process the video file and create the image for us, meaning that in actual fact, the PHP script has very little to do with the actual donkey work!

function createVideoThumbnails($videopath,$imagepath) {
    $status = false;

    // where ffmpeg is located, such as /usr/sbin/ffmpeg
    $ffmpeg = '/usr/bin/ffmpeg';

    // the input video file
    $video = $videopath;

    if (file_exists($video)) {

        // where you'll save the image
        $image = $imagepath;

        // default time to get the image
        $second = 1;

        // get the duration and a random place within the video file
        $cmd = "$ffmpeg -i \"$video\" 2>&1";
        if (preg_match('/Duration: ((\d+):(\d+):(\d+))/s', `$cmd`, $time)) {
            $total = ($time[2] * 3600) + ($time[3] * 60) + $time[4];
            $second = rand(1, ($total - 1));
        }

        // get the screenshot
        $cmd = "$ffmpeg -i \"$video\" -deinterlace -an -ss $second -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg \"$image\" 2>&1";
        $return = `$cmd`;

        if (file_exists($image)) {
            $status = true;
        } else {
            $status = false;
        }
    } else {
        $status = false;
    }
    return $status;
}

We make two calls to the ffmpeg function, the first to work out the duration of the video which we then use to make a random call as to where to take the thumbnail from in terms of starting point. The second call actually generates the thumbnail image, using the fully qualified video and image paths that we passed to the function right at the start.

So pretty simple stuff in other words. Note that if you want to specify the size of the generated screenshot, you can make use of the -s parameter. For example:

$cmd = "$ffmpeg -i \"$video\" -deinterlace -an -ss $second -t 00:00:01 -r 1 -y -vcodec mjpeg -s 180x135 -f mjpeg \"$image\" 2>&1";

Nifty.

How to Set a Cookie using jQuery Programming 27 AUG 2013

jquery-logoIf jQuery is your javascript manipulation library of choice, then you would be pretty pleased that developer Klaus Hartl took the time and whipped up his excellent jquery-cookie plugin, thereby making the act of setting or retrieving browser cookies in your jQuery JavaScript a snap!

To set the value of a cookie is pretty simple, just pass along a key and a value, and as expected, you can make it a little more verbose by including a selection of all the standard cookie stuff like expiry date, path, or domain.

In action:

$.cookie("mycookie", "on!");

//Additionally, to set a timeout of a certain number of days (10 here) on the cookie:
$.cookie("mycookie", "on!", { expires : 10 });

Note, if the expires option is omitted, then the cookie becomes a session cookie, and is deleted when the browser exits.

This snippet covers most of the options in setting up a cookie that are available to you:

$.cookie("mycookie", "on!", {
   expires : 10,           //expires in 10 days

   path    : '/',          //The value of the path attribute of the cookie 
                           //(default: path of page that created the cookie).

   domain  : 'jquery.com',  //The value of the domain attribute of the cookie
                           //(default: domain of page that created the cookie).

   secure  : true          //If set to true the secure attribute of the cookie
                           //will be set and the cookie transmission will
                           //require a secure protocol (defaults to false).
});

To read back the value of the cookie:

var cookieValue = $.cookie("mycookie");

//You may wish to specify the path parameter if the cookie was created on a different path to the current one:
var cookieValue = $.cookie("mycookie", { path: '/view' });

To delete a cookie:

$.removeCookie("mycookie");

Right, that should now be enough to get you up and running!

Related Link: https://github.com/carhartl/jquery-cookie

PHP: Get the Number of Days between Two Dates Programming 22 AUG 2013

green php elephants - elephpantsA fairly common programming problem that crops up is calculating the number of days between two dates.

Prior to PHP 5.3 and all the goodness it added to the language, one usually set about calculating this simply by converting both dates to timestamps and then subtracting the one from the other, before finally converting the result into days which would of course be your answer.

Note that this was not particularly useful for all the guys out there using daylight savings time, but for guys like us in South Africa then it was perfectly fine!

In practice, this would have looked something like this:

$now = time(); // or your second date
$your_date = strtotime("2013-01-01");
$datediff = $now - $your_date;
echo floor($datediff/(60*60*24));

However, if you do have access to PHP 5.3, and really, you should by now, then you’ll be far better off using the functionality that the clever DateTime construct gives us:

$start_timestamp = time(); // or your second date
$end_timestamp = strtotime("2013-01-01");
$datetime1 = new DateTime(date('Y-m-d', $start_timestamp));
$datetime2 = new DateTime(date('Y-m-d', $end_timestamp));
$interval = $datetime1->diff($datetime2, true);
$days = intval($interval->format('%a'), 10); //or echo $interval->format('%R%a')

Nifty.

Bonus: And say that we wanted to be sure we have a full set of say 7 day periods for a trend graph, then we could use the above in something like this:

$datetime1 = new DateTime(date('Y-m-d', $start_timestamp));
$datetime2 = new DateTime(date('Y-m-d', $end_timestamp));
$interval = $datetime1->diff($datetime2, true);
$days = intval($interval->format('%a'), 10);
$extra = $days % 7;
if ($extra != 0) {
    $extra = 6 - $extra;
}
if ($extra != 0) {
    $start_timestamp = strtotime('-' . $extra . ' days', $start_timestamp);
}

That last one is more of a note to myself than anything else to be honest. Anyway, as per usual, play around with it on the useful PHP Code Pad.

CSS: How to Horizontally and Vertically Center Align a DIV Box Programming 15 AUG 2013

css ninja t-shirtAs a rule (well to me anyway), login boxes look their absolute best when centering slap bang in the middle of the page, in other words centered both horizontally as well as vertically!

To achieve this middle of everything trick using plain old CSS is pretty simple, and in this quickfire tutorial example, I’ll show you just how easy it is to end up with a nicely placed DIV block, listing both the required CSS as well as a handy selection of demo HTML.

Let’s begin with the CSS:

html, body {
  height: 100%; //pretty important!
}
 
body {
  margin: 0; //doesn't strictly have to be zero, CSS would probably readjust
}
 
.loginformbox {
  width: 100%;
  min-height: 120px;
  font-size: 1.5em;
  text-align: center;
}
 
.loginformboxcentered {
  display: inline-block;
  vertical-align: middle;
  padding: 20px 50px; //whatever look spretty to you
  font-size: 1em; //note you have to set size, thanks to our zeroing of the parent container's value
  letter-spacing: normal;
}
 
.loginformbox .loginformboxcentered {
  width: 800px; //this defines how wide your block is
  margin: 0 auto;
  text-align: left;
}
  
 .loginformbox:before {
  content: "";
  display: inline-block;
  vertical-align: middle;
  width: 0;
  height: 100%;
  min-height: inherit;
  max-height: inherit;
  padding: 0;
}

Right, for the most part pretty self explanatory (actually that’s not completely true. But seeing as this post is kind of for my reference and I don’t really want to comment up all the CSS, I’m going to leave it at that).

Right, now for the HTML:

<html>
<body>
<div class="loginformbox ">
    	<div class="loginformboxcentered">
    		<h1>My Login Box</h1>
    		<p>A nice and vertically and horizontally centered login box. Nifty.</p>
    	</div>
</div>
</body>
</html>

And to be honest, that’s pretty much it. Copy, paste and off you go!

How to Generate a Random Number in JavaScript Programming 13 AUG 2013

javascript logoGenerating a random number in JavaScript is a relatively easy thing – we simply made use of JavaScript’s built in random() function, part of the JavaScript Math object.

The random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

If we then combine this method with the floor() method (also from the JavaScript Math object – Give x, returns x, rounded downwards to the nearest integer), then it becomes trivial to quickly generate a random number.

For example:

//Return a random number between 1 and 10:
Math.floor((Math.random()*10)+1);

//Return a random number between 1 and 50:
Math.floor((Math.random()*50)+1);

Simple and effective.

How to get a simple File Listing in PHP Programming 08 AUG 2013

green php elephants - elephpantsReturning a list of files contained in a folder in PHP is turned into something fairly trivial, thanks to the built in readdir function. Basically, the function returns the name of the next entry from the currently open directory handle resource, itself opened with the standard opendir command.

(Note, if the directory handle is not specified, the last link opened by opendir() is assumed.)

The readdir function returns the file name entries in the order in which they are stored by the filesystem, meaning that it is up to you if you want to present them ordered in a particular fashion.

So in practice, a simple file listing in PHP would look as follows:

if ($handle = opendir($_SERVER['DOCUMENT_ROOT'] . '/portal/widget_scripts')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<p>$entry</p>\n";
        }
    }
    closedir($handle);
}

Nifty.

CSS: How to Force a Footer DIV to Stick to the Bottom of a Page Programming 06 AUG 2013

css ninja t-shirtWeb page design at the moment has very much settled on the layout of header, content and footer panels. For this particular quick tutorial I’m going to show you how to very simply force your footer div to ‘stick’ to the bottom of the page, meaning that even for pages that are very light on content, your happy little footer bar will remain firmly at the bottom of the browser window, instead of hanging about and looking silly in the middle of the page.

As it turns out, achieving this is relatively simple and the technique can easily be applied to existing websites if necessary. So what needs to be done then?

Well for a start, you need to declare the following CSS rules:

html {
    position: relative;
    min-height: 100%;
}
body {
    margin: 0 0 100px; /* bottom matches your desired footer height */
}
#footer {
    position: absolute;
    left: 0;
    bottom: 0;
    height: 100px;
    width: 100%;
}

And that’s pretty much it. Here’s some sample HTML code to see how it would appear in action:

<!DOCTYPE html>
<head>
    <title>Hello World</title>
</head>
<body>
    <div id=header>Hello World</div>
    <div id=content>Lorem ipsum...</div>
    <div id=footer>My Footer</div>
</body>
</html>

This works in IE8+, Chrome, Firefox, and Opera.