Clear Firefox cache – the fastest way

Firefox creators made things really user friendly IMO

You can clear Firefox cache by following these three steps:

  1. Press Ctrl+Shift+Del
  2. Choose the time range and tick the part of your history you wanna get rid of (Browsing and Download History, Forms & Search Data, etc…), you may need to click the arrow to show those details
  3. Click “Clear Now”

After doing your first experiment, you will see that it takes only a few seconds to clear firefox cache.

Firefox clear cache

JavaScript Tween function

This is a small library I wrote for creating simple and complicated easing effects without using JQuery, MooTools or other JS libraries.

The library is small 13.4 KB or 5.6 KB compressed,

The function can be called as follows:

tween(element, property, from, to, duration, [optional] function)

Parameters

element: The idΒ  of the HTML element you want to animate likeΒ  “my_div”, “left_sidebar”, DOM objects are also accepted

property: The CSS property that you want to animate like “color”, background-color”, “left”, “margin-top”…

from: The initial value, like 0px, top, none, 0.5…

to: The final value

duration: the animation duration in ms

function (optional): the easing function to use, by default the tween function uses the linear tween, there are nine other functions included (easeInBack, easeOutBack, easeInOutBack, easeInCirc, easeOutCirc, easeInOutCirc, easeInBounce, easeOutBounce & easeInOutBounce)

Examples

Demos available here

Minified version

Function available here

Full version

var fps = 40;
var debugging = 0;
var tw = [];
var rand_str = generatePassword();
var float_pcre = new RegExp("(\+|-)?(\d*\.)?\d+", 'g');
var color_at_end = new RegExp("[Cc]olor$");

function tween(element, property, from, to, duration) {

    if (arguments.length = 0.75) {
        for (var i = 0; i < tw.length; ++i) {
            if (tw[i]["status"] === "playing") break;
            if (i == tw.length - 1) {
                tw = [];
            }
        }
    }

    var tw_id = tw.length;
    tw[tw_id] = [];
    tw[tw_id]["f"] = (Boolean(arguments[5])) ? arguments[5] : "linear";
    tw[tw_id]["ez"] = 0; // defined here to avoid collisions on simultaneous tw
    tw[tw_id]["status"] = "playing"; // playing, aborted, complete
    tw[tw_id]["element"] = resolve_element(element);
    tw[tw_id]["property"] = resolve_property(property);
    if (Boolean(tw[tw_id]["property"].match(color_at_end))) tw[tw_id]["is_color_tween"] = true;
    tw[tw_id]["duration"] = duration; //ms
    tw[tw_id]["step"] = 0;
    tw[tw_id]["interval"] = 1000 / fps; //ms
    tw[tw_id]["steps"] = Math.ceil(duration / tw[tw_id]["interval"]);
    tw[tw_id]["from_orig"] = from; //  '', 'current', '1', '30%' ...
    tw[tw_id]["to_orig"] = to;
    tw[tw_id]["timer"] = false;

    // Stop simultaneous
    for (var kounter = 0; kounter < tw_id; ++kounter) {
        if (tw[kounter]["status"] !== "playing") continue;
        if (tw[kounter]["element"] !== tw[tw_id]["element"]) continue;
        if (tw[kounter]["property"] !== tw[tw_id]["property"]) continue;
        // We arrived here! that means 2 tw on the same element with the same property, keep the newest tween..
        tw[kounter]["status"] = "aborted";
        clearInterval(tw[kounter]["timer"]);
    }


    if (tw[tw_id]["from_orig"] === 'current') {
        tw[tw_id]["from"] = getStyle(tw[tw_id]["element"], tw[tw_id]["property"]);
        if (tw[tw_id]["from"] === '' || tw[tw_id]["from"] === 'NaN' || typeof (tw[tw_id]["from"]) === "undefined") tw[tw_id]["from"] = tw[tw_id]["element"].style[tw[tw_id]["property"]];
        if (tw[tw_id]["from"] === '' || tw[tw_id]["from"] === 'NaN' || typeof (tw[tw_id]["from"]) === "undefined") {
            if (tw[tw_id]["is_color_tween"]) tw[tw_id]["from"] = "#7F7F7F";
            else tw[tw_id]["from"] = '0';
        }
        // Format the color array
        if (tw[tw_id]["is_color_tween"]) tw[tw_id]["from"] = resolve_color(tw[tw_id]["from"]);
    }


    if (tw[tw_id]["is_color_tween"]) {
        if (tw[tw_id]["from_orig"] === 'current'); // tw[tw_id]["from"]	= tw[tw_id]["from"];
        else tw[tw_id]["from"] = resolve_color(tw[tw_id]["from_orig"]);
        tw[tw_id]["to"] = resolve_color(tw[tw_id]["to_orig"]);
        tw[tw_id]["change"] = [];
        tw[tw_id]["change"]["red"] = tw[tw_id]["to"]["red"] - tw[tw_id]["from"]["red"];
        tw[tw_id]["change"]["green"] = tw[tw_id]["to"]["green"] - tw[tw_id]["from"]["green"];
        tw[tw_id]["change"]["blue"] = tw[tw_id]["to"]["blue"] - tw[tw_id]["from"]["blue"];
    } else {
        if (tw[tw_id]["from_orig"] !== '') {
            // tmp is a temporary variable that I use for retrieving prefix and suffix
            if (tw[tw_id]["from_orig"] === 'current') {
                try {
                    tw[tw_id]["from"] = tw[tw_id]["from"].match(float_pcre)
                } catch (e) {
                    tw[tw_id]["from"] = 0;
                }
            } else tw[tw_id]["from"] = tw[tw_id]["from_orig"].match(float_pcre);

            tw[tw_id]["from"] = parseFloat(tw[tw_id]["from"]);
            tw[tw_id]["to"] = parseFloat(tw[tw_id]["to_orig"].match(float_pcre));
            tw[tw_id]["change"] = tw[tw_id]["to"] - tw[tw_id]["from"];

            var tmp;
            if (tw[tw_id]["from_orig"] === 'current') tmp = tw[tw_id]["to_orig"];
            else tmp = tw[tw_id]["from_orig"];
            tmp = tmp.replace(float_pcre, rand_str);
            tw[tw_id]["prefix"] = tmp.slice(0, tmp.indexOf(rand_str));
            tw[tw_id]["suffix"] = str_replace(tw[tw_id]["prefix"] + rand_str, '', tmp);
        }
    }

    // debuggg...
    if (debugging) {
        var tw_info = new String();
        var elm_props = ['id', 'tagName', 'className'];
        for (var i in tw[tw_id]) {
            tw_info += i + ": ";
            if (i !== "element" && typeof (tw[tw_id][i]) === typeof (Object())) {
                for (var j in tw[tw_id][i])
                tw_info += "nt" + j + ": " + tw[tw_id][i][j];
            } else if (i === "element") {
                for (var j = 0; j < elm_props.length; j++)
                tw_info += "nt" + elm_props[j] + ": " + tw[tw_id][i][elm_props[j]];
            } else tw_info += tw[tw_id][i];
            tw_info += "nn";
        }
        alert(tw_info);
    }

    if (tw[tw_id]["from_orig"] === "") {
        tw[tw_id]["status"] = "playing";
        tw[tw_id]["timer"] = setTimeout("tw[" + tw_id + "]["element"].style[tw[" + tw_id + "]["property"]] = tw[" + tw_id + "]["to_orig"];tw[" + tw_id + "]["status"] = "complete"", tw[tw_id]["duration"]);
    } else ease(tw_id);

    return tw_id;
}

function ease(tw_id) {

    if (tw[tw_id]["step"] === 0) {
        tw[tw_id]["status"] = "playing";
        if (tw[tw_id]["is_color_tween"]) tw[tw_id]["element"].style[tw[tw_id]["property"]] = "rgb(" + tw[tw_id]["from"]["red"] + "," + tw[tw_id]["from"]["green"] + "," + tw[tw_id]["from"]["blue"] + ")";
        else tw[tw_id]["element"].style[tw[tw_id]["property"]] = tw[tw_id]["prefix"] + tw[tw_id]["from"] + tw[tw_id]["suffix"];
    }

    tw[tw_id]["step"]++;

    if (tw[tw_id]["step"] = tw[tw_id]["steps"]) {
        tw[tw_id]["status"] = "complete";
    }

}

function ease_repeat(tw_id) {
    try {
        tw[tw_id]["element"].style[tw[tw_id]["property"]] = tw[tw_id]["ez"];
        ease(tw_id);
    } catch (e) {}
}


/* Keep it simple with these nice functions */

function h2d(h) {
    // hex to decimal
    return parseInt(h, 16);
}

function str_replace(search, replace, subject, count) {
    // version: 908.406
    // discuss at: http://phpjs.org/functions/str_replace
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,
        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = r instanceof Array,
        sa = s instanceof Array;
    s = [].concat(s);
    if (count) this.window[count] = 0;
    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') continue;
        for (j = 0, fl = f.length; j  "MozBorderRadius";
    var matched;
    var dash_letter = new RegExp("-[a-z]");
    while (1) {
        if (matched = property.match(dash_letter)) {
            matched = matched.toString();
            property = str_replace(matched, matched.charAt(1).toUpperCase(), property);
        } else break;
    }
    return property;
}

function resolve_color(color) {
    // return an array containing R, G and B values 
    if (color === 'transparent') // IE (6 and ?)
    color = '#FFF';
    var r, g, b;
    var hex_color_pcre = new RegExp("^#[0-9a-f]{3}([0-9a-f]{3})?$", 'gi');
    var rgb_color_pcre = new RegExp("rgb\(\s*((?:[0-2]?[0-9])?[0-9])\s*,\s*((?:[0-2]?[0-9])?[0-9])\s*,\s*((?:[0-2]?[0-9])?[0-9])\s*\)$", 'gi');
    var rgb_percent_color_pcre = new RegExp("rgb\(\s*((?:[0-1]?[0-9])?[0-9])%\s*,\s*((?:[0-1]?[0-9])?[0-9])%\s*,\s*((?:[0-1]?[0-9])?[0-9])%\s*\)$", 'gi');
    if (color.match(hex_color_pcre)) {
        if (color.length == 4) {
            r = color.charAt(1) + "" + color.charAt(1);
            g = color.charAt(2) + "" + color.charAt(2);
            b = color.charAt(3) + "" + color.charAt(3);
        } else {
            r = color.charAt(1) + "" + color.charAt(2);
            g = color.charAt(3) + "" + color.charAt(4);
            b = color.charAt(5) + "" + color.charAt(6);
        }
        r = h2d(r);
        g = h2d(g);
        b = h2d(b);
    } else if (color.match(rgb_color_pcre)) {
        r = RegExp.$1;
        g = RegExp.$2;
        b = RegExp.$3;
    } else if (color.match(rgb_percent_color_pcre)) {
        r = parseInt((RegExp.$1) * 2.55);
        g = parseInt((RegExp.$2) * 2.55);
        b = parseInt((RegExp.$3) * 2.55);
    } else return false;

    var returned = [];
    returned['red'] = r;
    returned['green'] = g;
    returned['blue'] = b;
    return returned;
}

function getStyle(oElm, strCssRule) {
    // http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/
    var strValue = "";
    if (document.defaultView && document.defaultView.getComputedStyle) {
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    } else if (oElm.currentStyle) {
        strCssRule = strCssRule.replace(/-(w)/g, function (strMatch, p1) {
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

function generatePassword(len) {
    // http://kadimi.com/en/javascript/random-password-string/
    len = parseInt(len);
    if (!len) len = 6;
    var password = "";
    var chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var charsN = chars.length;
    var nextChar;

    for (i = 0; i < len; i++) {
        nextChar = chars.charAt(Math.floor(Math.random() * charsN));
        password += nextChar
    }
    return password;
}

function substr(f_string, f_start, f_length) {
    // version: 908.406
    // discuss at: http://phpjs.org/functions/substr
    f_string += '';

    if (f_start < 0) {
        f_start += f_string.length;
    }

    if (f_length == undefined) {
        f_length = f_string.length;
    } else if (f_length < 0) {
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if (f_length  1000000000 && timeStamp < 2000000000
    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10);

    return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

// My favorite $()


function $() {
    //http://v3.thewatchmakerproject.com/code/extended-dollar.txt
    var elements = new Array();
    for (var i = 0, len = arguments.length; i < len; i++) {
        var element = arguments[i];
        if (typeof element == 'string') {
            var matched = document.getElementById(element);
            if (matched) {
                elements.push(matched);
            } else {
                var allels = (document.all) ? document.all : document.getElementsByTagName('*');
                var regexp = new RegExp('(^| )' + element + '( |$)');
                for (var i = 0, len = allels.length; i < len; i++) if (regexp.test(allels[i].className)) elements.push(allels[i]);
            }
            if (!elements.length) elements = document.getElementsByTagName(element);
            if (!elements.length) {
                elements = new Array();
                var allels = (document.all) ? document.all : document.getElementsByTagName('*');
                for (var i = 0, len = allels.length; i < len; i++) if (allels[i].getAttribute(element)) elements.push(allels[i]);
            }
            if (!elements.length) {
                var allels = (document.all) ? document.all : document.getElementsByTagName('*');
                for (var i = 0, len = allels.length; i < len; i++) if (allels[i].attributes) for (var j = 0, lenn = allels[i].attributes.length; j < lenn; j++) if (allels[i].attributes[j].specified) if (allels[i].attributes[j].nodeValue == element) elements.push(allels[i]);
            }
        } else {
            elements.push(element);
        }
    }
    if (elements.length == 1) {
        return elements[0];
    } else {
        return elements;
    }
}


// Ease function(s)
linear = function (t, b, c, d) {
    return c * t / d + b;
};




















// ease functions
// Back
easeInBack = function (t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c * (t /= d) * t * ((s + 1) * t - s) + b;
};
easeOutBack = function (t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
};
easeInOutBack = function (t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
    return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
};





//Circulat
easeInCirc = function (t, b, c, d) {
    return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
};

easeOutCirc = function (t, b, c, d) {
    return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
};

easeInOutCirc = function (t, b, c, d) {
    if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
    return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
};

//Bounce
easeInBounce = function (t, b, c, d) {
    return c - easeOutBounce(d - t, 0, c, d) + b;
};

easeOutBounce = function (t, b, c, d) {
    if ((t /= d) < (1 / 2.75)) {
        return c * (7.5625 * t * t) + b;
    } else if (t < (2 / 2.75)) {
        return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
    } else if (t < (2.5 / 2.75)) {
        return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
    } else {
        return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
    }
};
easeInOutBounce = function (t, b, c, d) {
    if (t < d / 2) return easeInBounce(t * 2, 0, c, d) * .5 + b;
    return easeOutBounce(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
};
//*/

How can I set a WordPress page as my blog homepage

This can be done with a few clicks from your WordPress blog control panel.

So first login to your control panel, then

  • under the Settings menu choose Reading,
  • after the page finishes loading, choose A static page (select below) for the option Front page displays,
  • then on the first drop-down listΒ  that follows choose the page you want to set as your blog homepage
  • save!.. you don’t wanna forget that one!

You Reading settings should look as follows (in this example, the page title is “The company” ):
WP homepage options

JavaScript round float to n decimal points

The best you can do with built in JavaScript functions is to round a number to the nearest integer using the method Math.round(x), so to round a float to n decimal points we need to come up with our own function.

The function round_float() rounds a floating point number x to n decimals, if you ommit the parameter n, the function will have the same behaviour as the round() method, here is the round_float function definition:

function round_float(x,n){
  if(!parseInt(n))
  	var n=0;
  if(!parseFloat(x))
  	return false;
  return Math.round(x*Math.pow(10,n))/Math.pow(10,n);
}

With prototyping

Dmitry suggested a better approach using prototyping:

if (!Number.toFixed) {
  Number.prototype.toFixed=function(n){
    return Math.round(this*Math.pow(10, n)) / Math.pow(10, n);
  }
}
 
// example:
floating_number = 123.45687;
decimal_points = 2;
window.alert(floating_number.toFixed(decimal_points));

My category order not working after WordPress upgrade

Description

You just upgraded WordPress and “My Category Order” (widget and functions) do not display any categories.
I hate to be you! But wait…

Solution

This is normal and you can fix it very easily by visiting the “My Category Order” page. When you visit the plugin page the first time after a WordPress upgrade, it will show this message:

File /home/advokata/public_html/wp-includes/taxonomy.php has been patched successfully

That’s it…

This is the solution Andrew (plugin author) pointed out by email after I commented on the “My Category Order” plugin page.

setAttribute/getAttribute(“style”) crossbrowser alternative

The JavaScript methods setAttribute and getAttribute are very handy when you are designing dynamic effects for your website, but those methods have a lot of bugs in IE (6 an 7 at least), I use these two crossbrowser functions as alternatives instead of using directly setAttribute() and getAttribute(), I’ve been using them for quite a long time and have had excellent results (crossbrowser compatibility):

/* setStyle function */
function setStyle(element, styleText){
	if(element.style.setAttribute)
		element.style.setAttribute("cssText", styleText );
	else
		element.setAttribute("style", styleText );
}
/* getStyle function */
function getStyle(element){
 	var styleText = element.getAttribute('style');
 	if(styleText == null)
		return "";
	if (typeof styleText == 'string') // !IE
		return styleText;
	else  // IE
		return styleText.cssText;
}

Now use the setStyle function whenever you need to change the style attribite of a HTML element

Demonstration

Roll over this trigger:

setStyle and getStyle Test (using border and padding)

Explanation

On the demonstration we define two style for the div, the default one and one that we will swith to once we “mouseover” the div.

<script type="text/javascript">
/* <![CDATA[ */
/* Test */
var my_element = document.getElementById("test_div");
var my_trigger = document.getElementById("trigger");
var initial_style = getStyle(my_element);
var alternative_style = "border:solid 6px green;padding:6px";
my_trigger.onmouseover = my_element.onload = function (){
	setStyle(my_element, alternative_style);
};
my_trigger.onmouseout = function (){
	setStyle(my_element, initial_style)
};
/* ]]> */
</script>
Roll over this <a id="trigger" href="#" onclick="return false;" >trigger</a>:
<div id="test_div" style="border:solid 2px green;padding:10px">
  setStyle and getStyle Test (using border and padding)
</div>

<div style="display:n

//

How to upgrade Ubuntu from 8.10 to 9.04 using the command line and the Internet?

You can upgrade your linux system using the package manager APT which is available on debian based distributions:

First we have to update all the packages installed:

$ sudo apt-get update
$ sudo apt-get upgrade

Now we make sure that we have the update-manager-core package installed with:

sudo apt-get install update-manager-core

Then we start the upgrade

sudo do-release-upgrade

How to check a file type efficiently in PHP?

The Problem

Do you know a method in PHP to check the type of an uploaded file
without relying on extension or Mime-type because these two can be faked?

Verifying the file type in PHP

Relying on the Mime-type of a file submitted by a user is a bad practice, using the extension is even worse!
Some people use functions of the php fileinfo extension, these functions do not rely on file extensions but do rely on bytes sections of the file that can be easily faked.

You can retrieve the mime type with finfo_file() like this:

<?php
$filename = "test.gif"

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file_mime_type = finfo_file($finfo, $filename);
finfo_close($finfo);

echo $file_mime_type; // Expected ouput: image/gif
?>

So you can use the php fileinfo functions to determine if the file is what it claims to be, I mean that the file extension matches the result of finfo_file(), if it doesn’t, there is no need to go further, the file should be rejected from being stored on your server and from beig served to your website visitors.

If the extension matches the MIME type we will have to go further and check if the files is really a GIF/JPEG/ZIP file or a fake file with malicious code.

For that we need to have a set of functions for the MIME types we are interested in, for images for example (TIFF, PNG, GIF, JPEG…), there is a good function that uses the identify linux command, modify it to suit your needs

<?php
function is_jpg($fullpathtoimage){
  exec("/usr/bin/identify -format %m $fullpathtoimage",$out);
  //using system() echos STDOUT automatically
  if(!empty($out)){
    //identify returns an empty result if the file is not an image
    if($out === 'JPEG')
      return true;
    return false;
  }
}
?>

Original code written by Ryan Day

Since I do not use file uploads, I can not provide functions for other file types, but I will search for them and edit my post if I find any.

There’s another solution that should work for all types but I’m not sure about it, it uses the linux file command:

<?php
function file_mime_type($fullpathtoimage){
 exec("/usr/bin/file -bi $fullpathtoimage",$out);
 $mime_type = array_shift(explode(';',$out[0]));
 return $mime_type;
}

// Test
print_r(file_mime_type(__FILE__)); // Outputs: text/x-c++ which is ok
?>

SMF mod: Add Posts Navigation

preview

Description and Features:

Enhance your website accessibility and add posts navigation arrows within posts to let you and your visitors navigate very easily between posts and pages:

  • Place top and down arrow within posts
  • Topmost arrow or downmost arrow take you to the previous or next page
  • No additional images loaded
  • No JavaScript
  • Unlike all other similar mods, this one is not broken when a post is deleted from the topic
  • Unlike all other similar mods, No useless arrows are shown (when there is no next or previous post or page)

Requirement(s):

Works on the default theme only

Demo:

See image

Download:

Link to download SMF mod: Add Posts Navigation

Print HTML code from JavaScript variable

This also was about to drive me crazy so I will not let it go without writing about it..

Let’s say you have some long HTML code contained on a PHP variable, something like this

<?php
$some_div = '
<div id="box">
  <h1>Title</h1>
  <p>Article contents + comments</p>
<div>';
?>

Now you want to use this HTML code as a JavaScript variable instead of printing it directly, you will tell me you’ll do this:

<script type="text/javascript">
/* <![CDATA[ */
  var some_div = '<?php echo $some_div; ?>';
/* ]]> */
</script>

JavaScript doesn’t like unescaped new lines and special characters (mainly “, <Β  and >) too much, so the previous code won’t work, my quick solution for that is to do the following:

  • Encode the html code in PHP using urlencode
  • Decode it within JavaScript

When using PHP’s urlencode function, all whitespace characters will be replaced by + signs, so we’d better deal with those characters before encoding them, otherwise, we won’t make a difference between spaces and real + signs, please read the comment on the PHP code below to understand:

<?php

// replace consecutive white space characters with a single space
$some_div_2 = preg_replace('/s+/',' ',$some_div);

// Explode (cut the string on the white space and put the resulting part on an array)
$some_div_2 = explode(' ', $some_div_2);

// Encode the text contained on the array cells
foreach($some_div_2 as $index => $content)
  $some_div_2[$index] = urlencode($content);

// Implode (reassemble) the array to a string again
$some_div_2 = implode(' ', $some_div_2);

?>

<script type="text/javascript">
/* <![CDATA[ */

  // Import the variable from PHP
  var some_div = <?php echo $some_div_2; ?>

  // Decode it
  some_div_2 = unescape(decodeURI(some_div));

  // Display it
  document.writeln(some_div_2);

/* ]]> */
</script>

A note on JavaScript arrays creation & initialization

I use PHP a lot in my projects and it happens that sometimes I combine PHP with another language and write completely useless code.

PHP arrays can be created and initialized with like this:

<?php
  $cities[] = "mecca";
  $cities[] = "medina";
?>

I thought that the same would apply to javascript… Yes, it can work, but only if the array already exists, otherwise you will get an error, Your browser will tell you that it can’t find that array, pretty simple… maybe…

var cities = []// we create the array first
  cities[0] = "mecca";
  cities[1] = "medina";

Note that JavaScript doesn’t automatically assign table indexes, you have to set them automatically. +1 for PHP (on most other languages)

Get file extension on PHP

There are many ways to retrieve files extension with PHP, but we will have to choose one that feets our needs and gives more reliable results.
When dealing with file extension you should know that a file extension is not always 3 characters long (ex:Β  foto.jpeg, index.html) and that it doesn’t start after the last dot (.) in the file name (ex: program.tar.gz, config.php.inc).

Let’s write the filename_details function that we will use to retrieve the extension of the file module.tar.bz or any file you have:

<?php
function filename_details($filename, $dots){
  $filename_no_ext = $filename;
  while($dots--){
    $temp_arr = explode('.', $filename_no_ext);
    $extension = '.'.array_pop($temp_arr).$extension;
    $filename_no_ext = implode('.', $temp_arr);
  }
  $extension = substr($extension, 1);
  return array($filename_no_ext, $extension);
}
print_r(filename_details('module.tar.bz',2));

/*
Output: 
Array
(
  [0] => module
  [1] => tar.bz
)
//*/

?>

Install PHP 5.2.6 on CentOs 5.x

Oddly enough, PHP 5.2.6 is still not available on the default CentOS repositories ([base], [updates], [addons], and [extras]), the latest PHP version available in those repos is PHP 5.1.6!

In order to install PHP 5.2.6 you can add the CentOS testing repository and enable it then install or update PHP.

To add the CentOS testing directory, create a file /etc/yum.repos.d/centos-test.repo and add this line:

[c5-testing]
name=CentOS-5 Testing
baseurl=http://dev.centos.org/centos/5/testing/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://dev.centos.org/centos/RPM-GPG-KEY-CentOS-testing

Then install or update PHP:

[root@server ~]# yum install php

or

[root@server ~]# yum update php

Then you can disable the testing repo by editing the file and setting the option “enabled” to “0”

[c5-testing]
name=CentOS-5 Testing
baseurl=http://dev.centos.org/centos/5/testing/$basearch/
enabled=0
gpgcheck=1
gpgkey=http://dev.centos.org/centos/RPM-GPG-KEY-CentOS-testing

MySQL script files how-to

What is a MySQL script file?.. Why use it?

A MySQL script file (aka MySQL batch file) is a regular text file containing MySQL statements separeted by terminantors, statements in a MySQL script file can be run from the MySQL client, this is very useful, many PHP script available online come with MySQL script files that need to be run as part of the PHP script installation process, Continue reading “MySQL script files how-to”