How to integrate Recurly Subscription Billing with CakePHP


Integrating Recurly Subscription Billing with CakePHP is very simple.

Download Recurly PHP Client from the GitHub project site or download as a zip file.

Step 1:Unzip files to /app/Vendors folder

Step 2: On top of the controller, add import Vendor code. Example :

App::import('Vendor', 'Recurly',  array('file' => 'recurly-client'. DS . 'lib'.  DS  . 'recurly.php'));

Step 3: Get API Key and Private Key from Recurly site.

Step 4: Use code in any method will work

// Required for the API
Recurly_Client::$apiKey = 'Your api key';
// Optional for Recurly.js:
Recurly_js::$privateKey = 'your private key';
$account = new Recurly_Account();
$account->account_code = 'account_code';
$account->email = '';
$account->first_name = 'Verena';
$account->last_name = 'Example';

$account->billing_info = new Recurly_BillingInfo();
$account->billing_info->first_name = $account->first_name;
$account->billing_info->last_name = $account->last_name;
$account->billing_info->number = '4111-1111-1111-1111';
$account->billing_info->verification_value = '123';
$account->billing_info->month = 11;
$account->billing_info->year = 2015;
$account->billing_info->ip_address = $_SERVER['REMOTE_ADDR'];


for more details of Recurly PHP Client API functions visit this link PHP Client Library



Remove index.php from CodeIgnitor URL



While we use codeignitor in local server, sometime the .htaccess provided by codeignitor guide wont help. Now I found a good htaccess file which worked on my xampp successfully. Here is the htaccess file.

Options +FollowSymlinks
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt|js|css)

RewriteCond %{REQUEST_URI} (index\.php|webroot/|images/|css/|js/|robots\.txt|favicon\.ico)
RewriteRule ^(images|css|files|js)/(.*)$ webroot/$1/$2 [L]
RewriteRule ^(favicon\.ico)$ webroot/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Please comment if it really helped you.
Link reference :


Place holder plugin with jQuery


Hi Friends,

Its very helpful for a web developer to make a default text in a textbox/text area while development,. And in modern browsers its started supporting tag named “placeholder”.

Hover, Its important how we implement and if its using a jQuery, We will be running an easiest method.

Recently, i have found a kool plugin with jQuery for placeholder.

Please check this and use 😀


Find links in text and replace to href with PHP


Here is the code to find the link in text and replace link as href,

function addlinks($text = ""){
 // The Regular Expression filter
 $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
 // Check if there is a url in the text
 if(preg_match($reg_exUrl, $text, $url)) {
 // make the urls hyper links
 return  preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $text);
 } else {
 // if no urls in the text just return the text
 return $text;


Text : This is google website

Output : This is google website

Please comment with jQuery or javascript method to do the same.

Thanks in advance


Things to be noted while applying jobs for freelance websites


Lets take Elance as an example,

About Elance Profile

  1. You must give correct imformation in profile
  2. You must need to add your photo
  3. Add more portfolios. Create portfolio like all web dev, flash works, design works etc for a designer profile, min 20 numbers
  4. Overview is must. Mention about your experience ans specialization in minimum words.  Focus to the area of interest.
  5. Everything must be completed in Elance profile. You can check the profile completion. It must be minimum 80% completed. Try to pass the tests available so that will increase your confidence on applying a job.
  6. Correct all spelling mistakes in profile.
  7. On the title, fill with your areas of experience. for Eg: “CakePHP, jQuery | Web & Mobile | PHP, AJAX, HTML, CSS, SEO – Freelance Programmer / Developer”
  8. Your profile must be complete and accurate.

About applying jobs

  1. Read job description carefully.
  2. Apply for job post with proper questions asked to the client.
  3. Just think, You have hired by the client and reply.

For example suppose job description is

“Need a website design with shopping cart…………”

Your application must be like

I am an experienced Web designer. I have done around 20 shopping carts.
Here is 3 links to my latest works on shopping cart,


I have few questions because i feels the job description is incomplete. Please let me know,

  1. What kind of shoping cart you need?
  2. Do you have any color specification?
  3. Can you give me some ideas about how the design should be?

I can create a basic design in less than 20 hours. Please reply this questions so as i can give you a time estimate so that will help you to track your budget.

I am new to Elance. But i have got more than 10 years experience and now looking for building a profile on Elance. Please check my profile and portfolio in Elance so that you will get more idea about me.

Thanks and all the best
Your name

Rates for project.

For the first 4-6 works, just dont think about earning. just work for creating profile. Means you may need to work of 100$ project for $20. just apply for small fixed rate works in Elance. This will help to manage your loss. And you will get one feedback for every work. So apply with min hourly rates. lets say between $3-$5. this will give clients to choose you because if you were not successfull they will have a less loss. Lets work for first 5-6 works like the same rate. then slowly increase the rate from $4 to $5. work for 3-4 projects, then…. so on.

At once you have enough hours billed and have enough feedback for every areas you specilized fix a rate and plan your career growth.


Thanks and all the best.


cakePHP : How to skip Associations on find


Hi Friends,

I am back again. Now there are 10000 cases where we need to get the results from a table with specific set of fields. Like we need to get

$this->find("all", array("fields" => "User.firstname, User.lastname, User.avatar","order" => "User.last_login DESC", "limit" => $cnt));

Now if the parent table be User and it have so many associations then this find will join all the other sets of fields in other Associated tables.
To avoid this use the following
(I am writing code for model. If controller specify the model also. eg: $this->User->recursive = -1 etc)

function active_users($cnt = 9){
    	$this->recursive = -1;
    	return $this->find("all", array("fields" => "User.firstname, User.lastname, User.avatar","order" => "User.last_login DESC", "limit" => $cnt));

Facebook Connect Plugin for cakePHP



Here is an excellent plugin for cakephp. Facebook operations can be easily handled through this. You can integrate to Auth component also.

check it out : Facebook Plugin for Cakephp



Google Map for CakePHP 1.3 +


Hi Friends,

Here is another link i found for google map. Google Map Helper . You can copy this code for good map for your views.

For Cake 1.3 +

copy and paste this file in /app/views/helper/google_map.php

< ?php
 * CakeMap -- a google maps integrated application built on CakePHP framework.
 * Based on initial versione from Garrett J. Woodworth :
 * Rewritten by  :
 * @author
 * @version     0.2
 * @license     OPPL
 * Modified by     Mahmoud Lababidi <>
 * Date        Dec 16, 2006
 * Rewritten by small software utilities <info>
 * Date        May, 2010
class GoogleMapHelper extends Helper {
    var $errors = array();
    var $key = "your key here, not needed for v3";
    var $url ="";
    function map($default, $style = 'width: 400px; height: 400px' )
        //if (empty($default)){return "error: You have not specified an address to map"; exit();}
        $out = "<div id=\"map\"";
        $out .= isset($style) ? "style=\"".$style."\"" : null;
        $out .= " ></div>";
        $out .= "
        <script type=\"text/javascript\">
        //< ![CDATA[
     var directionDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;
    var iconimage = \"\";
         var iconshadow = \"\";
         var myOptions = {
            zoom: ".$default['zoom'].",
            center: new google.maps.LatLng(".$default['lat'].", ".$default['long']."),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
        streetViewControl: true
      var map = new google.maps.Map(document.getElementById(\"map\"), myOptions);
      function cleardirs()
          div = document.getElementById('".(isset($default['directions_div'])?$default['directions_div']:'directions_div')."');
              div.innerHTML = \"\";
                $out .= "
                  directionsDisplay = new google.maps.DirectionsRenderer();
              function calcRoute(fromid,tolat,tolon) {
                from = document.getElementById(fromid).value;
              var start = from;
              var end = new google.maps.LatLng(tolat,tolon);
              var request = {
                travelMode: google.maps.DirectionsTravelMode.DRIVING
              directionsService.route(request, function(result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
        $out .="
        return $out;
    function addMarkers(&$data, $icon=null)
        $out = "
            <script type=\"text/javascript\">
            //< ![CDATA[
                $i = 0;
                foreach($data as $n=>$m){
                    $keys = array_keys($m);
                    $point = $m[$keys[0]];
                    if(!preg_match('/[^0-9\\.\\-]+/',$point['longitude']) &&
                        && !preg_match('/[^0-9\\.\\-]+/',$point['latitude']) &&
                        $out .= "
                            var point".$i." = new google.maps.LatLng(".$point['latitude'].",".$point['longitude'].");
                            var marker".$i." = new google.maps.Marker({
                                  position: point".$i.",
                      map: map,
                      shadow: iconshadow,
                    icon: iconimage,
                           $out .= " var infowindow$i = new google.maps.InfoWindow({
                          content: \"$point[title]$point[html]\"
                      google.maps.event.addListener(marker".$i.", 'click', function() {
        $out .=    "
        return $out;
    function addClick($var, $script=null)
        $out = "
            <script type=\"text/javascript\">
            //< ![CDATA[
            google.maps.event.addListener(map, 'click', ".$var.", true);
        return $out;
    function addMarkerOnClick($innerHtml = null)
        $mapClick = '
            var mapClick = function (event) {
                var marker = new google.maps.Marker({
                icon: iconimage,
                var infowindow = new google.maps.InfoWindow({
            content: \"'.$innerHtml.'\"
        google.maps.event.addListener(marker, \'click\', function() {
        return $this->addClick('mapClick', $mapClick);
    function moveMarkerOnClick($lngctl, $latctl, $innerHtml = null)
        $mapClick = '
            var mapClick = function (event) {
                lngctl = document.getElementById(\''.$lngctl.'\');
                latctl = document.getElementById(\''.$latctl.'\');
                 lngctl.value = event.latLng.lng();
                 latctl.value =;
        return $this->addClick('mapClick', $mapClick);

And add in controller

var $helpers = array('GoogleMap');

Use in Views

 < ?php      
 		$default = array('type'=>'0','zoom'=>13,'lat'=>'42.5846353751749','long'=>'11.5191650390625');
        $points = array();
        $points[0]['Point'] = array('longitude' =>$default['long'],'latitude' =>$default['lat']);
        $key = $this->GoogleMap->key;
        echo $javascript->link($this->GoogleMap->url);
        echo $this->GoogleMap->map($default,'width: 600px; height: 400px');
        echo $this->GoogleMap->addMarkers($points);
        echo $this->GoogleMap->moveMarkerOnClick('StructureLongitudine','StructureLatitudine');

All credit of this helper goes to GoogleMap V3 cakePHP Helper

And i am trying to find a google database for IP to location(returns lat and lang). Will let you know soon.



13 links for cakephp beginners



Here i found an important link for cakePHP beginners to add 13 things to your cakePHP app.

Dont forget to visit 13 things for cakePHP

Hope you enjoyed?


Integrating SWFUpload with CakePHP (all versions)



I am very impressed with SWFUpload and will make use of this in future developments. Its kool flash player can handle all things needed for a developer to handle things in client side. There are so many benefits of using this for fileuploads because everything needed for handling file uploads can be done with there flash player so as there is no need of checking through scripts. The only disadvantage is only flash supported clients can handle uploading.

As my fav is cakePHP and i uses 80% of my developments through cake, the first i i thought about integrating SWFUpload to CakePHP. For this as my first work is searched some components for easy use. I have found some. I have made some try to integrate this components and successfully wasted my 2 hours.

Later i though about why cant i directly integrate SWFUpload into the view. Since SWFUpload completely a client side script and just making an ajax call to the server, i planned to go as manual integration and got success.

As i have bad memory i think i need to update this in to blog so that it will be helpful for me in future. And may be you too…. enjoy

Integrating SWFUpload with CakePHP

  1. Download SWFUpload from
  2. Be sure you have a cakePHP in your server
  3. Unzip and place the file in this manner (You can use anywhere and only thing is you should know how to set path in views)
  4. Copy all images to app\webroot\img . See i have these images in the folder cancelbutton.gif, XPButtonUploadText_61x22.png
  5. Copy all javascript and flash files app\webroot\js\swfupload. I have the following files in mentioned folder now fileprogress.js, handlers.js, swfupload.js, swfupload.queue.js, swfupload.swf, swfupload.swfobject.js, swfuploadbutton.swf
  6. In view (You can add this in layout in ‘head’ tag. I have added in view to reduce overload printing these files on all views and i know this is not a good method).
    //This code is in view to print script files
    < ?php e($javascript->link(array(
    		)));    ?>

    Followed by

    // Script code in view enclosed with script tag
    < script>
    var swfu;
    SWFUpload.onload = function () {
    	var settings = {
    		flash_url : site_url + "js/swfupload/swfupload.swf",
    		upload_url: "< ?php echo $html->url('/images/sampleupload/'.$session->id()) ?>",
    		post_params: {
    			"PHPSESSID" : "NONE",
    			".what" : "OKAY"
    		file_size_limit : "3 MB",
    		file_types : "*.jpg",
    		file_types_description : "JPG Files",
    		file_upload_limit : 30,
    		file_queue_limit : 0,
    		custom_settings : {
    			progressTarget : "fsUploadProgress",
    			cancelButtonId : "btnCancel"
    		debug: false,
    		// Button Settings
    		button_image_url : site_url + "/img/XPButtonUploadText_61x22.png",
    		button_placeholder_id : "spanButtonPlaceholder",
    		button_width: 61,
    		button_height: 22,
    		// The event handler functions are defined in handlers.js
    		swfupload_loaded_handler : swfUploadLoaded,
    		file_queued_handler : fileQueued,
    		file_queue_error_handler : fileQueueError,
    		file_dialog_complete_handler : fileDialogComplete,
    		upload_start_handler : uploadStart,
    		upload_progress_handler : uploadProgress,
    		upload_error_handler : uploadError,
    		upload_success_handler : uploadSuccess,
    		upload_complete_handler : uploadComplete,
    		queue_complete_handler : queueComplete,	// Queue plugin event
    		// SWFObject settings
    		minimum_flash_version : "9.0.28",
    		swfupload_pre_load_handler : swfUploadPreLoad,
    		swfupload_load_failed_handler : swfUploadLoadFailed
    	swfu = new SWFUpload(settings);

    Please note. My settings may be different. So please read how the settings needed to be given for SWFUpload.onload. Just know how the paths are given. See “upload_url:” This is the path to controller method where it handles the uploads. I will add my method below/ And important is need to pass $session->id(). and in “flash_url:”, site_url is the location (eg: http://localhost/fileuploading)

  7. Now we can move to controller. There are few things to note in controller
    // Controller images before filter to handle session->id()
    function beforeFilter() { 
            if ($this->action == 'sampleupload') {

    Then the method simpleupload (I have added some components for uplaoding the file. You can use your own script for uploading)

    // controller method code for uploading
    function sampleupload(){
    		// Code for Session Cookie workaround
    				if (isset($_POST["PHPSESSID"])) {
    				} else if (isset($_GET["PHPSESSID"])) {
    			// Check post_max_size (
    				$POST_MAX_SIZE = ini_get('post_max_size');
    				$unit = strtoupper(substr($POST_MAX_SIZE, -1));
    				$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
    			// Settings
    				$save_path = realpath('../../app/webroot/uploads/listings') . "/";;				// The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
    				$upload_name = "Filedata";
    				$max_file_size_in_bytes = 2147483647;				// 2GB in bytes
    				$extension_whitelist = array("jpg", "gif", "png");	// Allowed file extensions
    				$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';				// Characters allowed in the file name (in a Regular Expression format)
    			// Other variables	
    				$MAX_FILENAME_LENGTH = 260;
    				$file_name = "";
    				$file_extension = "";
    				$uploadErrors = array(
    			        0=>"There is no error, the file uploaded with success",
    			        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
    			        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
    			        3=>"The uploaded file was only partially uploaded",
    			        4=>"No file was uploaded",
    			        6=>"Missing a temporary folder"
    			// Validate the upload
    				if (!isset($_FILES[$upload_name])) {
    					$this->HandleError("No upload found in \$_FILES for " . $upload_name);
    				} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
    				} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
    					$this->HandleError("Upload failed is_uploaded_file test.");
    				} else if (!isset($_FILES[$upload_name]['name'])) {
    					$this->HandleError("File has no name.");
    			// Validate the file size (Warning: the largest files supported by this code is 2GB)
    				$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
    				if (!$file_size || $file_size > $max_file_size_in_bytes) {
    					$this->HandleError("File exceeds the maximum allowed size");
    				if ($file_size < = 0) {
    					$this->HandleError("File size outside allowed lower bound");
    			// Validate file name (for our purposes we'll just remove invalid characters)
    				$file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
    				if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
    					$this->HandleError("Invalid file name");
    			// Validate that we won't over-write an existing file
    				if (file_exists($save_path . $file_name)) {
    					$this->HandleError("File with this name already exists");
    				// Validate file extension
    				$path_info = pathinfo($_FILES[$upload_name]['name']);
    				$file_extension = $path_info["extension"];
    				$is_valid_extension = false;
    				foreach ($extension_whitelist as $extension) {
    					if (strcasecmp($file_extension, $extension) == 0) {
    						$is_valid_extension = true;
    				if (!$is_valid_extension) {
    					$this->HandleError("Invalid file extension");
    				/* Starts uploading functions */
    				$listing_id = $_POST['listing_id'];
    				/* Ends uploading functions */
    				$listing = $this->Listing->read(null , $listing_id);
    				$this->data['Image'] = $_FILES[$upload_name];
    				$file = $_FILES[$upload_name];
    		    	if (!empty($listing)) {
    		    		$mls_number = $listing['Listing']['mls_number'];
    		    		$listing_id = $listing['Listing']['id'];
    		    		$this->HandleError(__('Invalid listing.', true));
    				// Begin : uploading images....
    					$errors = array();
    						// grab the file
    						$file_name = date('Ymdhis') . ".jpg";
    						// This is a component function use your upload code here
    						$uploaded = $this->Upload->upload($file, $destination_path, $file_name);
    	function HandleError($message) {
    		echo $message;
  8. Done. 🙂

Please note. Just take the concepts. There may be errors in controller. Use it with your idea


Go to Top