Infinite redirect loop when using CakePHP

You will sometimes run into this issue when using CakePHP, I did  a few times, and randomly or so it seemed and the reason is in my case, and I want to bet in most cases, is that you are using the Auth Component, and added a new action to your controller, and simply forgot to add it to the allowed functions in the Auth Component. Make sure you add the action name that you want to be made available to anyone to the Auth.allow() call in your beforeFilter() function body in the controller where the action is defined.

Advertisements

Speed up your CakePHP application by using Memcached

In anticipation of heavier traffic and also just for performance reasons, I’ve started looking into ways of caching data for Nouchi.Mobi. Since this is a CakePHP application, I naturally looked into PHP cache based solutions and you’d be hard pressed not be recommended Memcached(Used by Facebook, Twitter, Youtube, Flicker amongst others). Why would you want database caching? If you’re using a framework to build your application or just from building any type of decently functional custom coded dynamic application nowadays, chances are you will make numerous calls to retrieve the data you want to display (the average Drupal site issues 300/400 queries!). Some pages do actually make more SQL queries than others and caching the result of these queries would give your application a significant performance boost. Memcached is a high performance in-memory data caching system that works by storing data as key-value pairs, meaning :

  • Store the value V with the key K
  • Retrieve the Value V identified by the key K

In the context of CakePHP, follow these instructions to get Memcached up and running in your local development environment. The trickiest steps in this set up will probably enabling the memcache support in your PHP configuration (getting and enabling the php_memcache.so extension in Linux). Keep in mind that for your production environment, unless you have your own Virtual Private Server, you’d be hard pressed to find any  host that will let you run Memcached in a shared hosting environment, but this is a scaling issue, and a problem you want to have, meaning your application is getting popular. Next you’d need to enable it in CakePHP in your app/core.php

Cache::config('default', array('engine' => 'Memcache'));

Once it’s up and running what you have to remember about using caching is that it is not magic. You have to code with caching in mind, and caching works best for queries that return the same data or that don’t change often. Teknoid has a good article on explaining what I mean by that with an example. Hope that’s enough to get you started and you can also take a look at this excellent Nettuts tutorial on the matter.

Set up JSON action output in CakePHP 1.3

Working  on setting up the Rest Plugin for CakePHP helped me realize that i wanted to set up JSON output for some of my actions. This way, if you request for example “www.yourapp.com/app/post/view/1.json” in the url, you will be returned the JSON post data. This excellent tutorial here will help you achieve it. The steps are simple:

  • Enabling JSON parsing in your app/config/routes.php: Router::parseExtensions('json');
  • Enable the RequestHandler component in your app_controller.php:
    //Only enabling json response parsing for url requested with the .json extension
    if ($this->RequestHandler->ext === 'json')
    {
        $this->RequestHandler->setContent('json', 'application/json');
    //Prevent debug output that'll corrupt your json data
        Configure::write('debug', 0);
    }
  • In your app/layouts folder, create a json folder with the default.ctp (so the file path should be app/layout/json/default.ctp) file with the following content:
    < ?php
    header("Pragma: no-cache");
    header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
    header('Content-Type: application/json');
    echo $content_for_layout;
    ?>
  • Now for all controller actions that you want the json output enabled for, set the variable  in the viewVars for examples in my PostsController view action, i return the post data I want to view as:
    $this->set('post', $this->Post->read(null, $id));
  • Now second, we need to create the json view for this data. I created a "json" folder in my "views/posts" folder and created a "view.ctp" file (views/posts/json/view.ctp) with this content:
    <?php
        echo $this->Js->object($post); 
    //Some old posts you will find have this as echo $javascript->object($aPosts); This was done with the old Javascript helper, doing some //might give you trouble as it did for me. use the new JS helper syntax as of 1.3
    ?>
  • And that’s it you are home free, json output a go go for your action. Access http://www.yourapp.com/view/1 and you will get your regular html output, access http://www.yourapp.com/view/1.json and you will be returned your Json output, to view the Json file in Firefox install the JsonView extension.

Now you will notice that for all json views, we will be re-using the same code, basically just changing the name of the variable to output. This call for a JsonView, and I will post aboutit once i get it implemented correctly.

Programming: “It pays the bills” vs “It satisfies me”

At this point in my career I find myself increasingly frustrated with my day to day work. You see, living in the DMV area (DC-MD-VA), a lot of the jobs available are in government contracting and as many will tell you, those are well paying jobs with a certain level of job security added. For a while I did it and enjoyed it but deep inside i knew that this was not really what i want to be doing for the rest of my life. With things being the way they are, even when trying to switch jobs, it has been easier to do so going from one government contract to the next, with my attempted moves to the private sector being unsuccessful primarily because first my experience is mostly related to government projects, and second, the pay range was below was I was willing to go for. It is not greed on my part, but being married with kids means ” I got mouths to feed man! “(<= in Dave Chappelle’s voice) and obligations I have to tend to and can’t ignore.

This has limited the number of opportunities I considered and from a passing thought in the back of my mind it has grown into a daily contemplation of my future in this business. Over the years, I have gravitated toward doing and enjoying more of the front end work, and it’s a coincidence that the field in itself, especially when it comes to enterprise J2EE development, is becoming a full position in itself as opposed to being lumped in the “Java Developer” category just a couple of years ago (It still is, i just got another inquiry from a recruiter looking for a Java Developer where most of the work is front end related). My frustrations with the projects I have been on mostly stem from the technological limitations of working on government projects which sometimes involves outdated technologies,  security limitations and convoluted requirements that end up taking the fun out of the development process. From a design and functionality point of view, these applications lacked the “Wow” factor and being internal applications, even if they were, they were not of the “living portfolio” type of web applications that customers companies want to see when interviewing a developer.

I’ve realized that the type of work I want to be involved with has to be challenging, innovative, and current to what’s getting done today. It has to be a good mix of creative and technological skills that keeps me on my toes and gets the “Cool!” approval from family and friends when presented with it or when explained to, instead of a blank stare and a “Uh?”.

To work towards achieving that goal, I’ve started working on projects of my own, ideas i have been nurturing for a while with the hope of turning it into a startup if it gains traction. It’s a combination web/mobile app developed with CakePHP and Sencha Touch that has helped me turn some of the concepts and techniques I have been reading about and itching to try into actual code and challenged my thinking and skills in a way I had never experienced before. It has forced me to step out of my comfort zone and try new skills I didn’t practice before and it is a continually rewarding experience. I’ve also started working on side projects for friends of mine in order to expand my skill set and keep it sharp and relevant.

Through discussions with others (friends and colleagues) I’ve found out I was not the only suffering from this programmer’s “existential malaise” but some choose to go with the status quo while others like me find other projects to get involved with on the side that keeps them interested and challenged.Some have started their own startups, non-profits and organizations, building on the skills they have and pushing into new directions. Me, I figured I could spend my free time better than racking up “The Feared” accolades on Modern Warfare 2 or shouting angrily at my TV because my players messed up again in Fifa 11.

All this in waiting for that project that will bring the good mix of creativity, innovation, coolness and most of all, “will keep the kids fed, man!”(<= in Dave Chappelle’s voice).

Download phpssh2.dll extension for PHP 5.3 compatible with WAMP Server 2.1

A project that I am working on now requires shell access basically to dynamically create cron jobs. This took me a minute and will be the topic of an upcoming post but for now, in my local WAMP based dev environment, I need SSH2 set up and good to go. I quickly found out that the version downloaded from the official PHP site needs to be compiled in a DLL.  No time and not set up with MS Visual Studio for that. I was able to procure a version that worked with my local set up of WAMPServer V2.1 on Windows XP:

You can download it here.

Hope it helps!

WAMP Apache Error: “You don’t have permission to access / on this server”

Installing and setting up WAMP is a breeze on Windows, but you are bound to run into issues. I’ve encountered a peculiar one this weekend while trying to run a PHP application I am working on. I had XAMPP already running on my machine, and to avoid having both WAMP and XAMPP lauching by side, i decided to switch all my projects to running on the Apache server provided by WAMP. To do so, i needed to set up a Virtual Host to point to the directory previously holding the projects i had running under XAMPP. I modified my httpd.conf this way:


#Uncommented the line loading the Virtual Host configuration file

Include conf/extra/httpd-vhosts.conf

Then in the httpd-vhosts.conf file.

<pre>#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#

<Directory "C:\Dev\Workspace">
  Order Deny,Allow
  Allow from all
  AllowOverride all
</Directory>

<VirtualHost *:80>
    ServerAdmin aboukone@aboukone.com
    DocumentRoot "C:\Dev\Workspace"
    ServerName localhost.dev
</VirtualHost></pre>

With the configuration set up that way, I lost all access to my localhost when starting WAMP. I could access all the projects in the C:\Dev\Workspace folder, but not the ones in the C:\wamp\www standard folder. I could still access phpmyadmin web interface but nothing in the www folder, even a simple html file. Trying to access for example the WAMP index page (www/index.php) would get me:

<h1>Forbidden</h1>
You don't have permission to access / on this server.

I tried messing with the settings in the httpd.conf for the DocumentRoot at C:\www\wamp folder to Allow All, minding that this is unsafe on a live web server :

<pre><Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow all
</Directory></pre>

but got a:


The requested URL / was not found on this server.

error from Apache. A clue about going on to fix this came from commenting out the VirtualHost configuration line again in httpd.conf. That done, I was back in business with my www folder being visible again as well as all the projects within. It seemed that the VirtualHosts configurations were overriding the default Server configuration in httpd.conf. I then added the following code in httpd-vhosts.conf and both my C:\Dev\Workspace and C:\wamp\www folder were again “visible” and I was able to access projects in both locations:

<pre><Directory "C:\Dev\Workspace">
  Order Deny,Allow
  Allow from all
  AllowOverride all
</Directory>

<VirtualHost *:80>
    ServerAdmin aboukone@aboukone.com
    DocumentRoot "C:\Dev\Workspace"
    ServerName localhost.dev
</VirtualHost>
#Added this configuration for the WAMP www folder
<VirtualHost *:80>
    ServerAdmin aboukone@aboukone.com
    DocumentRoot "C:\wamp\www"
    ServerName localhost
</VirtualHost></pre>

Hope it helps!

Using the CakePHP 1.2 Email component

I was following the documentation at

http://book.cakephp.org/view/269/Sending-a-basic-message

about sending an email with CakePHP using the Email component, used the sample code they provided but could not get my application to send email. A little bit of googling helped me figure out what was going on. I have CakePHP setup within my XAMPP htdocs directory and my MercuryMail server was not started. You need to have a mail server setup to be able to send email and there are a few more steps you need to do as well to get up and running. It’s beautifully summarized here:

http://www.zoe.vc/2008/mercury-mail-transport-system-fur-externe-mail-konfigurieren/

Once your Mercury is properly setup, you are good to send emails from CakePHP!!!

Lesson learned i guess!

Hope It Helps!