Tag Archive: PHP

Some CakePHP Productive Tips

CakePHP Logo

I’ve been playing around with CakePHP for the last several days. I’m beginning to enjoy using it through the CLI (Command Line Interface) tools that comes with the framework. Maybe because I spent too much time on the command line thanks to the CR-48 (Chrome OS) developer mode :) . Anyway, here are some tips I found while learning this easy to use PHP framework:

  1. During the development, it’s a good practice to change the default value for CAKE_CORE_INCLUDE_PATH both in the index.php and test.php of webroot directory in case you forgot when deploy to the server. For example, I changed the value of this constant to $_SERVER[‘DOCUMENT_ROOT’] . DS . ‘cakephp’ which is converted into localhost/cakephp. Once I deployed the application to the server, the included path will change to robbychen.com/cakephp without any modification.
  2. According to its documentation, each database has its own form control and data type relationship. For example, the tinyint data type for MySQL generates the checkbox control, whereas the boolean data type for SQLite also generates the checkbox control. It also applies to the latest stable version of CakePHP 1.3.
  3. If you want additional database options, you can download datasources plugin. This plugin also contains sqlite3 which, for some reasons, haven’t included with the CakePHP core yet. If you’re going to use SQLite in the framework without this plugin or just specify sqlite in the database config file, it will use version 2 instead.
  4. This is probably a bug in CakePHP: The CakePHP console cannot find the sqlite database file unless it’s in the root of the application folder, whereas the CakePHP web application looks for the file in the webroot directory of the application folder. The database configuration cannot be simply changed to webroot/database.sqlite. If it changes to that value, the console could find it (webroot/database.sqlite) but the web application could not (webroot/webroot/database.sqlite). The solution I decided is to make a link at the root folder to link to the sqlite file in the webroot directory. This way could both benefit the console and web application. It however does not suitable for some of you who are working on both the localhost and the production server, or often change folder, since the link target cannot be edited. The link will break once the whole directory is moved to a different machine or the target file was renamed or moved.
  5. Type cake api [type] [method] in the command line to browse through the CakePHP documentation. It is a very helpful command for use as a reference. However, you may learn some new tricks through this command, or you could use this as the primary learning resource for CakePHP assume that you already knew this command before you learn something else. For example, I found something useful for my project in the Ajax API: cake api helper ajax

I hope these tips help you to become more productive with CakePHP. If you have any questions regarding the above tips, feel free to post them in the comment below.

Download WordPress and Other Source Code files Directly to your Server without download Locally using PHP copy function


When I tried to get the development environment working with Chrome OS (CR-48), I thought since Chrome OS is primary working for the cloud, why am I downloading, editing, and testing the website files locally? I found out that my hosting provider, iPage, offers a file manager and a basic text editor to manage and edit my PHP files, and since I use gEdit as my main code editor, I’m pretty comfortable with the text editor.

Basic code editor

The basic code editor available in the control panel

I shortly found some useful file operation functions on the official PHP document, one of them is copy. According to its documentation, the source and destination can both be URLs since 4.3.0. This means that I can download the code from another website directly to my server using the server resources. I wrote a test page to test this function and it worked without problem.

The Code

<section id='fileDownloader'>
 <article id='urlForm'>
  <form id='url' name='url' method='post' action=''>
   <label for='urlInput'>The file to be downloaded (URL): </label>
   <input type='text' name='urlInput' id='urlInput' placeholder='URL' size='60' autofocus value="<?=($_POST['submit'])?$_POST['urlInput']:""?>" />
   <br />
   <input type='submit' value='Download' name='submit' />
 <?php if ($_POST['submit']): ?>
 <article id='downloadStatus'>
  if (empty($_POST['urlInput'])): die("Please enter a valid download URL"); endif;
  $path = explode("/", $_POST['urlInput']);
  $fileName = $path[sizeof($path) - 1];
  <?php if (file_exists($fileName)): ?>
  This file already <a href="<?=$fileName?>" title="Download file from this server">downloaded</a>.
  <?php elseif (!copy($_POST['urlInput'], $fileName)): ?>
  Download failed. Make sure that the URL is correct.
  <?php else: ?>
  Download completed. You have the option to <a href="<?=$fileName?>" title="Download from this server">download this downloaded file</a> or <a href="<?=$_POST['urlInput']?>" title="Download from the original server">download the original file here</a>.
  <?php endif; ?>
 <?php endif; ?>

Note that I’m just staring to learn HTML5, so I can’t guarantee the above syntax is correct.


If you have any questions regarding this script, leave a comment below. And please don’t spam my server when testing on the test page, If you want to test it on your localhost, you can download the source code here.

A Very Nice PHP Array Technique


You properly already knew the following code:

$strings = array();
$strings[] = "apple";

This will contain an array of strings:

array(1=>"apple", 2=>"bamboo", 3=>"cat");

However, this is not very useful for multi-dimensional arrays where each array in a parent array contains the same keys and different values like the database array. This is where associative arrays come into play. The code below uses the same technique as above without using the array_push function.

Source Code

foreach ($strings as $row) {
 foreach ($row as $col=>$val) {
  $data[$col] = $val;


As you can see from the code, each array in the $strings array is copied into a new $data array. I can then use this newly copied array just after the end of second foreach loop to do something. For example, insert it into another database to change the database driver (MySQL to SQLite, for example).

Please share it in the comments below if you have any other uses for this technique.

Get File Name without Extension using pathinfo() PHP function

Back Story

I recently have a need to import a list of images into the database for easier management. Because they are all PNGs and JPGs, I was trying to find a way to separate each image to file name and extension. I could use two explode() functions to take out PNG and JPG extensions. However, the file name could be thief.jpgTopng.png which use these functions will convert it to thiefTopng.This type of issue is very common at least to me. Thanks to one of the comments on this page, I discovered an useful PHP function for working with file names called pathinfo().

The Code

The usage of pathinfo() is very easy compare to explode():

exec("ls {$path}", $images);
foreach ($images as $image) {
 $file = pathinfo($image); // get the path info
 $fileName  = $file['filename']; // get the file name

As you can see, I use exec() function to execute ls command to list all of the files inside the specified directory.

My First Regular Expression Statement


Sorry for not posting any updates for the past week. I have been very busy with the schoolwork lately. For this post, I will discuss about the first basic regular expression statement that I wrote.

During my quest searching for more AJAX tutorial using jQuery, I found the jQuery history plugin. It enables the back button and manipulate browser history for AJAX applications. What I loved about this plugin is that the page with a hash sign at the end of the URL will automatically go to the page specified after the hash sign. For example, the URL http://localhost/index.php#products normally would ignoring the hash sign and go to the home page instead of products page. With history, this URL will go to the products page directly once it is entered into the address bar.

On the demo page of history plugin, I noticed a regular expression embedded in the code. I didn’t care about the expression very much at first because I thought I didn’t need it. But after experimenting with it, I came up with this jQuery code:

$(document).ready(function() {

 function ajax404(page) {
   $("#content").load(page + ".php");
   $("#content").ajaxError(function(e, xhr) {
     if (xhr.status == 404) {
       page = page.replace(/^.*//, "");
       $("#content").html("Page " + page + " not found.");

 $.history.init(function(url) {
   if (url == "") {
   else {

 $("#products a").hover(function() {
   $("#products ul").css("visibility", "visible");
  }, function() {
   $("#products ul").css("visibility", "hidden");

 $("#menu a").click(function() {
   var menuLink = $(this).context.href;
   menuLink = menuLink.replace(/^.*#/, "");

The regular expression in the last click event is the same as the one in the history demo page. According to regular-expressions.info, it means to remove all the characters before the hash sign along with the hash sign. For example,

(Note that the following examples are based on this URL)

After the regular expression used with replace function, the new value will be


The ^ character in the expression means to start with. The .* characters means any character. In the above code, ^.*# means to start with any character until the hash sign.

In the function ajax404() of the above code, I used the regular expression ^.*/ to get rid of all the characters before the backslash (/) sign along with the backslash sign. This produced the following result:


As the function name implies, I used this expression to display the page name when the file is not found. The above expression would produce the following error message:

Page juice not found

instead of

Page products/juice not found

if not used with the expression, which is not a good error message.

As with PHP and C, the forward slash (\) represents the escape character. In the code above, the normal usage of backslash (/) character is the same as the use of quotation marks in PHP. If used with escape character, it would output a normal backslash character. For example,


would produce


To learn more about regular expression, visit regular-expressions.info. And if you have any tips on how to work with regular expression, please share them in the comment below.

By the way, I will continue to post C programming tutorials later today.

C sizeof Operator

The sizeof operator is used to determine the memory size of a variable or a type in bytes. Here are some examples:

size = sizeof array; // determine the size of an array
size = sizeof array[i]; // determine the size of i th element of the array
size = sizeof(float); //determine the total size of the float variable type in a program

As you can see, when used with variable types, the sizeof operator must use parentheses around the type name.

Below is the sample code for this operator:

 * sizeof.c
 * Program to demonstrate the sizeof operator
 * by Mark Virtue, 2001.

#include <stdio.h>

main() {
 int x;
 short arr[20];
 double y;
 char string[51];

 printf("The size of x (an integer) is %lu bytesn", sizeof x);
 printf("The size of arr (an array of 20 shorts) is %lu bytesn", sizeof arr);
 printf("The size of one element of arr (one short) is %lu bytesn", sizeof arr[0]);
 printf("The size of y (a double) is %lu bytesn", sizeof y);
 printf("The size of string (an array of 51 char) is %lu bytesn", sizeof string);
 printf("The size o one element of string (one char) is %lu bytesn", sizeof string[0]);
 printf("The size of a long is %lu bytesn", sizeof(long));


Note that I made a little change to the above code. It originally has %d in the printf statements instead of %lu. Since the gcc compiler interprets the output of sizeof operator as a long unsigned int, I changed to %lu as long unsigned. Interestingly, %li (long integer) also works.

Here is the sample code that shows the usage of this operator:

 * sizeof2.c
 * Program to demonstrate the use of the sizeof operator
 * by Mark Virtue, 2001

#include <stdio.h>

main() {
 int array[] = {1, 34, 65, 778, 111, 23, 782, 75, 94, 3, 100, 22, 58, 145, 72, 99, 43, 67, 278, 98, 53};
 int total = 0;
 float average;
 int i;

 for (i = 0; i < sizeof array / sizeof array[0]; i++) {
 total += array[i];

 average = total / (sizeof array / sizeof array[0]);

 printf("The total is %dn", total);
 printf("The average is %.3fn", average);


The usage of sizeof operator in the for loop at the above code reminded me the sizeof function in PHP. Both usages are similar except C needs to divide by the size of one element in the array since C has different sizes on each variable types.

More About CA272 (Pro Website Development) Final Project

CA272 Final Project LogoSince I mentioned the CA272 final project a little in the last post, I think it’s best to talk more about this topic.

I took CA272 class in the Spring of 2009. It is known as Professional Website Development. Actually to me, this is not a professional class. Instead, it is a very basic class: it doesn’t include sever-side script languages nor JavaScript, just basic HTML4. At that time however, I didn’t know jQuery and PHP until the very end of the semester.

As you can see through the source code of the Final Project page, all of the AJAX and JavaScript functions were created by myself. Because I discovered jQuery during the last week of final project submission, I hurriedly added some animated transitions to the pages using jQuery without the deep understanding of jQuery. Therefore, the animation looks a little incomplete.

The presentation below explains the most of features on the site:

Note that because I don’t have my own website at the time, I copied all the final project files to a free hosting. Therefore, the URL at the end of the video is not valid anymore, use http://robbychen.com/ca272/final/ instead.

Remove Part of File Names using PHP

Since David’s Batch Processor was pre-installed in GIMP on Ubuntu Studio, I used it extensively in the ICAF Gallery project.

My goal for these images is to resize their thumbnail version to 10KB or smaller and retain the original size for the enlarged version.

  1. Because most of these images are in different resolution, I randomly selected the scale value in the Batch Processor to resize the images.
  2. Then I had to manually view the file size of each image to see whether or not an image has to be resized again.
  3. After the differentiation, I moved the images that need to be resized once more to a new sub-directory and started the above process one more time.
  4. I would repeat these steps again and again until all the thumbnail version of the images are under or equal to 10KB.

During the early use of the Batch Processor, I missed a very important feature – that is to save the newly processed images to a different folder. This resulted my decision to write this Batch File Name Remover script.

The source code for this script is very easy to understand. It’s just some PHP functions plus two Linux commands: ls and mv.

I always place a postfix after the file name of processed thumbnails: “-thumb”. Because of that, I need to remove this postfix whenever I repeated the above resize steps.

The ls command is used to list the file name that contains the specified characters into an array. The mv command is used to remove the specified characters from the file name using PHP explode function. I used PHP instead of native Linux Bash script because PHP is easier than Bash for me :).

The source code for this script is available here.

Below is its source code:

<!doctype html>
        <title>Batch File Name Remover</title>
            table {
                width: 80%;
                margin: 0 auto;
            table tr td {
                width: 50%;
                text-align: left;
            table tr td[colspan="2"] {
                text-align: center;
            .original, .changed {
                font-style: italic;
            .original {
            .changed {
            #error {
                font-weight: bold;
        <h1>Batch File Name Remover</h1>
            if (!isset($_POST['submitted'])) {
        <table border="0" cellpadding="0" cellspacing="0">
        <form action="" method="post">
            <input type="hidden" name="submitted" />
                <td><label for="location">Folder Location: </label></td>
                <td><input type="text" id="location" name="location" size="100" value="/home/" /></td>
                <td><label for="remove">Characters to remove: </label></td>
                <td><input type="text" name="remove" id="remove" size="100" value="-" /></td>
                <td colspan="2">
                    <input type="submit" value="Remove" />
                    <input type="reset" value="Restore default value" />
            else {
                $location = $_POST['location'];
                $remove = $_POST['remove'];
                $fileList = exec("ls '{$location}'", $files);
                $notContain = 0;    // Initialize the number of file names that doesn't contain the specified characters

                for ($i = 0; $i < sizeof($files); $i++):
                    if (strstr($files[$i], $remove)):
                        $charsRemain = explode($remove, $files[$i]);
                        exec("mv '{$location}/{$files[$i]}' '{$location}/{$charsRemain[0]}{$charsRemain[1]}'");
                        echo "<span class='original'>{$files[$i]}</span> renamed to <span class='changed'>{$charsRemain[0]}{$charsRemain[1]}</span><br /><br />";
                echo "<br />{$notContain} file name(s) do(es)n't contain the character(s) \"{$remove}\".";

And here is the code in action:

Video coming soon …

Changing Back to the Original Schedule and First Video Post (Updated)

Update (12/08/2010): For some of you having trouble to run the PHP script, I posted a tutorial on how to install web server with PHP to help you who are non web developers to run the PHP scripts I wrote. Take a look here and leave a comment if you have any questions.

Update (08/25/2010): The video quality has been improved thanks to OpenShot. Note that to watch the original HD quality, you must switch to 720p or 1080p. I also fixed the PHP script to exclude the XML file inside the background.xml file so that the slideshow can run smoothly without an empty image.

After weeks of consideration, I finally decided to change back to my original post schedule of one post per day. Two posts each day simply doesn’t work for me.

I also plan to make a video version of the post along with each post. Here is my first video showing how to create a wallpaper slideshow in Ubuntu, one of the popular posts I wrote back to March of this year:

The steps in the video are different from the post. I recorded this video this afternoon. Just before that, I wrote a PHP script that can generate background.xml file for me.  You can download the PHP script here:

To use this script, you must first change the permission of the folder where the images are to 777. You may change it back to original permission after that for security reason.

If you have any problem running this script, please leave a comment below.