Wednesday, October 28, 2009

Image Upload and Resize Component for CakePHP

image.php component file
/*
File: /app/controllers/components/image.php
*/
class ImageComponent extends Object
{
/*
* Uploads an image and its thumbnail into $folderName/big and $folderName/small respectivley.
* the generated thumnail could either have the same aspect ratio as the uploaded image, or could
* be a zoomed and cropped version.

* Directions:
* In view where you upload the image, make sure your form creation is similar to the following
* create('FurnitureSet',array('type' => 'file')); ?>
*
* In view where you upload the image, make sure that you have a file input similar to the following
* file('Image/name1'); ?>
*
* In the controller, add the component to your components array
* var $components = array("Image");
*
* In your controller action (the parameters are expained below)
* $image_path = $this->Image->upload_image_and_thumbnail($this->data,"name1",573,80,"sets",true);
* this returns the file name of the result image. You can store this file name in the database
*
* Note that your image will be stored in 2 locations:
* Image: /webroot/img/$folderName/big/$image_path
* Thumbnail: /webroot/img/$folderName/small/$image_path
*
* Finally in the view where you want to see the images
* image('sets/big/'.$furnitureSet['FurnitureSet']['image_path']);
* where "sets" is the folder name we saved our pictures in, and $furnitureSet['FurnitureSet']['image_path'] is the file name we stored in the database

* Parameters:
* $data: CakePHP data array from the form
* $datakey: key in the $data array. If you used file('Image/name1'); ?> in your view, then $datakey = name1
* $imgscale: the maximum width or height that you want your picture to be resized to
* $thumbscale: the maximum width or height that you want your thumbnail to be resized to
* $folderName: the name of the parent folder of the images. The images will be stored to /webroot/img/$folderName/big/ and /webroot/img/$folderName/small/
* $square: a boolean flag indicating whether you want square and zoom cropped thumbnails, or thumbnails with the same aspect ratio of the source image
*/
function upload_image_and_thumbnail($data, $datakey, $imgscale, $thumbscale, $folderName, $square,$controller) {
if (strlen($data[$controller][$datakey]['name'])>4){
$error = 0;
$tempuploaddir = "img/temp"; // the /temp/ directory, should delete the image after we upload
$biguploaddir = "upload/".$folderName."/big"; // the /big/ directory
$smalluploaddir = "upload/".$folderName."/small"; // the /small/ directory for thumbnails

// Make sure the required directories exist, and create them if necessary
if(!is_dir($tempuploaddir)) mkdir($tempuploaddir,true);
if(!is_dir($biguploaddir)) mkdir($biguploaddir,true);
if(!is_dir($smalluploaddir)) mkdir($smalluploaddir,true);

$filetype = $this->getFileExtension($data[$controller][$datakey]['name']);
$filetype = strtolower($filetype);

if (($filetype != "jpeg") && ($filetype != "jpg") && ($filetype != "gif") && ($filetype != "png"))
{
// verify the extension
return;
}
else
{
// Get the image size
$imgsize = GetImageSize($data[$controller][$datakey]['tmp_name']);
}

// Generate a unique name for the image (from the timestamp)
$id_unic = str_replace(".", "", strtotime ("now"));
$filename = $id_unic;

settype($filename,"string");
$filename.= ".";
$filename.=$filetype;
$tempfile = $tempuploaddir . "/$filename";
$resizedfile = $biguploaddir . "/$filename";
$croppedfile = $smalluploaddir . "/$filename";

if (is_uploaded_file($data[$controller][$datakey]['tmp_name']))
{
// Copy the image into the temporary directory
if (!copy($data[$controller][$datakey]['tmp_name'],"$tempfile"))
{
print "Error Uploading File!.";
exit();
}
else {
/*
* Generate the big version of the image with max of $imgscale in either directions
*/
$this->resize_img($tempfile, $imgscale, $resizedfile);

if($square) {
/*
* Generate the small square version of the image with scale of $thumbscale
*/
$this->crop_img($tempfile, $thumbscale, $croppedfile);
}
else {
/*
* Generate the big version of the image with max of $imgscale in either directions
*/
$this->resize_img($tempfile, $thumbscale, $croppedfile);
}

// Delete the temporary image
unlink($tempfile);
}
}

// Image uploaded, return the file name
return $filename;
}
}

/*
* Deletes the image and its associated thumbnail
* Example in controller action: $this->Image->delete_image("1210632285.jpg","sets");
*
* Parameters:
* $filename: The file name of the image
* $folderName: the name of the parent folder of the images. The images will be stored to /webroot/img/$folderName/big/ and /webroot/img/$folderName/small/
*/
function delete_image($filename,$folderName) {
unlink("upload/".$folderName."/big/".$filename);
unlink("upload/".$folderName."/small/".$filename);
}

function crop_img($imgname, $scale, $filename) {
$filetype = $this->getFileExtension($imgname);
$filetype = strtolower($filetype);

switch($filetype){
case "jpeg":
case "jpg":
$img_src = ImageCreateFromjpeg ($imgname);
break;
case "gif":
$img_src = imagecreatefromgif ($imgname);
break;
case "png":
$img_src = imagecreatefrompng ($imgname);
break;
}

$width = imagesx($img_src);
$height = imagesy($img_src);
$ratiox = $width / $height * $scale;
$ratioy = $height / $width * $scale;

//-- Calculate resampling
$newheight = ($width <= $height) ? $ratioy : $scale;
$newwidth = ($width <= $height) ? $scale : $ratiox;

//-- Calculate cropping (division by zero)
$cropx = ($newwidth - $scale != 0) ? ($newwidth - $scale) / 2 : 0;
$cropy = ($newheight - $scale != 0) ? ($newheight - $scale) / 2 : 0;

//-- Setup Resample & Crop buffers
$resampled = imagecreatetruecolor($newwidth, $newheight);
$cropped = imagecreatetruecolor($scale, $scale);

//-- Resample
imagecopyresampled($resampled, $img_src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//-- Crop
imagecopy($cropped, $resampled, 0, 0, $cropx, $cropy, $newwidth, $newheight);

// Save the cropped image
switch($filetype)
{

case "jpeg":
case "jpg":
imagejpeg($cropped,$filename,80);
break;
case "gif":
imagegif($cropped,$filename,80);
break;
case "png":
imagepng($cropped,$filename,80);
break;
}
}

function resize_img($imgname, $size, $filename) {
$filetype = $this->getFileExtension($imgname);
$filetype = strtolower($filetype);

switch($filetype) {
case "jpeg":
case "jpg":
$img_src = ImageCreateFromjpeg ($imgname);
break;
case "gif":
$img_src = imagecreatefromgif ($imgname);
break;
case "png":
$img_src = imagecreatefrompng ($imgname);
break;
}

$true_width = imagesx($img_src);
$true_height = imagesy($img_src);

if ($true_width>=$true_height)
{
$width=$size;
$height = ($width/$true_width)*$true_height;
}
else
{
$width=$size;
$height = ($width/$true_width)*$true_height;
}
$img_des = ImageCreateTrueColor($width,$height);
imagecopyresampled ($img_des, $img_src, 0, 0, 0, 0, $width, $height, $true_width, $true_height);

// Save the resized image
switch($filetype)
{
case "jpeg":
case "jpg":
imagejpeg($img_des,$filename,80);
break;
case "gif":
imagegif($img_des,$filename,80);
break;
case "png":
imagepng($img_des,$filename,80);
break;
}
}

function getFileExtension($str) {

$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
} ?>


How to use in controller?
Sample code is here:-

class UserAvatarsController extends AppController {
var $name = 'UserAvatars';
var $uses = array('UserAvatar','User'); //using modules
var $helpers = array('Html','Form','Javascript','Session');
var $paginate = array('limit' => 15); // Set records per page
var $components = array('Image'); // used Image components
function upload()
{
$this->user_session_check();
if (!empty($this->data))
{
$image_path = $this->Image->upload_image_and_thumbnail($this->data,"avatar",573,80,"avatar",true,'UserAvatar');
$this->data['UserAvatar']['avatar']=$image_path;
if ($this->UserAvatar->save($this->data))
{
$this->flash('Your avatar has been uploaded successfully',_ROOT.'avatar/upload',1);
}
}
}
}
?>
for more info :- Anurag

A solution for e-mail handling in CakePHP

The emailComponent (cake\libs\controller\components\email.php) is a way for you to using the same concepts of layouts and view ctp files to send formated messages as text, html or both. It supports sending via the built in mail functions of PHP, via smtp server or a debug mode where it writes the message out to a session flash message. It also supports file attachments.
Implements it in three easy Steps
1. Controller (STEP 1)

In your controller you need to add the component to your $components array or add a $components array to your controller like:
1. <?php
2. var $components = array('Email');
3. ?>

In this example we will set up a private method to handle sending the email messages to a user identified by an $id. In our controller (let's use the User controller in this example)

1. <?php
2. function _sendNewUserMail($id) {
3. $User = $this->User->read(null,$id);
4. $this->Email->to = $User['User']['email'];
5. $this->Email->bcc = array('anuragtrivediphp@gmail.com');
6. $this->Email->subject = 'Welcome to cakePHP email handling functionally';
7. $this->Email->replyTo = 'anuragtrivediphp @ gmail.com';
8. $this->Email->from = Anurag Blog ';
9. $this->Email->template = ‘contact'; // note no '.ctp'
10. //Send as 'html', 'text' or 'both' (default is 'text')
11. $this->Email->sendAs = 'both'; // because we like to send pretty mail
12. //Set view variables as normal
13. $this->set('User', $User);
14. //Do not pass any args to send()
15. $this->Email->send();
16. }
17. ?>

You have sent a message; you could call this from another method like
1. $this->_sendNewUserMail( $this->User->id );

2. Setting up the Layouts (Step 2)
To use both text and html mailing message you need to create layout files for them, just like in setting up your default layouts for the display of your views in a browser, you need to set up default layouts for your email messages. In the app/views/layouts/ directory you need to set up (at a minimum) the following structure
email/
html/
default.ctp
text/
default.ctp
These are the files that hold the layout templates for your default messages. Some example content is below
email/text/default.ctp
1. <?php echo $content_for_layout; ?>

email/html/default.ctp
1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2. <html>
3. <body>
4. <?php echo $content_for_layout; ?>
5. </body>
6. </html>

3. Setup an email element for the message body
(Step 3)
In the app/views/elements/email/ directory you need to set up folders for text and html unless you plan to just send one or the other. In each of these folders you need to create templates for both types of messages referring to the content that you send to the view either by using $this->set() or using the $contents parameter of the send() method. Some simple examples are shown below. For this example we will call the templates
contact.ctp
1.Dear <?php echo $User['first']. ' ' . $User['last'] ?>,

In html

<p>Dear <?php echo $User['first']. ' ' . $User['last'] ?>,< br />
   Thank you for your interest.</p>


If need any help contact anuragtrivediphp@gmail.com

Monday, October 12, 2009

Custom 404 error page with CakePHP

1. Create your error layout in app/view/layouts/ (with name error.ctp)
2. Create your 404 error view in app/view/errors/ (with name error404.ctp)
In /cake/libs/view/errors you will find all the default error views.
You can copy and paste error404.ctp in your app/view/errors directory or create a new file and customize this view as you like.
3. Set the error layout in app_controller.php
Then add this to your app_controller.php :
function _setErrorLayout() {
if ($this->name == ‘CakeError’) {
$this->layout = ‘error’;
}
}

function beforeRender () {
$this->_setErrorLayout();
}

Monday, October 5, 2009

.htaccess file upload settings

RewriteEngine on
php_value post_max_size 500M
php_value upload_max_filesize 500M
php_value max_execution_time 1000
php_value max_input_time 1000



By this .htaccess code we can upload big files.

Tuesday, September 15, 2009

1)Rewriting product.php?id=12 to product-12.html

It is a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.

RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1

2) Rewriting product.php?id=12 to product/ipod-nano/12.html

SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.

RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2

3) Redirecting non www URL to www URL

If you type yahoo.com in browser it will be redirected to www.yahoo.com. If you want to do same with your website then put the following code to .htaccess file. What is benefit of this kind of redirection?? Please check the post about SEO friendly redirect (301) redirect in php and .htaccess.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^optimaxwebsolutions\.com$
RewriteRule (.*) http://www.optimaxwebsolutions.com/$1 [R=301,L]

4) Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz

Have you checked zorpia.com.If you type http://zorpia.com/roshanbh233 in browser you can see my profile over there. If you want to do the same kind of redirection i.e http://yoursite.com/xyz to http://yoursite.com/user.php?username=xyz then you can add the following code to the .htaccess file.

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1

5) Redirecting the domain to a new subfolder of inside public_html.

Suppose the you’ve redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “test.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, www.test.com point out to the files inside “new” folder.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.test\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*) /new/$1

Thursday, September 10, 2009

CakePHP URL-based language switching (internationalization and localization)

Write this below code in (app/config/routes.php) file.

Router::connect('/:language/:controller/:action/*',
array(),
array('language' => '[a-z]{3}'));

Wednesday, September 9, 2009

Internationalizing Your Cakephp Application(support multiple languages cakephp)

For some developers, allowing a website to support multiple languages is essential. Luckily cakePHP 1.2 has the foundations available to make this possible.

I certainly hope after using this guide you can quickly and easily implement multiple languages in your cake app without needing to skip around the place. If I fall short of this and you have suggestions, leave a comment.

Once you complete this tutorial your site will be able to:
1. display multiple languages
2. allow users to switch languages
3. store language settings in cookies, so returning visitors don't need to re-select their preferred language
The sites that I build typically require 3 languages:
1. British English(eng)
2. Koren (kor)
3. Japanes (jap)
Step 1: Setup the directories and file for your messages
app/locale/eng/LC_MESSAGES/ default.po
app/locale/kor/LC_MESSAGES/ default.po
app/locale/jap/LC_MESSAGES/ default.po

Example Code of app/locale/eng/LC_MESSAGES/ default.op file.
msgid "home"
msgstr "Home"
msgid "about_us"
msgstr "About us"
msgid "membership_options"
msgstr "Membership Options"
msgid "our_lessons"
msgstr "Our lessons"
msgid "community"
msgstr "Community"
msgid "contact_us"
msgstr "Contact Us"
msgid "faqs"
msgstr "FAQ's"

Step 2: Write some strings to translate.(.ctp view file code sample)


Step 3: Change the default language
// config/bootstrap.php
define(DEFAULT_LANGUAGE, 'eng');
Step 4: Let users change the language
Component Class:
class P28nComponent extends Object {
var $components = array('Session', 'Cookie');

function startup() {
if (!$this->Session->check('Config.language')) {
$this->change(($this->Cookie->read('lang') ? $this->Cookie->read('lang') : DEFAULT_LANGUAGE));
}
}

function change($lang = null) {
if (!empty($lang)) {
$this->Session->write('Config.language', $lang);
$this->Cookie->write('lang', $lang, null, '+350 day');
}
}
}
?>
Controller Class:
class P28nController extends AppController {
var $name = 'P28n';
var $uses = null;
var $components = array('P28n');

function change($lang = null) {
$this->P28n->change($lang);

$this->redirect($this->referer(null, true));
}

function shuntRequest() {
$this->P28n->change($this->params['lang']);

$args = func_get_args();
$this->redirect("/" . implode("/", $args));
}
}
?>
Controller Class:
//app_controller.php
class AppController extends Controller {
var $components = array('P28n');
}
?>
The final piece of code, are some custom routes that need to be added to cake/app/config/routes.php

//route to switch locale
Router::connect('/lang/*', array('controller' => 'p28n', 'action' => 'change'));

//forgiving routes that allow users to change the lang of any page
Router::connect('/eng/*', array('controller' => "p28n",'action' => "shuntRequest",'lang' => 'eng'));
Router::connect('/jap/*', array('controller' => "p28n",'action' => "shuntRequest",'lang' => 'jap'));
Router::connect('/kor/*', array('controller' => "p28n",'action' => "shuntRequest",'lang' => 'kor'));
Step 6: Links to change language
image("lang-3.gif", array("alt" => "english",'url' =>_ROOT.'lang/kor')); ?>

image("lang-2.gif", array("alt" => "english",'url' =>_ROOT.'lang/jpn')); ?>

image("lang-1.gif", array("alt" => "english",'url' =>_ROOT.'lang/eng')); ?>

Monday, August 10, 2009

Image Upload and Resize Component for CakePHP 1.2

############## image.php #####################
create a components image in following given path
/app/controllers/components/image.php

/*
File: /app/controllers/components/image.php
*/
class ImageComponent extends Object
{
/*
* Uploads an image and its thumbnail into $folderName/big and $folderName/small respectivley.
* the generated thumnail could either have the same aspect ratio as the uploaded image, or could
* be a zoomed and cropped version.

* Directions:
* In view where you upload the image, make sure your form creation is similar to the following
* create('FurnitureSet',array('type' => 'file')); ?>
*
* In view where you upload the image, make sure that you have a file input similar to the following
* file('Image/name1'); ?>
*
* In the controller, add the component to your components array
* var $components = array("Image");
*
* In your controller action (the parameters are expained below)
* $image_path = $this->Image->upload_image_and_thumbnail($this->data,"name1",573,80,"sets",true);
* this returns the file name of the result image. You can store this file name in the database
*
* Note that your image will be stored in 2 locations:
* Image: /webroot/img/$folderName/big/$image_path
* Thumbnail: /webroot/img/$folderName/small/$image_path
*
* Finally in the view where you want to see the images
* image('sets/big/'.$furnitureSet['FurnitureSet']['image_path']);
* where "sets" is the folder name we saved our pictures in, and $furnitureSet['FurnitureSet']['image_path'] is the file name we stored in the database

* Parameters:
* $data: CakePHP data array from the form
* $datakey: key in the $data array. If you used file('Image/name1'); ?> in your view, then $datakey = name1
* $imgscale: the maximum width or height that you want your picture to be resized to
* $thumbscale: the maximum width or height that you want your thumbnail to be resized to
* $folderName: the name of the parent folder of the images. The images will be stored to /webroot/img/$folderName/big/ and /webroot/img/$folderName/small/
* $square: a boolean flag indicating whether you want square and zoom cropped thumbnails, or thumbnails with the same aspect ratio of the source image
*/
function upload_image_and_thumbnail($data, $datakey, $imgscale, $thumbscale, $folderName, $square) {
if (strlen($data['Image'][$datakey]['name'])>4){
$error = 0;
$tempuploaddir = "img/temp"; // the /temp/ directory, should delete the image after we upload
$biguploaddir = "img/".$folderName."/big"; // the /big/ directory
$smalluploaddir = "img/".$folderName."/small"; // the /small/ directory for thumbnails

// Make sure the required directories exist, and create them if necessary
if(!is_dir($tempuploaddir)) mkdir($tempuploaddir,true);
if(!is_dir($biguploaddir)) mkdir($biguploaddir,true);
if(!is_dir($smalluploaddir)) mkdir($smalluploaddir,true);

$filetype = $this->getFileExtension($data['Image'][$datakey]['name']);
$filetype = strtolower($filetype);

if (($filetype != "jpeg") && ($filetype != "jpg") && ($filetype != "gif") && ($filetype != "png"))
{
// verify the extension
return;
}
else
{
// Get the image size
$imgsize = GetImageSize($data['Image'][$datakey]['tmp_name']);
}

// Generate a unique name for the image (from the timestamp)
$id_unic = str_replace(".", "", strtotime ("now"));
$filename = $id_unic;

settype($filename,"string");
$filename.= ".";
$filename.=$filetype;
$tempfile = $tempuploaddir . "/$filename";
$resizedfile = $biguploaddir . "/$filename";
$croppedfile = $smalluploaddir . "/$filename";

if (is_uploaded_file($data['Image'][$datakey]['tmp_name']))
{
// Copy the image into the temporary directory
if (!copy($data['Image'][$datakey]['tmp_name'],"$tempfile"))
{
print "Error Uploading File!.";
exit();
}
else {
/*
* Generate the big version of the image with max of $imgscale in either directions
*/
$this->resize_img($tempfile, $imgscale, $resizedfile);

if($square) {
/*
* Generate the small square version of the image with scale of $thumbscale
*/
$this->crop_img($tempfile, $thumbscale, $croppedfile);
}
else {
/*
* Generate the big version of the image with max of $imgscale in either directions
*/
$this->resize_img($tempfile, $thumbscale, $croppedfile);
}

// Delete the temporary image
unlink($tempfile);
}
}

// Image uploaded, return the file name
return $filename;
}
}

/*
* Deletes the image and its associated thumbnail
* Example in controller action: $this->Image->delete_image("1210632285.jpg","sets");
*
* Parameters:
* $filename: The file name of the image
* $folderName: the name of the parent folder of the images. The images will be stored to /webroot/img/$folderName/big/ and /webroot/img/$folderName/small/
*/
function delete_image($filename,$folderName) {
unlink("img/".$folderName."/big/".$filename);
unlink("img/".$folderName."/small/".$filename);
}

function crop_img($imgname, $scale, $filename) {
$filetype = $this->getFileExtension($imgname);
$filetype = strtolower($filetype);

switch($filetype){
case "jpeg":
case "jpg":
$img_src = ImageCreateFromjpeg ($imgname);
break;
case "gif":
$img_src = imagecreatefromgif ($imgname);
break;
case "png":
$img_src = imagecreatefrompng ($imgname);
break;
}

$width = imagesx($img_src);
$height = imagesy($img_src);
$ratiox = $width / $height * $scale;
$ratioy = $height / $width * $scale;

//-- Calculate resampling
$newheight = ($width <= $height) ? $ratioy : $scale;
$newwidth = ($width <= $height) ? $scale : $ratiox;

//-- Calculate cropping (division by zero)
$cropx = ($newwidth - $scale != 0) ? ($newwidth - $scale) / 2 : 0;
$cropy = ($newheight - $scale != 0) ? ($newheight - $scale) / 2 : 0;

//-- Setup Resample & Crop buffers
$resampled = imagecreatetruecolor($newwidth, $newheight);
$cropped = imagecreatetruecolor($scale, $scale);

//-- Resample
imagecopyresampled($resampled, $img_src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//-- Crop
imagecopy($cropped, $resampled, 0, 0, $cropx, $cropy, $newwidth, $newheight);

// Save the cropped image
switch($filetype)
{

case "jpeg":
case "jpg":
imagejpeg($cropped,$filename,80);
break;
case "gif":
imagegif($cropped,$filename,80);
break;
case "png":
imagepng($cropped,$filename,80);
break;
}
}

function resize_img($imgname, $size, $filename) {
$filetype = $this->getFileExtension($imgname);
$filetype = strtolower($filetype);

switch($filetype) {
case "jpeg":
case "jpg":
$img_src = ImageCreateFromjpeg ($imgname);
break;
case "gif":
$img_src = imagecreatefromgif ($imgname);
break;
case "png":
$img_src = imagecreatefrompng ($imgname);
break;
}

$true_width = imagesx($img_src);
$true_height = imagesy($img_src);

if ($true_width>=$true_height)
{
$width=$size;
$height = ($width/$true_width)*$true_height;
}
else
{
$width=$size;
$height = ($width/$true_width)*$true_height;
}
$img_des = ImageCreateTrueColor($width,$height);
imagecopyresampled ($img_des, $img_src, 0, 0, 0, 0, $width, $height, $true_width, $true_height);

// Save the resized image
switch($filetype)
{
case "jpeg":
case "jpg":
imagejpeg($img_des,$filename,80);
break;
case "gif":
imagegif($img_des,$filename,80);
break;
case "png":
imagepng($img_des,$filename,80);
break;
}
}

function getFileExtension($str) {

$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
} ?>

A easy captcha component implentation into cakephp.

First save the code below into a file called captcha.php and put it in your controller components folder

Then very important create a folder called "fonts" in your files which is located in webroot/files/ copy the fonts you want to use inside that folder you can add as many fonts as you like and use only true type fonts but here is a link to the fonts i used. www.getkeywords.co.za/files/fonts.tar.gz

uses('security');

class CaptchaComponent extends Object {

var $length = 6;

var $fontpath;

var $fonts;

var $components = array('Session');

var $controller = array();

var $sessionKey = 'Captcha';

var $case = false;

var $filters = array();

var $imgFormat = "png";

var $bgColor = array(255, 255, 255);

var $stringColor = array(0, 0, 0);


function startup(&$controller) {

if (strtolower($controller->name) == 'app' || (strtolower($controller->name) == 'tests' && Configure::read() > 0)) {
return;
}

$this->controller = $controller;

if (!method_exists($controller, 'captcha')) {

trigger_error(__('Could not find function captcha. Please create a captcha function in Controller::$controller.', true), E_USER_WARNING);
die();

}

$this->fontpath = $this->__getFontPath();

if(is_null($this->__getFonts())) {

trigger_error(__('Could not find any fonts in webroot/files/fonts/ please confirm you have created directory and have uploaded only true type fonts!', true), E_USER_WARNING);
die();

}

}


// Add this to controller action which you want to use captcha
// for and the model that has the capchta variable in.
function protect($model = 'Captcha') {

if(isset($this->controller->data[$model]['captcha']) && !empty($this->controller->data[$model]['captcha'])) {

if($this->__check($this->controller->data[$model]['captcha'])) {

$this->Session->del($this->sessionKey);
unset($this->controller->data[$model]['captcha']);

return true;

} else {

$this->__generate();
$this->Session->setFlash(__('Incorrect image verification please retry!',true));
unset($this->controller->data[$model]['captcha']);

return false;

}

} else {

$this->__generate();
return false;

}
}

// Create a function called captcha in a controller and reference
// the captcha image src in the view to it.
function show() {

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: no-store, no-cache");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");

$this->fontpath = $this->__getFontPath();

$this->fonts = $this->__getFonts();

$this->__makeCaptcha();

$this->controller->autoRender=false;

} //captcha

function __check($string) {

return ($string === $this->Session->read($this->sessionKey));

}

function __generate($protect = false) {

if(!$protect) {

$protect = !$this->Session->check($this->sessionKey);

}

if ($protect) {

$this->Session->write($this->sessionKey, $this->__stringGen());

}

}

function __getFontPath() {

return WWW_ROOT . 'files' . DS . 'fonts' . DS;

}

function __getFonts() {

$fonts = array();

if ($handle = @opendir($this->fontpath)) {

while (($file = readdir($handle)) !== FALSE) {

$extension = strtolower(substr($file, strlen($file) - 3, 3));

if ($extension == 'ttf') {

$fonts[] = $file;

}

}

closedir($handle);

} else {

return null;

}

if (count($fonts) == 0) {

return null;

} else {

return $fonts;

}

} //getFonts

function __getRandFont() {

return $this->fontpath . $this->fonts[mt_rand(0, count($this->fonts) - 1)];

} //getRandFont


function __stringGen() {

$results = null;
$uppercase = range('A', 'Z');
$numeric = range(0, 9);

$CharPool = array_merge($uppercase, $numeric);

if($this->case) {

$lowercase = range('a', 'z');
$CharPool = array_merge($CharPool, $lowercase);

}

$PoolLength = count($CharPool) - 1;

for ($i = 0; $i < $this->length; $i++) {

$results .= $CharPool[mt_rand(0, $PoolLength)];

}

return $results;

} //StringGen

function __makeCaptcha() {

$this->__generate(true);
$captchaString = $this->Session->read($this->sessionKey);

$imagelength = $this->length * 25 + 16;
$imageheight = 75;

$image = imagecreate($imagelength, $imageheight);

$bgcolor = imagecolorallocate($image, $this->bgColor[0], $this->bgColor[1], $this->bgColor[2]);

$stringcolor = imagecolorallocate($image, $this->stringColor[0], $this->stringColor[1], $this->stringColor[2]);

$this->__signs($image, $this->__getRandFont());

for ($i = 0; $i < strlen($captchaString); $i++) {

imagettftext($image, 25, mt_rand(-15, 15), $i * 25 + 10,
mt_rand(30, 70),
$stringcolor,
$this->__getRandFont(),
$captchaString{$i});

}

if(isset($this->filters['noise']) && is_numeric($this->filters['noise'])) {

$this->__noise($image, $this->filters['noise']);

}

if(isset($this->filters['blur']) && is_numeric($this->filters['blur'])) {

$this->__blur($image, $this->filters['blur']);

}

switch($this->imgFormat) {

case "png" : header('Content-type: image/png');
imagepng($image);
break;

case "jpg" : header('Content-type: image/jpg');
imagejpeg($image);
break;

case "jpeg" : header('Content-type: image/jpg');
imagejpeg($image);
break;

case "gif" : header('Content-type: image/gif');
imagegif($image);
break;

default : header('Content-type: image/png');
imagejpeg($image);
break;

}

imagedestroy($image);

} //MakeCaptcha


/*-----------------------------
* FILTER FOR CAPTCHA
*
*
*------------------------------*/

function __noise(&$image, $runs = 30) {

$w = imagesx($image);
$h = imagesy($image);

for ($n = 0; $n < $runs; $n++) {

for ($i = 1; $i <= $h; $i++) {

$randcolor = imagecolorallocate($image,
mt_rand(0, 255),
mt_rand(0, 255),
mt_rand(0, 255));

imagesetpixel($image,
mt_rand(1, $w),
mt_rand(1, $h),
$randcolor);

}

}

} //noise

function __signs(&$image, $font, $cells = 3) {

$w = imagesx($image);
$h = imagesy($image);

for ($i = 0; $i < $cells; $i++) {

$centerX = mt_rand(1, $w);
$centerY = mt_rand(1, $h);
$amount = mt_rand(1, 15);
$stringcolor = imagecolorallocate($image, 175, 175, 175);

for ($n = 0; $n < $amount; $n++) {

$signs = range('A', 'Z');
$sign = $signs[mt_rand(0, count($signs) - 1)];

imagettftext($image, 25,
mt_rand(-15, 15),
$centerX + mt_rand(-50, 50),
$centerY + mt_rand(-50, 50),
$stringcolor, $font, $sign);

}

}

} //signs

function __blur(&$image, $radius = 3) {

$radius = round(max(0, min($radius, 50)) * 2);

$w = imagesx($image);
$h = imagesy($image);

$imgBlur = imagecreate($w, $h);

for ($i = 0; $i < $radius; $i++) {

imagecopy ($imgBlur, $image, 0, 0, 1, 1, $w - 1, $h - 1);
imagecopymerge($imgBlur, $image, 1, 1, 0, 0, $w, $h, 50.0000);
imagecopymerge($imgBlur, $image, 0, 1, 1, 0, $w - 1, $h, 33.3333);
imagecopymerge($imgBlur, $image, 1, 0, 0, 1, $w, $h - 1, 25.0000);
imagecopymerge($imgBlur, $image, 0, 0, 1, 0, $w - 1, $h, 33.3333);
imagecopymerge($imgBlur, $image, 1, 0, 0, 0, $w, $h, 25.0000);
imagecopymerge($imgBlur, $image, 0, 0, 0, 1, $w, $h - 1, 20.0000);
imagecopymerge($imgBlur, $image, 0, 1, 0, 0, $w, $h, 16.6667);
imagecopymerge($imgBlur, $image, 0, 0, 0, 0, $w, $h, 50.0000);
imagecopy ($image , $imgBlur, 0, 0, 0, 0, $w, $h);

}

imagedestroy($imgBlur);

} //blur

} //class: captcha

?>
Then create a helper called captcha.php and put it in your helpers folder.
Helper Class:
/******************************************************************

Projectname: CAPTCHA Helper class
Version: 1.0
Author: Michael James (mikeyjsa@gmail.com)
Website: http://www.getkeywords.co.za
Last modified: 11. June 2008

* GNU General Public License (Version 2, June 1991)
*
* This program is free software; you can redistribute
* it and/or modify it under the terms of the GNU
* General Public License as published by the Free
* Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License
* for more details.

Description:
This helper is used to generate CAPTCHAs.

******************************************************************/
class CaptchaHelper extends AppHelper {

var $helpers = array('html', 'form');

function input($controller = null) {

if(is_null($controller)) {
$controller = $this->params['controller'];
}

$output = array();
$output[] = $this->html->image('/' . $controller . '/captcha/image.png', array('id' => 'captcha_image'));
$output[] = $this->form->input('Captcha/captcha', array('div' => 'captcha_input', 'label' => '(Case Sensitive!)'));

return implode("\r\n", $output);

}

}
?>

First in the controller you want to implement it into add the component then create a function called captcha and and in the following and on the form you want to protect where it checks if the data is empty just add "&& $this->Captcha->protect()". That will return a boolean back.






var $components = array('Captcha');
var $helpers = array('Captcha');

function captcha() {

$this->Captcha->show();

}

function add() {
if (!empty($this->data) && $this->Captcha->protect()) {
$this->ModelName->save($this->data);
}
}


?>
View Template:
Input this code in your .ctp file where you need a captcha

echo $captcha->input();

Friday, July 24, 2009

You can set CakePHP Debug Level

CakePHP Debug Level:

Production Mode:
0: No error messages, errors, or warnings shown. Flash messages redirect.

Development Mode:
1: Errors and warnings shown, model caches refreshed, flash messages halted.
2: As in 1, but also with full debug messages and SQL output.
3: As in 2, but also with full controller dump.

Note:-
In production mode, flash messages redirect after a time interval.
In development mode, you need to click the flash message to continue.

In core.php file u will get this code:-

Configure::write('debug',2);

Thursday, July 23, 2009

Redirect to custom error page,if page is not exists

ErrorDocument 404 /not-found.php

From this .htaccess code you can redirect to custom error page.
if user request for non exists file on site URL.

Saturday, July 18, 2009

Select or Unselect all Checkbox

You can use this free javascript code to Select / Unselect all the checkboxes by selecting a single check box.



checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}

OR consider this

tag_name=checkbox array name
checkallName=select all checkbox name

function checkedAll (tag_name,checkallName) {

var checked=false;
checked = document.getElementById(checkallName).checked;

for (var i = 0; i < document.getElementsByName(tag_name).length; i++) {
document.getElementsByName(tag_name)[i].checked = checked;
}

}

Friday, July 10, 2009

php realex payment gateway code

$timestamp = strftime("%Y%m%d%H%M%S");
$topay = '5';
$merchantid = "mytalentplace";//here grant crow`s realex merchent id should come
$secret = "wXcHmZ9yec";


$orderid= $timestamp.'-'.$_SESSION['ord_id'];





$amount =$_POST['amt']*100;

if($_REQUEST['currency']=="doller"){

$curr= "USD";

} elseif($_REQUEST['currency']=="euro"){

$curr= "EUR";

}else {

$curr= "GBP";

}

$tmp = "$timestamp.$merchantid.$orderid.$amount.$curr";
//$tmp = "$timestamp.$merchantid.$orderid";

$md5hash = sha1($tmp);

$tmp = "$md5hash.$secret";

$md5hash = sha1($tmp);

$up="UPDATE `mtp_user_payment` SET order_id='".$lid."' where user_payment_id='".$lid."'";
mysql_query($up);
?>

Opening Cake THTML file with Dreaweaver CS4

Just go to:

C:\Program Files\Adobe\Adobe Dreamweaver CS4\configuration

Open file: Extensions.txt

edit line 16 and add THTML

Save and Close the File

Next, Open MMDocumentTypes.xml at C:\Program Files\Adobe\Adobe Dreamweaver CS4\configuration\DocumentTypes

Add THTML online 75 : winfileextension=”thtml,php,php3,php4,php5″ macfileextension=”thtml,php,php3,php4,php5″

Save, close and Restart Dreamweaver!


For more Info :- http://keithics.com/blog/article/opening-cake-thtml-file-with-dreaweaver-cs4/118/


Tuesday, July 7, 2009

Website Payments Standard Integration Guide (Paypal)

https://www.paypalobjects.com/WEBSCR-580-20090702-1/en_US/pdf/PP_WebsitePaymentsStandard_IntegrationGuide.pdf

How do I generate a PayPal Identity Token

1. Click the My Account tab.
2. Click Profile at the top of the page.
3. On the right under Selling Preferences click on Website Payment Preferences.
4. Under Auto Return for Website Payments click "on"
5. After Return URL put http://www.example.com
6. Under Payment Data Transfer (Optional) click "on"
7. Scroll to the bottom of the page and click Save.
8. Copy the Identity Token (everything after the word "Token:" in the new window), and paste it into your My talent place PayPal Information.

PayPal Identity Token (PHP Script)

if (!$fp) { // HTTP ERROR } else { fputs ($fp, $header . $req); // read the body data $res = ''; $headerdone = false; while (!feof($fp)) { $line = fgets ($fp, 1024); if (strcmp($line, "\r\n") == 0) { // read the header $headerdone = true; } else if ($headerdone) { // header has been read. now read the contents $res .= $line; } }
// parse the data $lines = explode("\n", $res); $keyarray = array(); if (strcmp ($lines[0], "SUCCESS") == 0) { for ($i=1; $iaddPaymentDetails($keyarray['txn_id'], 'Paypal', $keyarray['mc_gross'], $keyarray['option_name1'],$status);
header("location:thanks_payment.php"); } else if (strcmp ($lines[0], "FAIL") == 0) { header("location:error.php"); // log for manual investigation //header("location:thanks_payment.php"); }
}
fclose ($fp);?>

Example of Custom URL rewritting

RewriteEngine on
RewriteRule ^career-options/(.*)-([0-9]+)\.html$ careerdetails.php?carr_id=$2RewriteRule ^career-advice$ careeradvice.phpRewriteRule ^parent-career-help$ parent_profile.phpRewriteRule ^Forum/(.*)-([0-9]+)\.html$ forum_index.php?career_category_id=$2RewriteRule ^career-advice/career-counselling$ careercounselling.phpRewriteRule ^career-advice/interview-training$ interviewsuccess.phpRewriteRule ^career-advice/interview-questions-answers$ interview_questions.phpRewriteRule ^career-options$ career.phpRewriteRule ^community$ community.phpRewriteRule ^career--options/(.*)-([0-9]+)\.html$ careerdetails.php?carr_id=$2&addFirstChoice=1

mytalentplace

One of my favorite recent developed web site.
URL :- http://www.mytalentplace.co.uk/

Wednesday, July 1, 2009

best blog for PHP script or code

This blog is created and maintained by Mr.Jawed Shamshedi (Sr.Eng..) for php developer's.

http://jawedphp.blogspot.com/

PHP date problem

useful URL for PHP date problem

url rewriting

useful url rewriting examples using .htaccess

1)Rewriting product.php?id=12 to product-12.html
It is a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1
2) Rewriting product.php?id=12 to product/ipod-nano/12.html
SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.
RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2
3) Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz
Have you checked zorpia.com.If you type http://zorpia.com/roshanbh233 in browser you can see my profile over there. If you want to do the same kind of redirection i.e http://yoursite.com/xyz to http://yoursite.com/user.php?username=xyz then you can add the following code to the .htaccess file.
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
4) Redirecting the domain to a new subfolder of inside public_html.
Suppose the you’ve redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “test.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, www.test.com point out to the files inside “new” folder.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.test\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*) /new/$1

ebook

lot of books collection here !

Testing Web Based Applications with JMeter

http://www.devarticles.com/c/a/PHP/Regression-Testing-With-JMeter/

Some Important Link to read about OOPs with php

Object Oriented Programming with PHP

http://www.devarticles.com/c/a/PHP/Object-Oriented-Programming-in-PHP/