CakePHP 3 project creation process using composer technique, very easy and faster.


The installation technique is only for Windows Machine with Xampp/Wamp Server.

1. Download & Install Composer in your local machine. Click here to download

2.  Now Go to your server root directory using command prompt. (ie. C:\wamp\www)

3. Run the Following code Now


composer self-update && composer create-project --prefer-dist cakephp/app bookmarker

4. Well Done!! You just setup a fresh CakePHP latest version Application using composer. Now modify your application based on your desire requirement.

5. Now You Need to Run the Code. Go to Your project directory and run the following code


bin\cake server

6. You will get a url like (http://localhost:8765/). Copy & browse.

cakephp3

7. Setup you database connection and use the cake console for rapid development.

Here is the sample CakePHP 3 Project for you in case you have a mistake. Download and Enjoy.

Github Link: https://github.com/ziyed/CakePHP3

Unicode font like arabic or others displaying technique on webpage from mysql database at CakePHP or raw php


1. Make Sure that your database has UTF8 Character set, Run the following code

 ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 

2. Make Sure that your table has UTF8 Character set and Collate utf8_unicode_ci or utf8_general_ci

 ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 

3. Make Sure that your webpage has utf8 enable

 <meta charset="UTF-8">
 

4. Set utf8 before any mysql query in raw php

 mysql_query("SET NAMES utf8");
 

At CakePHP you can set this very easily at database config file:

Remove the comment line before ‘encoding’ and make this line available for execution.

 
 public $default = array(
	'datasource' => 'Database/Mysql',
	'persistent' => false,
	'host' => 'localhost',
	'login' => 'root',
	'password' => '',
	'database' => 'cake278',
	'prefix' => '',
	//'encoding' => 'utf8',
 );
 
 

Google reCAPTCHA integration with MVC PHP Framework CakePHP Version 2


Just follow the below steps to setup Google reCAPTCHA in your webpage very quickly.

Step 1:

Register for reCAPTCHA from google recaptcha website link, Click Here To Visit This Web Page

You will get Site key, Secret key Once submit, Preserve it.

Step 2:

Add the below script to your headers.


  <script src='https://www.google.com/recaptcha/api.js'></script>

Step 3:

Add the below html code inside your form as your desire position to display Google reCAPTCHA. Replace your Google Site Key on Correct position given below.


  <div class="g-recaptcha" data-sitekey="#Replace This With Your Site Key From Google#"></div>

Step 4:

Final Code to check reCAPTCHA process complete successfully or not. paste the below code inside the controller method where the form will be posted.


  //reCaptcha Area start
  if (isset($this->request->data['g-recaptcha-response'])) {
    $captcha = $this->request->data['g-recaptcha-response'];
  }
  if (!$captcha) {
    $this->Session->setFlash(__('Please check the captcha form, try again.'), 'flash_error');
    $this->redirect(array('controller' => 'users', 'action' => 'register'));
  }
  $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=#Replace This With Your Secret Key From Google#&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
  if ($response . success == false) {
    $this->Session->setFlash(__('You are a spammer ! Get out'), 'flash_error');
    $this->redirect(array('controller' => 'users', 'action' => 'register'));
  } 
  //reCaptcha Area end

CakePHP application run without mod_rewrite activation on server


Some shared server can not provide to read/write .htaccess file for which cakephp application can not run properly on those server. here is the simple solution to overcome these situation. just follow the below steps to make it workable on any server.

To configure CakePHP *not* to use mod_rewrite and to use CakePHP pretty URLs, remove these .htaccess files:


   /.htaccess
   /app/.htaccess
   /app/webroot/.htaccess
 

Uncomment the App.baseUrl line from core file :

File location : /app/Config/core.php


   Configure::write('App.baseUrl', env('SCRIPT_NAME'));
 

File download functionality at CakePHP 2.0



  /*
     *  function name admin_download(
     *     Fiile Name,
     *     Folder Path
     *  )
     *  Admin Panel download
     */

    public function admin_download($filename='', $dir_path = '') {
        $name = pathinfo($filename, PATHINFO_FILENAME);
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $this->viewClass = 'Media';
        $params = array(
            'id' => $filename,
            'name' => $name,
            'download' => true,
            'extension' => $ext,
            'mimeType' => array(
                "docm" => "application/vnd.ms-word.document.macroEnabled.12",
                "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "dotm" => "application/vnd.ms-word.template.macroEnabled.12",
                "dotx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
                "potm" => "application/vnd.ms-powerpoint.template.macroEnabled.12",
                "potx" => "application/vnd.openxmlformats-officedocument.presentationml.template",
                "ppam" => "application/vnd.ms-powerpoint.addin.macroEnabled.12",
                "ppsm" => "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
                "ppsx" => "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
                "pptm" => "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
                "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                "xlam" => "application/vnd.ms-excel.addin.macroEnabled.12",
                "xlsb" => "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
                "xlsm" => "application/vnd.ms-excel.sheet.macroEnabled.12",
                "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "xltm" => "application/vnd.ms-excel.template.macroEnabled.12",
                "xltx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
                "pdf" => "application/pdf"
            ),
            'path' => WWW_ROOT . DS . $dir_path . DS
        );
        $this->set($params);
    }

Image resize function at CakePHP 2.0



    //How to call another function
    public function imgresize(){
        //create thumbnail of original image
        $source_image = WWW_ROOT . 'upload_books/' . $new_image_name;
        $destination_thumb_path = WWW_ROOT . 'upload_books/thumbs/' . $new_image_name;
        $this->__imageresize($source_image, $destination_thumb_path, 92, 112);
    }
/*
     *  function name __imageresize(
     *     Image Source, which one's thumb image will be create,
     *     Destination thumbs path with image name,
     *     Image width size,
     *     Image height size
     *  )
     * Note: If original image width is grater than height then the width, height value will be swap
     *
     */

    public function __imageresize($imagePath, $thumb_path, $destinationWidth, $destinationHeight) {
        // The file has to exist to be resized
        if (file_exists($imagePath)) {
            // Gather some info about the image
            $imageInfo = getimagesize($imagePath);

            // Find the intial size of the image
            $sourceWidth = $imageInfo[0];
            $sourceHeight = $imageInfo[1];

            if ($sourceWidth > $sourceHeight) {
                $temp = $destinationWidth;
                $destinationWidth = $destinationHeight;
                $destinationHeight = $temp;
            }

            // Find the mime type of the image
            $mimeType = $imageInfo['mime'];

            // Create the destination for the new image
            $destination = imagecreatetruecolor($destinationWidth, $destinationHeight);

            // Now determine what kind of image it is and resize it appropriately
            if ($mimeType == 'image/jpeg' || $mimeType == 'image/jpg' || $mimeType == 'image/pjpeg') {
                $source = imagecreatefromjpeg($imagePath);
                imagecopyresampled($destination, $source, 0, 0, 0, 0, $destinationWidth, $destinationHeight, $sourceWidth, $sourceHeight);
                imagejpeg($destination, $thumb_path);
            } else if ($mimeType == 'image/gif') {
                $source = imagecreatefromgif($imagePath);
                imagecopyresampled($destination, $source, 0, 0, 0, 0, $destinationWidth, $destinationHeight, $sourceWidth, $sourceHeight);
                imagegif($destination, $thumb_path);
            } else if ($mimeType == 'image/png' || $mimeType == 'image/x-png') {
                $source = imagecreatefrompng($imagePath);
                imagecopyresampled($destination, $source, 0, 0, 0, 0, $destinationWidth, $destinationHeight, $sourceWidth, $sourceHeight);
                imagepng($destination, $thumb_path);
            } else {
                $this->Session->setFlash(__('This image type is not supported.'), 'flash_error');
            }

            // Free up memory
            imagedestroy($source);
            imagedestroy($destination);
        }
    }


Marketo API Call and insert/update lead from third party using SOAP at CakePHP


1. First you need to download Marketo api php class file.You can download it from below link.
2. Download link: Download Marketo SOAP API PHP Client Class
3. Unzip the folder and put it to cakephp vendor folder
4. Now at CakePHP controller you can use this class to insert/update marketo lead

 


    function marketo_api_call($attributes) {
        $this->layout = 'null';
        $this->autoRender = FALSE;
        $email = $attributes['email'];

	//importing marketo class
        App::import('Vendor', 'marketosoapphpcient',
                   array('file' => 'marketosoapphpcient.php'));

	//Set default MKTOWS_USER_ID and  MKTOWS_SECRET_KEY
	define('MKTOWS_USER_ID', 'test_45454545454554D595850D6D12DHG38');
        define('MKTOWS_SECRET_KEY', '4545456456453132DDFDHGFGB704A9FC75');

        $accessKey = mktSampleMktowsClient::MKTOWS_USER_ID;
        $secretKey = mktSampleMktowsClient::MKTOWS_SECRET_KEY;
        $soapEndPoint = 'https://na-k.marketo.com/soap/mktows/1_7';
        $client = new mktSampleMktowsClient(
                    $accessKey, $secretKey, $soapEndPoint
        );
        $attrs = array(
            "City" => $attributes['city'],
            "Company" => $attributes['company_title'],
            "Country" => $attributes['country'],
            "Email" => $email,
            "FirstName" => $attributes['first_name'],
            "LastName" => $attributes['last_name'],
            "MobilePhone" => $attributes['cell_phone'],
            "Phone" => $attributes['work_phone'],
            "State" => $attributes['state'],
            "Title" => $attributes['job_title']
        );

	// syncLead called to perform insert/update lead 
        // to marketo list through Marketo API 
        $success = $client->syncLead($email, $attrs);
        return $success;
    }

 

Create new input file field on the fly at client side using jquery at cakephp


Html code of input field

<div>
<div style=”float: left;width:160px”>
<label for=”ExhibitorMaterials”><span>Additional Materials/Files : </span></label>
</div>
<div style=”float: left”>
<?php echo $this->Form->input(”, array(‘name’ => ‘data[Exhibitor][materials][]’, ‘label’ => ”, ‘type’ => ‘file’)); ?>
<div id=”newMaterialsHolder”></div>
<a id=”add_New_Materials” title=”Add another file” href=”javascript:void(0)”><span>Add Another File</span></a>
</div>
</div>

Related jQuery Code to implement this

<script type=”text/javascript”>
jQuery(document).ready(function(){
var i = 1;
var template = ‘<?php echo $this->Form->input(”, array(‘name’ => ‘data[Exhibitor][materials][]’, ‘label’ => false, ‘type’ => ‘file’)); ?>’;
template += ‘<a href=”javascript:void(0)”><span style=”color:red”>Close</span></a>’;
template = ‘<div>’+template+'</div>’;
jQuery(‘#add_New_Materials’).click(function(){
var tpl = jQuery(template).find(‘input[type=file]’).attr(‘id’, ‘in’+i).end();
jQuery(‘#newMaterialsHolder’).append(tpl);
tpl.find(‘a’).click(function(){
jQuery(tpl).remove();
});
i++;
});
});
</script>

 

file downlaod code at cakephp


This code help you to download any file from server

function download($filename) {
$filename = WWW_ROOT . DS . $filename;
if (file_exists($filename)) {
header(“Pragma: public”);
header(“Expires: 0”);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
header(“Cache-Control: private”, false);
header(“Content-Type: application/force-download”);
header(“Content-Type: application/zip”);
header(“Content-Type: application/pdf”);
header(“Content-Type: application/octet-stream”);
header(“Content-Type: image/png”);
header(“Content-Type: image/gif”);
header(“Content-Type: image/jpg”);
header(“Content-Type: application/vnd.ms-excel”);
header(“Content-Type: application/vnd.ms-excel”);
header(“Content-Type: application/vnd.ms-powerpoint”);
header(“Content-type: application/x-msexcel”);
header(“Content-type: application/msword”);
header(“Content-Description: File Transfer”);
header(“Content-Disposition: attachment; filename=” . basename($filename) . “;”);
header(“Content-Transfer-Encoding: binary”);
header(“Content-Length: ” . filesize($filename));
readfile($filename) or die(‘Errors’);
exit(0);
}
}

Another Example:

function download_material($id = null){
$material = $this->ExhibitorMaterial->read(null,$id);
$filename = WWW_ROOT . ‘exhibitor_material’ . DS . $material[‘ExhibitorMaterial’][‘file_type’];
if (file_exists($filename)) {
//Parse file get extension and size
$fsize = filesize($filename);
$path_parts = pathinfo($filename);
$ext = strtolower($path_parts[“extension”]);
// Determine Content Type
switch ($ext) {
case “pdf”:
$ctype = “application/pdf”;
break;
case “exe”:
$ctype = “application/octet-stream”;
break;
case “zip”:
case “rar”:
$ctype = “application/zip”;
break;
case “doc”:
case “docx”:
$ctype = “application/msword”;
break;
case “xls”:
case “xlsx”:
$ctype = “application/vnd.ms-excel”;
break;
case “ppt”:
case “pptx”:
$ctype = “application/vnd.ms-powerpoint”;
break;
case “gif”:
$ctype = “image/gif”;
break;
case “png”:
$ctype = “image/png”;
break;
case “jpeg”:
case “jpg”:
$ctype = “image/jpg”;
break;
default: $ctype = “application/force-download”;
}
header(“Pragma: public”);
header(“Expires: 0”);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
header(“Cache-Control: private”, false);
header(“Content-Type: $ctype”);
header(“Content-Description: File Transfer”);
header(“Content-Disposition: attachment; filename=” . basename($filename) . “;”);
header(“Content-Transfer-Encoding: binary”);
header(“Content-Length: ” . $fsize);
readfile($filename) or die(‘Errors’);
exit(0);
}
}

Resize and create a new image from another existing image at server side


Cakephp function to create new image from another image:

public function _createHeaderImage($file_name, $theme_name , $thumb_file_name ) {
$final_width_of_image = 960;
$path_theme_directory = ‘../../app/webroot/theme_folder’;
$path_to_image_directory = $path_theme_directory.DS.”$theme_name”;
$filenamelower = strtolower($file_name);
$check = null;
if(strstr($filenamelower, ‘.jpg’)) {
$im = imagecreatefromjpeg($path_to_image_directory.DS.$file_name);
$check = ‘jpg’;
}else if (strstr($filenamelower, ‘.gif’)) {
$im = imagecreatefromgif($path_to_image_directory.DS.$file_name);
$check = ‘gif’;
}else if (strstr($filenamelower, ‘.png’)) {
$im = imagecreatefrompng($path_to_image_directory.DS.$file_name);
$check = ‘png’;
}else if(strstr($filenamelower, ‘.jpeg’)) {
$im = imagecreatefromjpeg($path_to_image_directory.DS.$file_name);
$check = ‘jpeg’;
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
//$ny = floor($oy * ($final_width_of_image / $ox));
$ny = 180;
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(($check == ‘jpg’) ||($check == ‘jpeg’) ){
imagejpeg($nm, $path_to_image_directory.DS.$thumb_file_name);
}else if($check == ‘gif’){
imagegif($nm, $path_to_image_directory.DS.$thumb_file_name);
}else if($check == ‘png’){
imagepng($nm, $path_to_image_directory.DS.$thumb_file_name);
}
}