How to fix Potential for Information Disclosure in CakePHP

fix Potential for Information Disclosure in CakePHP

The default application skeleton contained a beforeRender() method on the AppController that could potentially lead to unwanted information disclosure in your application. The unsafe default code was present between 3.1.0 and 3.5.0 of the application skeleton.

Risks

The default beforeRender hook would automatically serialize all view variables into JSON/XML if the _serialize view variable was not defined by the controller action. Controller methods that define the _serialize variable would behave correctly and only expose the named variables.

This behavior is triggered by the AppController and ErrorController loading RequestHandlerComponent, which configures the View class to be used based on the client’s Accept header. Then code in AppController::beforeRender() would enable all view variables to be serialized if no variables were explicitly listed.

The default controllers generated by bake set the _serialize view variable. This helps limit the impact, but could still lead to unwanted information exposure if entity classes are not correctly configured.

How to fix

You can fix the potential for information disclosure by modifying your application code. Unfortunately we cannot resolve this problem for you through a patch release of CakePHP or its appplication skeleton.

If you don’t have ErrorController in your src/Controller directory (CakePHP <= 3.3)

If you are using CakePHP 3.3.0 or greater and do not have an ErrorController in your application, you should download an ErrorController and put it into your src/Controller directory.

If you don’t use JSON/XML response based on client requests

  • Remove $this->loadComponent(‘RequestHandler’) from the initialize() method of your AppController and ErrorController.
  • Remove $this->set(‘_serialize’, true); from the beforeRender() of your AppController.

If you use JSON/XML response based on client requests

  • Remove $this->set(‘_serialize’, true); from the beforeRender() of your AppController.
  • Remove $this->set(‘_serialize’, [ (variable names) ]) from all controller actions, that should not return JSON/XML.
  • Add $this->set(‘_serialize’, [ (variable names) ]) explicitly to some actions of your controllers, which you want to return JSON/XML.

While we have no reports of information disclosure in the wild, this issue was found by Kurita Takashi and we felt this was important to disclose.

Read From Official CakePHP blog

How to view records from Database in CakePHP

view records in CakePHP

To view records in CakePHP and To monitor records of database, we need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument. Now, this new instance is used to find records from database using find() method. This method will return all records from the requested table.

Example

Make changes in the config/routes.php file as shown in the following code.

config/routes.php

<?php
   use Cake\Core\Plugin;
   use Cake\Routing\RouteBuilder;
   use Cake\Routing\Router;

   Router::defaultRouteClass('DashedRoute');
   Router::scope('/', function (RouteBuilder $routes) {
      $routes->connect('/users', ['controller' => 'Users', 'action' => 'index']);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();

Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file.

src/controller/UsersController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\ORM\TableRegistry;
   use Cake\Datasource\ConnectionManager;

   class UsersController extends AppController{
      public function index(){
         $users = TableRegistry::get('users');
         $query = $users->find();
         $this->set('results',$query);
      }
   }
?>

Create a directory Users at src/Template, ignore if already created, and under that directory create a View file called index.ctp. Copy the following code in that file.

src/Template/Users/index.ctp

<a href = "add">Add User</a>
<table>
   <tr>
      <td>ID</td>
      <td>Username</td>
      <td>Password</td>
      <td>Edit</td>
      <td>Delete</td>
   </tr>

   <?php
      foreach ($results as $row):
         echo "<tr><td>".$row->id."</td>";
         echo "<td>".$row->username."</td>";
         echo "<td>".$row->password."</td>";
         echo "<td><a href = '".$this->Url->build
         (["controller" => "Users","action"=>"edit",$row->id])."'>Edit</a></td>";
         
         echo "<td><a href = '".$this->Url->build
         (["controller" => "Users","action"=> "delete",$row->id])."'>Delete</a></td></tr>";
      endforeach;
   ?>
</table>

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/users

Output

Upon execution, the above URL will give you the following output.

View a Record in CakePHP

click here to read more cakePHP official website

 

Read more:

How to fix Potential for Information Disclosure in CakePHP

How to Logging Configuration in CakePHP

Logging Configuration in CakePHP

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy − the log() function is provided by the LogTrait, which is the common ancestor for almost all CakePHP classes.

Logging Configuration

We can configure the log in file config/app.php. There is a log section in the file where you can configure logging options as shown in the following screenshot.

Logging Configuration

By default, you will see two log levels − error and debug already configured for you. Each will handle different level of messages.

CakePHP supports various logging levels as shown below −

  • Emergency − System is unusable
  • Alert − Action must be taken immediately
  • Critical − Critical conditions
  • Error − Error conditions
  • Warning − Warning conditions
  • Notice − Normal but significant condition
  • Info − Informational messages
  • Debug − Debug-level messages

Writing to Log file

There are two ways by which we can write in a Log file.

The first is to use the static write() method. The following is the syntax of the static write() method .

Syntax write( integer|string $level , mixed $message , string|array $context[] )
Parameters The severity level of the message being written. The value must be an integer or string matching a known level.

Message content to log.

Additional data to be used for logging the message. The special scope key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the scope key. See CakeLogLog::config() for more information on logging scopes.

Returns boolean
Description Writes the given message and type to all of the configured log adapters. Configured adapters are passed both the $level and $message variables. $level is one of the following strings/values.

The second is to use the log() shortcut function available on any using the LogTrait Calling log() will internally call Log::write()

Example

Make changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘logex’,[‘controller’=>’Logexs’,’action’=>’index’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

Create a LogexController.php file at src/Controller/LogexController.php. Copy the following code in the controller file.

src/Controller/LogexController.php

<?php namespace AppController; use AppControllerAppController; use CakeLogLog; class LogexsController extends AppController{ public function index(){ /*The first way to write to log file.*/ Log::write(‘debug’,”Something didn’t work.”); /*The second way to write to log file.*/ $this->log(“Something didn’t work.”,’debug’); } } ?>

Create a directory Logexs at src/Template and under that directory create a View file called index.ctp. Copy the following code in that file.

src/Template/Logexs/index.ctp

Something is written in log file. Check log file logsdebug.log

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/logex

Output

Upon execution, you will receive the following output.

Logexs

How to Validation Package in CakePHP

Validation Package in CakePHP

Often while making websites we need to validate certain things before processing data further. CakePHP provides validation package to build validators that can validate data with ease.

Validation Methods

CakePHP provides various validation methods in the Validation Class. Some of the most popular of them are listed below.

Syntax Add (string $field, array|string $name, array|CakeValidationValidationRule $rule [] )
Parameters
  • The name of the field from which the rule will be added.
  • The alias for a single rule or multiple rules array.
  • The rule to add
Returns $this
Description Adds a new rule to a field’s rule set. If second argument is an array, then rules list for the field will be replaced with second argument and third argument will be ignored.
Syntax allowEmpty (string $field, boolean|string|callable $when true, string|null $message null)
Parameters
  • The name of the field.
  • Indicates when the field is allowed to be empty. Valid values are true (always), ‘create’, ‘update’. If a callable is passed, then the field will be left empty only when the callback returns true.
  • The message to show if the field is not.
Returns $this
Description Allows a field to be empty.
Syntax alphanumeric (string $field, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add an alphanumeric rule to a field.
Syntax creditCard (string $field, string $type ‘all’, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • The type of cards you want to allow. Defaults to ‘all’. You can also supply an array of accepted card types, for example, [‘mastercard’, ‘visa’, ‘amex’].
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add a credit card rule to a field.
Syntax Email (string $field, boolean $checkMX false, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • Whether or not to check the MX records.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add an email validation rule to a field.
Syntax maxLength (string $field, integer $max, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • The maximum length allowed.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add a string length validation rule to a field.
Syntax minLength (string $field, integer $min, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • The maximum length allowed.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add a string length validation rule to a field.
Syntax notBlank (string $field, string|null $message null, string|callable|null $when null)
Parameters
  • The field you want to apply the rule to.
  • The error message when the rule fails.
  • Either ‘create’ or ‘update’ or a callable that returns true when the validation rule should be applied.
Returns $this
Description Add a notBlank rule to a field.

Tutorials on Generating URLs in CakePHP

Generating URLs in CakePHP

This is a cool feature of CakePHP. Using the generated URLs, we can easily change the structure of URL in the application without modifying the whole code.

url( string|array|null $url null , boolean $full false )

The above function will take two arguments −

  • The first argument is an array specifying any of the following − ‘controller’, ‘action’, ‘plugin’. Additionally, you can provide routed elements or query string parameters. If string, it can be given the name of any valid url string.
  • If true, the full base URL will be prepended to the result. Default is false.

Example

Make Changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use CakeCorePlugin; 
use CakeRoutingRouteBuilder; 
use CakeRoutingRouter; 
Router::defaultRouteClass('DashedRoute'); 
Router::scope('/', function (RouteBuilder $routes){ $routes->connect('/generate',
['controller'=>'Generates','action'=>'index']); }); 
Plugin::routes();

Create a GeneratesController.php file at src/Controller/GeneratesController.php. Copy the following code in the controller file.

src/Controller/GeneratesController.php

<?php namespace AppController; 
use AppControllerAppController; 
use CakeORMTableRegistry; 
use CakeDatasourceConnectionManager; 
class GeneratesController extends AppController{ public function index(){ } } ?>

Create a folder Generates at src/Template and under that folder create a View file called index.ctp. Copy the following code in that file.

src/Template/Generates/index.ctp

This is CakePHP tutorial and this is an example of Generating URLs.

Execute the above example by visiting the following URL −

http://localhost:85/CakePHP/generate

Tutorials on CakePHP Controllers in Details

Tutorials on CakePHP Controllers

Controllers are the ‘C’ in MVC. After routing has been applied and the correct controller has been found, your controller’s action is called. Your controller should handle interpreting the request data, making sure the correct models are called, and the right response or view is rendered. Controllers can be thought of as middle layer between the Model and View. You want to keep your controllers thin, and your models fat. This will help you reuse your code and makes your code easier to test.

Commonly, a controller is used to manage the logic around a single model. For example, if you were building a site for an online bakery, you might have a RecipesController managing your recipes and an IngredientsController managing your ingredients. However, it’s also possible to have controllers work with more than one model. In CakePHP, a controller is named after the primary model it handles.

Your application’s controllers extend the AppController class, which in turn extends the core Controller class. The AppController class can be defined in src/Controller/AppController.php and it should contain methods that are shared between all of your application’s controllers.

Controllers provide a number of methods that handle requests. These are called actions. By default, each public method in a controller is an action, and is accessible from a URL. An action is responsible for interpreting the request and creating the response. Usually responses are in the form of a rendered view, but there are other ways to create responses as well.

AppController

The AppConttroller class is the parent class of all applications’ controllers. This class extends the Controller class of CakePHP. AppController is defined at src/Controller/AppController.php. The file contains the following code.

namespace App\Controller;

use Cake\Controller\Controller;

class AppController extends Controller
{
}

AppController can be used to load components that will be used in every controller of your application. The attributes and methods created in AppController will be available in all controllers that extend it. The initialize() method will be invoked at the end of controller’s constructor to load components.

Controller Actions

The methods in the controller class are called Actions. Actions are responsible for sending appropriate response for browser/user making the request. View is rendered by the name of action, i.e., the name of method in controller.

Example

class RecipesController extends AppController{ public function view($id){ // Action logic goes here. } public function share($customerId, $recipeId){ // Action logic goes here. } public function search($query){ // Action logic goes here. } }

As you can see in the above example, the RecipesController has 3 actions − View, Share, and Search.

Redirecting

For redirecting a user to another action of the same controller, we can use the setAction() method. The following is the syntax for the setAction() method −

Syntax

CakeControllerController::setAction($action, $args…)

The following code will redirect the user to index action of the same controller.

$this->setAction(‘index’);

The following example shows the usage of the above method.

Example

Make changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘/redirectcontroller’,[‘ controller’=>’Redirects’,’action’=>’action1′]); $routes->connect(‘/redirectcontroller2’,[‘ controller’=>’Redirects’,’action’=>’action2′]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

Create a RedirectsController.php file at src/Controller/RedirectsController.php. Copy the following code in the controller file.

src/Controller/RedirectsController.php

<?php namespace AppController; use AppControllerAppController; use CakeORMTableRegistry; use CakeDatasourceConnectionManager; class RedirectsController extends AppController{ public function action1(){ } public function action2(){ echo “redirecting from action2”; $this->setAction(‘action1’); } } ?>

Create a directory Redirects at src/Template and under that directory create a Viewfile called action1.ctp. Copy the following code in that file.

src/Template/Redirects/action1.ctp

This is an example of how to redirect within controller.

Execute the above example by visiting the following URL.

http://localhost:85/CakePHP/redirect-controller

Output

Upon execution, you will receive the following output.

Redirects

Now, visit the following URL − http://localhost:85/CakePHP/redirect-controller2

The above URL will give you the following output.

Redirecting Action2

Loading Models

In CakePHP, a model can be loaded using the loadModel() method. The following is the syntax for the loadModel() method.

Syntax

CakeControllerController::loadModel(string $modelClass, string $type)

There are two arguments to the above function −

  • The first argument is the name of model class.
  • The second argument is the type of repository to load.

Example

If you want to load Articles model in a controller, then it can be loaded by writing the following line in controller’s action.

$this->loadModel(‘Articles’);

Read more from CakePHP Official Documentation – Controllers 3.7

How to Manage Cookie in CakePHP

How to Manage Cookie in CakePHP

Handling Cookie with CakePHP is easy and secure. There is a CookieComponent class which is used for managing Cookie. The class provides several methods for working with Cookies.

Write Cookie

The write() method is used to write cookie. Following is the syntax of the write() method.

CakeControllerComponentCookieComponent::write(mixed $key, mixed $value = null)

The write() method will take two arguments, the name of cookie variable ($key), and the value of cookie variable ($value).

Example

$this->Cookie->write(‘name’, ‘John’);

We can pass array of name, values pair to write multiple cookies.

Read Cookie

The read() method is used to read cookie. Following is the syntax of the read() method.

CakeControllerComponentCookieComponent::read(mixed $key = null)

The read() method will take one argument, the name of cookie variable ($key).

Example

echo $this->Cookie->read(‘name’);

Check Cookie

The check() method is used to check whether a key/path exists and has a non-null value. Following is the syntax of the check() method.

CakeControllerComponentCookieComponent::check($key)

Example

echo $this->Cookie->check(‘name’);

Delete Cookie

The delete() method is used to delete cookie. Following is the syntax of the delete() method.

CakeControllerComponentCookieComponent::delete(mixed $key)

The delete() method will take one argument, the name of cookie variable ($key) to delete.

Example 1

$this->Cookie->delete(‘name’);

Example 2

Make changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass(‘DashedRoute’); Router::scope(‘/’, function (RouteBuilder $routes) { $routes->connect(‘cookie/write’,[‘controller’=>’Cookies’,’action’=>’write_cookie’]); $routes->connect(‘cookie/read’,[‘controller’=>’Cookies’,’action’=>’read_cookie’]); $routes->connect(‘cookie/check’,[‘controller’=>’Cookies’,’action’=>’check_cookie’]); $routes->connect(‘cookie/delete’,[‘controller’=>’Cookies’,’action’=>’delete_cookie’]); $routes->fallbacks(‘DashedRoute’); }); Plugin::routes();

Create a CookiesController.php file at src/Controller/CookiesController.php. Copy the following code in the controller file.

src/Controller/Cookies/CookiesController.php

<?php namespace AppController; use AppControllerAppController; use CakeControllerComponentCookieComponent; class CookiesController extends AppController{ public $components = array(‘Cookie’); public function writeCookie(){ $this->Cookie->write(‘name’, ‘John’); } public function readCookie(){ $cookie_val = $this->Cookie->read(‘name’); $this->set(‘cookie_val’,$cookie_val); } public function checkCookie(){ $isPresent = $this->Cookie->check(‘name’); $this->set(‘isPresent’,$isPresent); } public function deleteCookie(){ $this->Cookie->delete(‘name’); } } ?>

Create a directory Cookies at src/Template and under that directory create a View file called write_cookie.ctp. Copy the following code in that file.

src/Template/Cookie/write_cookie.ctp

The cookie has been written.

Create another View file called read_cookie.ctp under the same Cookies directory and copy the following code in that file.

src/Template/Cookie/read_cookie.ctp

The value of the cookie is: <?php echo $cookie_val; ?>

Create another View file called check_cookie.ctp under the same Cookies directory and copy the following code in that file.

src/Template/Cookie/check_cookie.ctp

<?php if($isPresent): ?> The cookie is present. <?php else: ?> The cookie isn’t present. <?php endif; ?>

Create another View file called delete_cookie.ctp under the same Cookies directory and copy the following code in that file.

src/Template/Cookie/delete_cookie.ctp

The cookie has been deleted.

Output

Execute the above example by visiting the following URL − http://localhost:85/CakePHP/cookie/write

This will help you write data in cookie.

Cookies

Visit the following URL to read cookie datahttp://localhost:85/CakePHP/cookie/read

CakePHP Cookies

Visit the following URL to check cookie datahttp://localhost:85/CakePHP/cookie/check

CakePHP Cookies

Visit the following URL to delete cookie datahttp://localhost:85/CakePHP/cookie/delete

Cookies Deleted