Archive for category Programming Languages

PHP Redirect 301 Permanently

Sometimes you might want to redirect your visitors to a new URL address. This article will show you how to make a PHP redirect using the 301 “moved permanently” redirection. This is the one you should use as it is the most search engine friendly. Like the name suggests, PHP redirect tells the browser (or a search engine bot) that the page has been permanently moved to a new location.

PHP Redirect Code

To redirect people and robots to a new location use this PHP redirecting code:

header("HTTP/1.1 301 Moved Permanently");

You could skip the 301 Moved Permanently tag and use just:


But this would result in a “302 Moved Temporarily” redirect instead of a 301 one. This should be avoided as permanent redirects are more search engine friendly and should be used where possible.

You can enter any sub-page for the location, this PHP code will redirect users to the test.php sub-page of your website:

header("HTTP/1.1 301 Moved Permanently");

It is important that you don’t have any other code (including empty rows and spaces) before the above PHP redirect code. If you do you will get a nice headers already sent notice from PHP and the redirect will not work.

That’s it! Enjoy redirecting PHP pages.

No Comments

Compressing Stylesheets with PHP

If you wonder what else you can do to compress your files, I found a PHP code of which is written by a German coder that is shared on another blog. Basicaly it removes spaces and back slashes to minify the included files and compress them using ob_gzhandler.

  header('Content-type: text/css');
  function compress($buffer) {
    /* remove comments */
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    /* remove tabs, spaces, newlines, etc. */
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
    return $buffer;

  /* your css files */


No Comments

Compressing Web Site Contents, Scripts and Stylesheets

Today I wonder how I could minify my javascript files and do a server side compression to minimize the cost of loading web site requred javasript and stylesheet files. Where to begin… I’ll start from Apache Server configuration information for server side compression and finish with YUI Compressor that helps you to minify your script files as you should have seen those files ending with “your_script_file.min.js”. If you are using Apache Server, you might have Deflate Module installed with your Apache installation. What you need to load this module while your your server starts is to configure your apache configuration file.

LoadModule deflate_module modules/

And if you have access to the httpd.conf then you can add following lines to it.

<Location />
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/x-js text/css

If not; you should specify the initialization line into your htaccess file.

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css text/plain text/javascript text/xml application/xhtml+xml application/x-httpd-php

You might have problems to compress javascript files which has different mime types. Then, you can use followig configuration.

AddOutputFilterByType DEFLATE application/x-javascript

That will do. Now, I will introduce YUI Compressor. YUI Compressor is one of Yahoo developer team product that you can download from here. If you have dowloaded the YUI Compressor built from the site that I shared above, what you should do to compress your file is:

java -jar yuicompressor-x.y.z.jar myfile.js -o myfile-min.js --charset utf-8

Where, x, y and z are the version number of the YUI Compressor download. Also you can find more information about YUI Compressor at

Thank you for reading, I hope this will help some of you guys.

No Comments

CakePHP : Translate Behaviour : Fixing Nested Translation Problem

If you ever tried to use Translation Behaviour of CakePHP you should realize that Translate Behavior does not support nested translations for the model relations. I’ve found one article that shows how to fix a similar translation problem on related models at

Unfortunately it was not a complete solution that you can implement easily but it gave me a good approach to help the model to request nested queries to make Translate Behaviour work.

I need to warn you that this solution is not a really good one but until CakePHP team fix this issue on one of the future releases of CakePHP this would help you a lot.

Here is the code:

class AppModel extends Model {

    var $_findMethods = array('all' => true, 'first' => true, 'count' => true,
		'neighbors' => true, 'list' => true, 'threaded' => true, 'translated' => true);

    function _findTranslated($state, $query, $results = array()) {
        if ($state == 'before') {
            return array_merge($query, array(
                //'fields' => array('id', 'name'),
                //'recursive' => -1
        } elseif ($state == 'after') {
            if (empty($results)) {
                return $results;

            // get the model's belongs to relation model names
            $belongsTo = Set::extract($this->belongsTo, '/@*');

            if(!empty($belongsTo) && isset($belongsTo[0]) && is_array($belongsTo[0]))
                $belongsTo = $belongsTo[0];

                foreach($results as &$result)
                    foreach($belongsTo as $modelName)
                        if(isset($result[$modelName]) &&
                            isset($result[$modelName]['id']) &&

                            $data = $this->$modelName->find('first', array(
                                'conditions' => array(
                                    $modelName.'.id' => $result[$modelName]['id']
                                'recursive' => -1

                                $result[$modelName] = $data[$modelName];

            return $results;

What you need to do is just implement the _findTranslated method on your model or on AppModel for general usage with the $_findMethods private variable and instead of using regular find methods for example:


You should use:


And the result will look as the same above but with translated inner relations.

Not: I have not implement all types of the relations yet but if you find hard to add such relations let me know, I’ll do my best.

I hope this could help you. Please leave me some responses to make sure is helpful.

Thank you for reading this article.

No Comments

Ext JS Templates – The Complete Tutorial

Today I’ve searched all over the web sites to find some basic Ext JS template definitions and could not find a good resource as I needed. So, I decided to bring out one myself. Hope you will enjoy.


Ext JS templates have their own parsing algorithms that needs to be compiled before used and here is a quick start to it.

Defining Variables

If you would like to add variables on the template you need to surround the variable name with curly parentheses (‘{‘ and ‘}’ ).



Using Variables in Texts

To add variables into the predefined texts you can just add the variable with curly parentheses where you want to put the variable.


This page has {page_picture_count} pictures.

Using HTML Tags on Templates

It is the same way you add html tags on your Ex JS template as adding predefined text.


<a id="{id}" href="{url}">{text}</a>


You can set conditions to perform on template rendering to the parameter as well. How you do this is pretty simple.


<tpl if="your condition">{field}</tpl>

Example 1 (If condition):

<tpl if="{field}=='Good Example'">{field}</tpl>

With this template what ever else the field variable is will not be evaluated except if it is equal to ‘Good Example’ string.


You can use loops when you need to output a list of variables.


<tpl for="{parent}">{child}, </tpl>

With this template for each child in parent will be separated with columns.

Example 2 (If and Else If condition):

<tpl if="{field}=='Good Example'">{field}</tpl>
<tpl if="{field}=='Else Example'">{field}</tpl>

With this template what ever else the field variable is will not be evaluated except if it is equal to ‘Good Example’ or ‘Else Example’ string.

Using Predefined Functions on Templates

Ext JS has internal Template functions that are useful for your templates.

Suppose we want to output a variable named content but we are afraid that it may take too much space. A useful feature would be able to truncate this content to 50 characters and show the user a link to view all of the content. We can use the formatting function “ellipsis” to truncate the content to only 50 characters. This function will also append “…” to indicate to our users that there is actually more content but it has been truncated.


<div>{content:ellipsis(50)}<br/><a href="{moreLink}">Read More</a></div>

Here is a list of the formatting functions which you can use with Templates:

ellipsis(length): Abbreviate your variable to a specified length and append “…”. Useful for when you want to only show the first x characters and then provide a more detailed view.

undef: If the variable is undefined show “” instead of “undefined”

htmlEncode: If the variable contains ampersands, less than, greater than symbols or quotes HTML escape them.

trim: If the variable contains extra rwhite space, trim it.

substr(start, length): Substring the variable

lowercase: Transform the variable to all lowercase.

uppercase: Transform the variable to all uppercase.

capitalize: Capitalize the first letter of the variable, the remaining characters will be transformed to lowercase.

usMoney: Format in US Dollars. ie: $10.97

date[(format)]: Transform the variable to a date format, if the format argument is omitted uses the mask ‘m/d/Y’

stripTags: Strips the variable of all html tags.

You can also create your own custom formatting functions by adding a new method to your template instance and calling it by prepending this. to your format function like this “{VARIABLE:this.<FORMATFUNCTION>}”

Here is a sample which adds a new function called yesNoFormat to an instance of a template. yesNoFormat is similar to a ColdFusion function which converts ‘truthy’ values to the word “Yes” and ‘falsey’ values to the word “No”.

var testCustomTpl = new Ext.Template(
    '<div>User: {username} IsRevoked: {revoked:this.yesNoFormat}</div>'
testCustomTpl.yesNoFormat = function(value) {
	return value ? 'Yes' : 'No';
testCustomTpl.append(document.body, {username: 'aconran', revoked: 1});

Note: This post will continue when I found something else and developing some examples on Ext JS Templates.

No Comments

Building the Best SQL Manager With PHP (Part 2)

After a long day work on a complicated class I finally finished my requiered querying algorithm. The final output of my SQL Manager class is like

 `adproperties`.*, `properties`.*
 FROM `adproperties`
 left join (select
 FROM `advertisementproperties`
  WHERE ((`advertisementproperties`.`advertisement_id` = '113'))) `properties` on (`properties`.`adproperty_id` = (`adproperties`.`id`))
  WHERE ((`adcategory_id` = (select
 `advertisements`.`adcategory_id` as adcategory
 FROM `advertisements`
  WHERE (((`advertisements`.`id` = '113') and (`advertisements`.`account_id` = '1'))))))

This worked for me perfectly. Even I add some more conditions on it. Later I’ll have time to fix the paranthesis problem but for the beginning, I’ll keep using this code instead of the old one.
I must finaly point that, I have not tried it with other kind of configuration array but after I finish the whole it will be the perfect SQL Manager Class written in PHP ever.

No Comments

Building the Best SQL Manager With PHP

Today I decided to improve one of my developed SQL Manager class to be able to create easy sql queries but complicated enough not to be able ease work on defining the complicated queries. With my old solution I could not be able to complete a query like below.

FROM `adproperties`
                WHERE `advertisementproperties`.`advertisement_id` = 110) `properties`
ON `properties`.`adproperty_id` = `adproperties`.`id`  
`adcategory_id` = (SELECT 
                           `advertisements`.`adcategory_id` as `adcategory` 
                           FROM `advertisements` 
                           WHERE `advertisements`.`id` = 110)

It is something right? So, what I need to do is adding inner queries up on my old manager even on the Joining phrases and Where clauses. It is not easy to build a complete solution for SQL because you would always think on the current problem to be fixed not the whole. Even though, I could have been able to build a generalization to create search queries on the relational queries of which is also used in many projects of mine.

Now what I can do with it is like:

`adproperties_rel`.`id` as `adproperty_id`,
FROM `advertisementproperties`
RIGHT JOIN `adproperties` `adproperties_rel`
ON `adproperties_rel`.`id` = `advertisementproperties`.`adproperty_id`
(`adproperties_rel`.`account_id` = '1') or ISNULL
(`adproperties_rel`.`account_id`)) and (
(`advertisement_id` = 113) or ISNULL
(`advertisement_id`)) and
(`adproperties_rel`.`adcategory_id` = '22')

This code above is not able to do what I needed and it is not a good SQL query either. What I really need to do is to create better querying solution for it.

I started from the end to internal core of the code and firstly defined the object that I would like it to create my query:

$sqlMgr = new SQLManager(array(
    "method" => "select",
    "selections" => array("adproperties"  => "*", "properties"  => "*"),
    "tableName" => "adproperties",
    "relations" => array(
        "properties" => array(
            "join" => "left",
            "tableName" => array(
                "query" => true,
                "method" => "select",
                "tableName" => "advertisementproperties",
                "conditions" => array("advertisementproperties" => "advertisement_id", "=" => 113)
            "conditions" => array("properties" => "adproperty_id", "=" => array("adproperties" => "id"))
    "conditions" => array(
        "=" => array(
            "query" => true,
            "method" => "select",
            "tableName" => "advertisements",
            "selections" => array("advertisements" => "adcategory_id"),
            "fieldAliases" => array(
                    "table" => "advertisements", 
                    "name" => "adcategory_id",
                    "alias" => "adcategory"
            "conditions" => array(array("advertisements" => "id", "=" => 113), "and" => array("advertisements" => "account_id", "=" => 1))

This code should definitely do what I would like to do with my SQL Manager Class. Now is the time to get this configuration in to action.
With my old SQL Helper I’m no where close :)

SELECT `*`.*, `*`.*, `l_rel`.`l` as `l`, `adproperties`.`_rel`
 FROM `adproperties`
 L JOIN `l` `l_rel` ON `l_rel`.`l` = `adproperties`.`l` 
  JOIN `` `_rel` ON `_rel`.`` = `adproperties`.`` 
(`advertisements`.`adcategory_id`) and 
(`_rel`.`Array`)) and ()

Some of the generated query is right how it supposed to be. I’ll start from the selections.

No Comments