CakePHP: How To Use ‘neighbors’ With ‘find’ Method

CakePHP ‘find’ method makes it easier to retrieve data from database. The ‘find’ method can be used to construct anything from extremely simple queries to more complex ones without writing much code. This method can handle most SQL type requests and can be extended for more specific SQL queries.  I will walk you through the below example about the basics of working with the ‘find’  method

Here Are Some Inbuilt Types in CakePHP

  1. $this->Model->find(‘all’,$condition);
  2. $this->Model->find(‘first’,$condition);
  3. $this->Model->find(‘count’,$condition);
  4. $this->Model->find(‘list’,$condition);
  5. $this->Model->find(‘neighbors’,$condition);
  6. $this->Model->find(‘threaded’,$condition);

First four types are the most commonly used in CakePHP
Now, let’s take a look at an example of ‘neighbors’ type

Example

Let’s assume QuizQuestion is your model and you want to fetch the previous and next entries

Your Controller/action will look like,

public function getNeighbors($id){
 
$this->QuizQuestion->id = $id;
 
$neighbors = $this->QuizQuestion->find('neighbors',array('fields'=>array('id','question_no','description')));
}

A couple of queries will be generated in SQL as,

Query: SELECT 'QuizQuestion'.'id', 'QuizQuestion'.'question_no', 'QuizQuestion'.'description',
'QuizQuestion'.'id' FROM 'quiz_questions' WHERE 'QuizQuestion'.'id' < 38   ORDER BY
'QuizQuestion'.'id' DESC  LIMIT 1
Query: SELECT 'QuizQuestion'.'id', 'QuizQuestion'.'question_no', 'QuizQuestion'.'description',
'QuizQuestion'.'id' FROM 'quiz_questions' WHERE 'QuizQuestion'.'id' > 38   ORDER BY
'QuizQuestion'.'id' ASC  LIMIT 1

Here’s the output

Array
(
[prev] => Array
(
[QuizQuestion] => Array
(
[id] => 37
[question_no] => 1
[description] => Mathematics
)
 
)
[next] => Array
(
[QuizQuestion] => Array
(
[id] => 39
[question_no] => 3
[description] => Mathematics
)
 
)
 
)

Voila! Using the result keys ‘prev’ and ‘next’ you can view the results the way you want.

SSL Authentication Using Security Component In CakePHP

We can achieve SSL authentication in CakePHP by writing own methods like ‘forceSSL’ and ‘unforceSSL’. Also there is an in-built Security Component in CakePHP to achieve SSL authentication.

  • Using Security Component we can integrate tighter security in our application.
  • Like all components it needs configurations through several parameters.
  • We can get CSRF and form tampering protection using Security Component.
  • CsrfExpires controls the form submission.

Example:

All SSL URLs will redirect to a sub-domain ‘https://app.andolacrm.com/’ and the non SSL URL will redirect to a sub-domain ‘http://www.andolacrm.com’

How To Use Security Component

  • Include the security component in you AppControler.php
  •  Like as below

[sourcecode]class AppController extends Controller {
public $components =array( ‘Acl’,’Session’,’Email’,’Security’,’Cookie’ );

}[/sourcecode]

  • There are 3 configurable variable for which you need to set the values as per the requirement of your application in the beforeFilter functions of AppController.php
  • validatePost:

This variable basically used to validate your post data. Set false if you want skip validating you post data or in case data coming from 3rd party Services. Default its true.

  • csrfCheck :

CSRF(Cross-Site_Request_Forgery)  Used for form protection   . Set to false to skip CSRF protections.

  • CsrfUseOnce :

This is used for CSRF token.If it is set as false then it will user one csrf token through out the application else it will generate new token for each form submissions.

Sample Code :

[sourcecode]function beforeFilter() {
// Codes added for SSL security
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Security-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;validatePost=false;
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Security-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;csrfCheck=false;
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Security-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;csrfUseOnce=false;
}[/sourcecode]

  • In the ‘AppController.php’ you need to define the list of URLs that doesn’t need to be checked for SSL

[sourcecode]$sslnotallowed_url=array(‘beta_user’,’terms’,’privacy’,’security’,’display’,’faq’);[/sourcecode]

  • Code to be written in your ‘beforeFilter()’ of ‘AppController.php’

[sourcecode]function beforeFilter() {
// Codes added for SSL security
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Security-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;validatePost=false;
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Security-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;csrfCheck=false;
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Security-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;csrfUseOnce=false;
$sslnotallowed_url&nbsp; = array(‘beta_user’,’terms’,’privacy’,’security’);
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Security-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;blackHoleCallback = ‘forceSSL’;
if(!in_array($this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;params[‘action’],$sslnotallowed_url)){
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;Security-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;requireSecure(‘*’);
}
}[/sourcecode]

ForceSSL Method

[sourcecode]function forceSSL() {
$this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;redirect(‘https://app.andolacrm.com’ . $this-&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;here);
}[/sourcecode]

NOTE: Security Component can only be used for the forms create using FormHelper.

Conclusion:

Using the steps as described above would facilitate you to successfully implement the SSL in CakePHP. But you need to be more careful while using security component for your application. It may cause ‘blackhole’ error if there is any kind of security hole in your application. However, you could avoid such errors by setting above described variable to ‘false’.

How To Integrate PayPal In PHP

To accept online payments through your website you would need a payment gateway. There are numerous payment gateways that can be implemented to your website; however you will need to choose the best for your PHP application. “PayPal” is one of the most renowned payment platforms that offers the best in class services as well as secure payment transaction. One of the best features of PayPal is that it facilitates developers to check-out the integration on merchant sites.

From a developer’s point of view, PayPal API is a simple, user friendly and versatile which facilitates them to avoid the PCI burden of having credit card details to be passed through their servers. PayPal is also the most secure platform that takes care of all the money transactions for the users.

Integrating PayPal in Your Website

The first thing we need is a Sandbox Credential and API Credentials. This can be availed using the following steps:

  • Create a Business account in “https://developer.paypal.com/” in order to access the Sandbox account.
  • Log into your business account; move to the ‘Application Tab’ and create a Sandbox test account for developers to check-out the PayPal integration.
  • For PayPal payment pro services, you can use this Sandbox Credentials for logging into “https://www.sandbox.paypal.com/”
  • If you want to login to your sandbox account you have to first log into your developer account.

Steps to Implement ‘the work’ in Your Site

  • In PayPal payment pro ‘the work’ is done through API call.
  • In your code you will have to implement a function i.e. ‘PPHttpPost(methodname,str);’
  • ‘methodname’ specifies the name of the API you want to call i.e. ‘CreateRecurringPaymentsProfile’, ‘GetTransactionDetails’ etc.

There are numerous other methods for the integration which can be availed form the PayPal developer site:  https://developer.paypal.com/webapps/developer/docs/classic/api/

Under ‘Merchant’ API you would find a list of functions that can be performed by PayPal website pro.
Clicking on NVP link of each function you can view the methods and the required parameters for that method.

Second Parameter in the string; which is passed to the API, is for getting the response. It includes all the parameters that have to be passed e.g.

[sourcecode]$str = "&TOKEN = $token&AMT = $paymentAmount&CURRENCYCODE = $currencyID&PROFILESTARTDATE =
$startDate";[/sourcecode]

 

[sourcecode]$nvpStr  .= "&BILLINGPERIOD = $billingPeriod&BILLINGFREQUENCY = $billingFreq&CREDITCARDTYPE = $CREDITCARDTYPE&ACCT = $ACCT&EXPDATE = $EXPDATE&CVV2 = $CVV2&EMAIL = $EMAIL&STREET = $STREET&CITY = $CITY&STATE = $STATE&COUNTRYCODE = $COUNTRYCODE&ZIP = $ZIP&FIRSTNAME = $FIRSTNAME&LASTNAME = $LASTNAME&DESC = $DESC&FAILEDINITAMTACTION = $FAILEDINITAMTACTION&INITAMT = $INITAMT";[/sourcecode]

Note: This string might differ for different methods but the structure is similar.

  • This function returns an array having one key as ACK.
  • The value of this key specifies the FAILURE and SUCCESS of the function.

If ACK is a failure then the returned array contains following error message.

[sourcecode]function PPHttpPost($methodName, $nvpStr_) {

$APIUserName = urlencode(‘API USERNAME’);

$APIPassword = urlencode(‘API PASSWORD’);

$APISignature = urlencode(‘API SIGNATURE’);

$APIEndpoint = "https://api-3t.sandbox.paypal.com/nvp"; //sandbox url.

$version = urlencode(‘51.0’);

//setting the curl parameters.

$choice = curl_init();

curl_setopt($choice, CURLOPT_URL, $APIEndpoint);

curl_setopt($choice, CURLOPT_VERBOSE, 1);

//turning off the server and peer verification(TrustManager Concept).

curl_setopt($choice, CURLOPT_SSL_VERIFYPEER, FALSE);

curl_setopt($choice, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($choice, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($choice, CURLOPT_POST, 1);

//NVPRequest for submitting to server

$nvprequest = "METHOD=$methodName&VERSION=$version&PWD=$APIPassword&USER=$APIUserName&SIGNATURE=$APISignature";

// setting the nvprequest as POST FIELD to curl

curl_setopt($choice, CURLOPT_POSTFIELDS, $nvprequest);

//getting response from server

$httpResponse = curl_exec($choice);

if(!$httpResponse) {

exit("$methodName failed: ".curl_error($choice).'(‘.curl_errno($choice).’)’);

}

// Here Extract the RefundTransaction response details

$httpResponseArr = explode("&", $httpResponse);

$httpParsedResponseArr = array();

foreach ($httpResponseArr as $i => $value) {

$tmpAr = explode("=", $value);

if(sizeof($tmpAr) > 1) {

$httpParsedResponseArr[$tmpAr[0]] = $tmpAr[1];
}
}

if((0 == sizeof($httpParsedResponseArr)) || !array_key_exists(‘ACK’, $httpParsedResponseArr)) {
exit("Invalid HTTP Response for POST request($nvprequest) to $APIEndpoint.");
}
return $httpParsedResponseArr;
}[/sourcecode]

Setting of IPN URL

IPN stands- Instant Payment Notification

Under the Profile tab of the sandbox site there is an ‘Instant Payment Notification preference’ link. Set the IPN URL from the link.

Conclusion:

This notification is sent from server to server when any transaction is done in PayPal. To capture this transaction we can set URL in Instant Payment Notification preferences page and manage those transaction information.

CakePHP is Faster Development Of Next Generation Web Application

There are numerous PHP frameworks available such as Zend, CodeIgniter, Akelos etc. CakePHP on the other hand is the most popular framework among them and reduces significant coding time and investment. It is an open source web application development tool. It helps to build the web pages and applications faster and simpler.

Some features of CakePHP framework

  • Compatible with almost all PHP versions
  • Facilitates code scaffolding for faster development of prototypes
  • Doesn’t require any complex configuration
  • This framework is safe and secure:  It provides in-built tools for input validation, XSS prevention, SQL prevention for secure application development.
  • It provides built-in view helpers for AJAX, JavaScript, HTML etc.
  • It offers faster and flexible tempting features as well as data validation features

Never miss an update from us. Join 10,000+ marketers and leaders.

These features make installation and use of CakePHP easy which in turn makes PHP more manageable. As it is an open source, it can be customized according to the needs of specific business requirements. It provides the CakePHP developers with MVC framework, Class inheritance, re-usability, Ajax support and many more to make the development process easier and effortless.  It assists the PHP developers at all levels and provide the ability to manage every part of project development.

Conclusion

It has a lot of advantages over other PHP frameworks, such as less code, less maintenance, and more scalability. CakePHP team works tirelessly to make sure that programmers who want to use CakePHP can do so in an easy and enjoyable way. CakePHP itself is easy to use, and the framework has many features to make life easier for developers who need to create applications that work well and scale to large numbers of users.

Our CakePHP development team is highly experienced to deliver robust, logical, most reliable and effective solutions to our global clients. Our expertise in CakePHP development helps us for building cost effective apps that too matching customer budget with quick turn-around time.

CloudLinux’s Recent Integration of PHP 5.5 Alpha 2 Version

Shared hosting operating system provider CloudLinux has expanded their PHP offerings by declaring the availability of PHP 5.5 Alpha2 version to its PHP selector tool.

With the ability to select PHP versions, PHP selector allows the users to get the latest feature updates

and preferred PHP version like PHP 5.2, 5.3, 5.4, and now, 5.5 Alpha2 from their web hosting control panel. CloudLinux places each individual website in a virtual private server.

Never miss an update from us. Join 10,000+ marketers and leaders.

Each account is then assigned a specific amount of hardware resources and a desirable PHP version, by using the PHP selector tool.

PHP 5.5 Alpha2 version includes new features like the most awaited password hashing API and providing users the ability to use bcrypt along with loop-controlling generators.

Igor Seletskiy the CEO of CloudLinux has expressed that the availability of PHP selector has made it easier to get access to PHP features. He quoted “PHP is possibly the most widely used aspect of any shared web hosting plan.”

Igor Seletskiy also added “Like the rest of the web hosting community, we are excited to start exploring the new features of PHP version 5.5.

However, many hosting companies and their customers would not usually deploy an Alpha version on a large-scale, server-wide basis.

CloudLinux and PHP Selector make it possible for hosting providers to assign individual accounts their own PHP version without affecting other sites on the same hardware.” Integrating such features in CloudLinux has helped PHP development to become easier and more productive

How To Generate PDF File In CakePHP

TCPDF is a free and open source software one of the widely used PHP libraries in the world. This is because of the fact that it already included in the most popular PHP-based CMS and applications including CakePHPHow to generate pdf file in cakephp.

The installation is pretty straight forward and easy-to-use in CakePHP Framework. Many web applications use this as output documents like invoices, contracts or just web pages in the PDF format.

 

Following are the steps to integrate TCPDF in CakePHP MVC framework.

Step 1:

  • Go to http://www.tcpdf.org and download the latest version of TCPDF zip file.
  • Then unzip the zip file and save under the Vendor folder in cakephp framework(app\vendors)
  • This creates a directory tcpdf there with tcpdf.php and more in it (app\vendors\tcpdf)
  •  You can configure the PDF file Like header Logo Image, Page Title, page Margin etc. in the TCPDF configure file (app->vendors->tcpdf-> tcpdf_config.php)

Step 2:

You can create your own header and footer page of your PDF file. Create a page “xtcpdf.php” under app/vendors with these contents as shown below.

App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF
{
var $xheadertext = 'PDF created using CakePHP and TCPDF';
var $xheadercolor = array(0,0,200);
var $xfootertext = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
var $xfooterfont = PDF_FONT_NAME_MAIN ;
var $xfooterfontsize = 8 ;
/* Change header text and font size as per your requirement in the above variable*******/
function Header()
{
list($r, $b, $g) = $this->xheadercolor;
$this->setY(10); // shouldn't be needed due to page margin, but helas, otherwise it's at the page top
$this->SetFillColor($r, $b, $g);
$this->SetTextColor(0 , 0, 0);
$this->Cell(0,20, '', 0,1,'C', 1);
$this->Text(15,26,$this->xheadertext );
}
function Footer()
{
$year = date('Y');
$footertext = sprintf($this->xfootertext, $year);
$this->SetY(-20);
$this->SetTextColor(0, 0, 0);
$this->SetFont($this->xfooterfont,'',$this->xfooterfontsize);
$this->Cell(0,8, $footertext,'T',1,'C');
}
}
?>

Step 3:

Create your layout under app/views/layouts/pdf.ctp;

header("Content-type: application/pdf");
echo $content_for_layout;
?>

Step 4:

Here is the Controller code which will display output code of generating PDF file;

function view_pdf($id = null) {
if (!$id) {
$this->Session->setFlash('Sorry, there was no PDF selected.');
$this->redirect(array('action'=>'index'), null, true);
}
$this->layout = 'pdf'; //this will use the pdf.ctp layout
$this->render();
}

Step 5:

Create a page under your view directory (app/views/) named as “view_pdf.ctp” (this name can be change as per your controller method) and write your HTML code/PHP code.