Cool Coder
What i find myself?
What i find myself?
Feb 22nd
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 = 'verena@example.com'; $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']; $account->create();
for more details of Recurly PHP Client API functions visit this link PHP Client Library
Thanks.
Amjith
Nov 11th
Hi,
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 : http://codeigniter.com/forums/viewthread/201644/
Thanks
Jun 12th
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.
http://code.google.com/p/jquery-watermark/

Please check this and use
Thanks
Apr 16th
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;
}
}
Example
Text : This is google website http://google.com
Output : This is google website http://google.com
Please comment with jQuery or javascript method to do the same.
Thanks in advance
Amjith
Jan 11th
Lets take Elance as an example,
About Elance Profile
About applying jobs
For example suppose job description is
“Need a website design with shopping cart…………”
Your application must be like
“Sir,
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,
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.
Amjith
Aug 17th
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)); }
Jul 30th
Hi,
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
Thanks
Amjith
Jul 23rd
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 : gwoo@rd11.com * Rewritten by : http://www.small-software-utilities.com * * @author info@small-software-utilities.com * @version 0.2 * @license OPPL * * Modified by Mahmoud Lababidi <lababidi@bearsontherun.com> * Date Dec 16, 2006 * Rewritten by small software utilities <info @small-software-utilities.com> * Date May, 2010 */ class GoogleMapHelper extends Helper { var $errors = array(); var $key = "your key here, not needed for v3"; var $url ="http://maps.google.com/maps/api/js?sensor=false"; 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 = \"http://labs.google.com/ridefinder/images/mm_20_red.png\"; var iconshadow = \"http://labs.google.com/ridefinder/images/mm_20_shadow.png\"; 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() { if(directionsDisplay) directionsDisplay.setMap(null); div = document.getElementById('".(isset($default['directions_div'])?$default['directions_div']:'directions_div')."'); if(div) div.innerHTML = \"\"; } "; if(isset($default['directions_div'])) { $out .= " directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); directionsDisplay.setPanel(document.getElementById('".$default['directions_div']."')); function calcRoute(fromid,tolat,tolon) { directionsDisplay.setMap(map); from = document.getElementById(fromid).value; var start = from; var end = new google.maps.LatLng(tolat,tolon); var request = { origin:start, destination:end, travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionsService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(result); } }); } "; } $out .=" //]]> </script>"; return $out; } function addMarkers(&$data, $icon=null) { $out = " <script type=\"text/javascript\"> //< ![CDATA[ "; if(is_array($data)) { $i = 0; foreach($data as $n=>$m){ $keys = array_keys($m); $point = $m[$keys[0]]; if(!preg_match('/[^0-9\\.\\-]+/',$point['longitude']) && preg_match('/^[-]?(?:180|(?:1[0-7]\\d)|(?:\\d?\\d))[.]{1,1}[0-9]{0,15}/',$point['longitude']) && !preg_match('/[^0-9\\.\\-]+/',$point['latitude']) && preg_match('/^[-]?(?:180|(?:1[0-7]\\d)|(?:\\d?\\d))[.]{1,1}[0-9]{0,15}/',$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, title:\"".(isset($point['title'])?$point['title']:'')."\", shadow: iconshadow, icon: iconimage, });"; if(isset($point['title'])&&isset($point['html'])) { $out .= " var infowindow$i = new google.maps.InfoWindow({ content: \"$point[title]$point[html]\" }); google.maps.event.addListener(marker".$i.", 'click', function() { infowindow$i.open(map,marker".$i."); });"; } $data[$n][$keys[0]]['js']="marker$i.openInfoWindowHtml(marker$i.html);"; $i++; } } } $out .= " //]]> </script>"; return $out; } function addClick($var, $script=null) { $out = " <script type=\"text/javascript\"> //< ![CDATA[ $script google.maps.event.addListener(map, 'click', ".$var.", true); //]]> </script>"; return $out; } function addMarkerOnClick($innerHtml = null) { $mapClick = ' var mapClick = function (event) { var marker = new google.maps.Marker({ position:event.latLng, icon: iconimage, map:map }); var infowindow = new google.maps.InfoWindow({ content: \"'.$innerHtml.'\" }); google.maps.event.addListener(marker, \'click\', function() { infowindow.open(map,marker); }); } '; return $this->addClick('mapClick', $mapClick); } function moveMarkerOnClick($lngctl, $latctl, $innerHtml = null) { $mapClick = ' var mapClick = function (event) { marker0.setPosition(event.latLng); lngctl = document.getElementById(\''.$lngctl.'\'); latctl = document.getElementById(\''.$latctl.'\'); if(lngctl) lngctl.value = event.latLng.lng(); if(latctl) latctl.value = event.latLng.lat(); } '; return $this->addClick('mapClick', $mapClick); } } ?> </info>
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.
Thanks
amjith
Jul 23rd
Hey,
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?
Thanks.
amjith
Jul 1st
Hi,
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
//This code is in view to print script files < ?php e($javascript->link(array( 'swfupload/swfupload', 'swfupload/swfupload.swfobject', 'swfupload/swfupload.queue', 'swfupload/fileprogress', 'swfupload/handlers', ))); ?>
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)
// Controller images before filter to handle session->id() function beforeFilter() { if ($this->action == 'sampleupload') { $this->Session->id($this->params['pass'][0]); $this->Session->start(); } parent::beforeFilter(); }
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"])) { session_id($_POST["PHPSESSID"]); } else if (isset($_GET["PHPSESSID"])) { session_id($_GET["PHPSESSID"]); } // Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762) $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); exit(0); } else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) { $this->HandleError($uploadErrors[$_FILES[$upload_name]["error"]]); exit(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."); exit(0); } else if (!isset($_FILES[$upload_name]['name'])) { $this->HandleError("File has no name."); exit(0); } // 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"); exit(0); } if ($file_size < = 0) { $this->HandleError("File size outside allowed lower bound"); exit(0); } // 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"); exit(0); } // 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"); exit(0); } // 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; break; } } if (!$is_valid_extension) { $this->HandleError("Invalid file extension"); exit(0); } /* 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']; }else{ $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); exit(0); } function HandleError($message) { echo $message; }
Please note. Just take the concepts. There may be errors in controller. Use it with your idea
Amjith