CakePHP – Security

CakePHP – Security ”; Previous Next Security is another important feature while building web applications. It assures the users of the website that, their data is secured. CakePHP provides some tools to secure your application. Encryption and Decryption Security library in CakePHP provides methods, by which we can encrypt and decrypt data. Following are the two methods, which are used for the same purpose. static CakeUtilitySecurity::encrypt($text, $key, $hmacSalt = null) static CakeUtilitySecurity::decrypt($cipher, $key, $hmacSalt = null) The encrypt method will take text and key as the argument to encrypt data and the return value will be the encrypted value with HMAC checksum. To hash a data, hash() method is used. Following is the syntax of the hash() method. static CakeUtilitySecurity::hash($string, $type = NULL, $salt = false) CSRF CSRF stands for Cross Site Request Forgery. By enabling the CSRF Component, you get protection against attacks. CSRF is a common vulnerability in web applications. It allows an attacker to capture and replay a previous request, and sometimes submit data requests using image tags or resources on other domains. The CSRF can be enabled by simply adding the CsrfComponent to your components array as shown below − public function initialize(): void { parent::initialize(); $this->loadComponent(”Csrf”); } The CsrfComponent integrates seamlessly with FormHelper. Each time you create a form with FormHelper, it will insert a hidden field containing the CSRF token. While this is not recommended, you may want to disable the CsrfComponent on certain requests. You can do so by using the controller’s event dispatcher, during the beforeFilter() method. public function beforeFilter(Event $event) { $this->eventManager()->off($this->Csrf); } Security Component Security Component applies tighter security to your application. It provides methods for various tasks like − Restricting which HTTP methods your application accepts − You should always verify the HTTP method, being used before executing side-effects. You should check the HTTP method or use CakeNetworkRequest::allowMethod() to ensure the correct HTTP method is used. Form tampering protection − By default, the SecurityComponent prevents users from tampering with forms in specific ways. The SecurityComponent will prevent the following things − Unknown fields cannot be added to the form. Fields cannot be removed from the form. Values in hidden inputs cannot be modified. Requiring that SSL be used − All actions to require a SSL- secured Limiting cross controller communication − We can restrict which controller can send request to this controller. We can also restrict which actions can send request to this controller’s action. Example Make changes in the config/routes.php file as shown in the following program. config/routes.php <?php use CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope(”/”, function (RouteBuilder $builder) { $builder->registerMiddleware(”csrf”, new CsrfProtectionMiddleware([ ”httpOnly” => true, ])); $builder->applyMiddleware(”csrf”); //$builder->connect(”/pages”, [”controller”=>”Pages”,”action”=>”display”, ”home”]); $builder->connect(”login”,[”controller”=>”Logins”,”action”=>”index”]); $builder->fallbacks(); }); Create a LoginsController.php file at src/Controller/LoginsController.php. Copy the following code in the controller file. src/Controller/LoginsController.php <?php namespace AppController; use AppControllerAppController; class LoginsController extends AppController { public function initialize() : void { parent::initialize(); $this->loadComponent(”Security”); } public function index(){ } } ?> Create a directory Logins at src/Template and under that directory create a View file called index.php. Copy the following code in that file. src/Template/Logins/index.php <?php echo $this->Form->create(NULL,array(”url”=>”/login”)); echo $this->Form->control(”username”); echo $this->Form->control(”password”); echo $this->Form->button(”Submit”); echo $this->Form->end(); ?> Execute the above example by visiting the following URL − http://localhost/cakephp4/login Output Upon execution, you will receive the following output. Print Page Previous Next Advertisements ”;

CakePHP – Quick Guide

CakePHP – Quick Guide ”; Previous Next CakePHP – Overview CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks. Advantages of CakePHP The advantages of using CakePHP are listed below − Open Source MVC Framework Templating Engine Caching Operations Search Engine Friendly URLs Easy CRUD (Create, Read, Update, Delete) Database Interactions. Libraries and Helpers Built-in Validation Localisation Email, Cookie, Security, Session, and Request Handling Components View Helpers for AJAX, JavaScript, HTML Forms and More CakePHP Request Cycle The following illustration describes how a Request Lifecycle in CakePHP works − A typical CakePHP request cycle starts with a user requesting a page or resource in your application. At high level, each request goes through the following steps − The webserver rewrite rules direct the request to webroot / index.php. Your application’s autoloader and bootstrap files are executed. Any dispatch filters that are configured can handle the request, and optionally generate a response. The dispatcher selects the appropriate controller and action based on routing rules. The controller’s action is called and the controller interacts with the required Models and Components. The controller delegates response creation to the View to generate the output resulting from the model data. The view uses Helpers and Cells to generate the response body and headers. The response is sent back to the client. CakePHP – Installation In this chapter, we will show the installation of CakePHP 4.0.3. The minimum PHP version that we need to install is PHP 7.3. You need to have PHP 7.3 and Composer to be installed before starting the installation of cakePHP. For Windows users, install or update WAMP server with PHP version > 7.3. Go to www.wampserver.com/en/download-wampserver-64bits/ and install it. For Linux users, kindly refer Tutorials Point website which is available at www.tutorialspoint.com/php7/php7_installation_linux.htm for installation of PHP . Installing Composer Go to composer at https://getcomposer.org/download/ and click on download as per the operating system (OS) of your computer and install composer on your system. Add the location to PATH variable for windows users, so that you can use composer from any directory. Once you are done installing composer, let us now start to install CakePHP. Installing CakePHP Go to the folder where wamp is located for windows users and in www/ folder, create a folder cakephp4/. For Linux users, create the folder var/www/html/ and then create folder cakephp4/. cakephp4/ is the folder where we are going to install CakePHP. Use composer to execute the following command − composer create-project –prefer-dist cakephp/app:4.0.3 cakephp4 This is what you should see, when the command executes − Once the installation is complete, use localhost to open your project in browser. The Path for the same is http://localhost/cakephp. CakePHP – Folder Structure Here, we will learn about the Folder structure and the Naming Convention in CakePHP. Let us begin by understanding the Folder structure. Folder Structure Take a look at the following screenshot. It shows the folder structure of CakePHP. The following table describes the role of each folder in CakePHP − Sr.No Folder Name & Description 1 bin The bin folder holds the Cake console executables. 2 config The config folder holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here. 3 logs The logs folder normally contains your log files, depending on your log configuration. 4 plugins The plugins folder is where the Plugins of your application uses are stored. 5 resources The files for internationalization in the respective locale folder will be stored here. E.g. locales/en_US. 6 src The src folder will be where you work your magic. It is where your application’s files will be placed and you will do most of your application development. Let’s look a little closer at the folders inside src. Console − Contains the console commands and console tasks for your application. Controller − Contains your application’s controllers and their components. Model − Contains your application’s tables, entities and behaviors. View Presentational classes are placed here: cells, helpers, and template files. 7 templates Template Presentational files are placed here: elements, error pages, layouts, and view template files. 8 tests The tests folder will be where you put the test cases for your application. 9 tmp The tmp folder is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions and sometimes session information. 10 vendor The vendor folder is where CakePHP and other application dependencies will be installed. Make a personal commitment not to edit files in this folder. We can’t help you, if you’ve modified the core. 11 webroot The webroot directory is the public document root of your application. It contains all the files you want to be publically reachable. Naming Convention Naming convention is not something mandatory to be followed, but is a good coding practice and will be very helpful as your project goes big. Controller Convention The controller class name has to be plural, PascalCased and the name has to end with Controller. For example, for Students class the name of the controller can be StudentsController. Public methods on Controllers are often exposed as ‘actions’ accessible through a web browser. For example, the /users /view maps to the view() method of the UsersController out of the box. Protected or private methods cannot be accessed with routing. File and Class Name Convention Mostly, we have seen that our class name file name is almost the same. This is similar in cakephp. For example, the class StudentsController will have the file named as StudentsController.php. The files have to be saved as the module name and in the respective folders in app folder. Database Conventions The tables used for CakePHP models, mostly have names plural with underscore. For example, student_details, student_marks. The field name has an underscore, if it is made up of two

CakePHP – Date and Time

CakePHP – Date and Time ”; Previous Next To work with date and time in cakephp4, we are going to make use of the available FrozenTime class. To work with date and time, include the class in your controller use CakeI18nFrozenTime; Let us work, on an example and display date and time, using FrozenTime class. Example Make Changes in the config/routes.php file as shown in the following program. config/routes.php <?php use CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope(”/”, function (RouteBuilder $builder) { $builder->registerMiddleware(”csrf”, new CsrfProtectionMiddleware([ ”httpOnly” => true, ])); $builder->applyMiddleware(”csrf”); //$builder->connect(”/pages”,[”controller”=>”Pages”,”action”=>”display”, ”home”]); $builder->connect(”datetime”,[”controller”=>”Dates”,”action”=>”index”]); $builder->fallbacks(); }); Create a DatesController.php file at src/Controller/DatesController.php. Copy the following code in the controller file. Ignore if already created. src/Controller/DatesController.php <?php namespace AppController; use AppControllerAppController; use CakeI18nFrozenTime; class DatesController extends AppController{ public function index(){ $time = FrozenTime::now(); $now = FrozenTime::parse(”now”); $_now = $now->i18nFormat(”yyyy-MM-dd HH:mm:ss”); $this->set(”timenow”, $_now); $now = FrozenTime::parse(”now”); $nice = $now->nice(); $this->set(”nicetime”, $nice); $hebrewdate = $now->i18nFormat(IntlDateFormatter::FULL, null, ”en-IR@calendar=hebrew”); $this->set(“hebrewdate”,$hebrewdate); $japanesedate = $now->i18nFormat(IntlDateFormatter::FULL, null, ”en-IR@calendar=japanese”); $this->set(“japanesedate”,$japanesedate); $time = FrozenTime::now(); $this->set(“current_year”,$time->year); $this->set(“current_month”,$time->month); $this->set(“current_day”,$time->day); } } ?> Create a directory Dates at src/Template and under that directory create a View file called index.php. Copy the following code in that file. src/Template/Dates/index.php <?php echo “The Current date and time is = “.$timenow; echo “<br/>”; echo “Using nice format available = “.$nicetime; echo “<br/>”; echo “Date and Time as per Hebrew Calender =” .$hebrewdate; echo “<br/>”; echo “Date and Time as per Japanese Calender =” .$japanesedate; echo “<br/>”; echo “Current Year = “.$current_year; echo “<br/>”; echo “Current Month = “.$current_month; echo “<br/>”; echo “Current Day = “.$current_day; ?> Execute the above example by visiting the following URL − http://localhost/cakephp4/datetime Output When you run the code, you will see the following output − Print Page Previous Next Advertisements ”;

CakePHP – Delete a Record

CakePHP – Delete a Record ”; Previous Next To delete a record in database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using the get() method. The get() method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to delete. Call the get() method with this new instance and pass the primary key to find a record which will be saved in another instance. Use the TableRegistry class’s instance to call the delete method to delete record from database. Example Make changes in the config/routes.php file as shown in the following code. config/routes.php <?php use CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope(”/”, function (RouteBuilder $builder) { $builder->registerMiddleware(”csrf”, new CsrfProtectionMiddleware([ ”httpOnly” => true, ])); $builder->applyMiddleware(”csrf”); //$builder->connect(”/pages”,[”controller”=>”Pages”,”action”=>”display”, ”home”]); $builder->connect(”/users/delete”, [”controller” => ”Users”, ”action” => ”delete”]); $builder->fallbacks(); }); Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file. src/controller/UsersController.php <?php namespace AppController; use AppControllerAppController; use CakeORMTableRegistry; use CakeDatasourceConnectionManager; class UsersController extends AppController{ public function index(){ $users = TableRegistry::get(”users”); $query = $users->find(); $this->set(”results”,$query); } public function delete($id){ $users_table = TableRegistry::get(”users”); $users = $users_table->get($id); $users_table->delete($users); echo “User deleted successfully.”; $this->setAction(”index”); } } ?> Just create an empty View file under Users directory called delete.ctp. src/Template/Users/delete.ctp Create a directory Users at src/Template, ignore if already created, and under that directory create a Viewfile 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 and click on Delete link to delete record. http://localhost:85/CakePHP/users Output After visiting the above URL and clicking on the Delete link, you will receive the following output where you can delete record. Click on Delete link to delete the record. Print Page Previous Next Advertisements ”;

CakePHP – View a Record

CakePHP – View a Record ”; Previous Next To view records of database, we first 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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope(”/”, function (RouteBuilder $builder) { $builder->registerMiddleware(”csrf”, new CsrfProtectionMiddleware([ ”httpOnly” => true, ])); $builder->applyMiddleware(”csrf”); //$builder->connect(”/pages”,[”controller”=>”Pages”,”action”=>”display”, ”home”]); $builder->connect(”/users”, [”controller” => ”Users”, ”action” => ”index”]); $builder->fallbacks(); }); Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file. src/controller/UsersController.php <?php namespace AppController; use AppControllerAppController; use CakeORMTableRegistry; use CakeDatasourceConnectionManager; 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.php. 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/cakephp4/users Output Upon execution, the above URL will give you the following output. Print Page Previous Next Advertisements ”;

CakePHP – Installation

CakePHP – Installation ”; Previous Next In this chapter, we will show the installation of CakePHP 4.0.3. The minimum PHP version that we need to install is PHP 7.3. You need to have PHP 7.3 and Composer to be installed before starting the installation of cakePHP. For Windows users, install or update WAMP server with PHP version > 7.3. Go to www.wampserver.com/en/download-wampserver-64bits/ and install it. For Linux users, kindly refer Tutorials Point website which is available at www.tutorialspoint.com/php7/php7_installation_linux.htm for installation of PHP . Installing Composer Go to composer at https://getcomposer.org/download/ and click on download as per the operating system (OS) of your computer and install composer on your system. Add the location to PATH variable for windows users, so that you can use composer from any directory. Once you are done installing composer, let us now start to install CakePHP. Installing CakePHP Go to the folder where wamp is located for windows users and in www/ folder, create a folder cakephp4/. For Linux users, create the folder var/www/html/ and then create folder cakephp4/. cakephp4/ is the folder where we are going to install CakePHP. Use composer to execute the following command − composer create-project –prefer-dist cakephp/app:4.0.3 cakephp4 This is what you should see, when the command executes − Once the installation is complete, use localhost to open your project in browser. The Path for the same is http://localhost/cakephp. Print Page Previous Next Advertisements ”;

CakePHP – Form Handling

CakePHP – Form Handling ”; Previous Next CakePHP provides various in built tags to handle HTML forms easily and securely. Like many other PHP frameworks, major elements of HTML are also generated using CakePHP. Following are the various functions used to generate HTML elements. The following functions are used to generate select options − Syntax _selectOptions( array $elementsarray(), array $parentsarray(), boolean $showParentsnull, array $attributesarray() ) Parameters Elements to format Parents for OPTGROUP Whether to show parents HTML attributes Returns array Description Returns an array of formatted OPTION/OPTGROUP elements The following functions are used to generate HTML select element. Syntax select( string $fieldName, array $options array(), array $attributes array() ) Parameters Name attribute of the SELECT Array of the OPTION elements (as ”value”=>”Text” pairs) to be used in the SELECT element. Returns Formatted SELECT element. Description Returns a formatted SELECT element. The following functions are used to generate button on HTML page. Syntax Button(string $title, array $optionsarray() ) Parameters The button”s caption. Not automatically HTML encoded. Array of options and HTML attributes Returns HTML button tag. Description Creates a <button> tag. The type attribute defaults to type=”submit”. You can change it to a different value by using $options[”type”]. The following functions are used to generate checkbox on HTML page. Syntax Checkbox(string $fieldName, array $optionsarray() ) Parameters Name of a field, like this “Modelname.fieldname” Array of HTML attributes. Possible options are value, checked, hiddenField, disabled, default. Returns An HTML text input element. Description Creates a checkbox input widget. The following functions are used to create form on HTML page. Syntax create( mixed $modelnull , array $optionsarray() ) Parameters The model name for which the form is being defined. Should include the plugin name for plugin models. e.g. ContactManager.Contact. If an array is passed and $options argument is empty, the array will be used as options. If false, no model is used. An array of html attributes and options. Possible options are type, action, url, default, onsubmit, inputDefaults, encoding. Returns A formatted opening FORM tag. Description Returns an HTML FORM element. The following functions are used to provide file uploading functionality on HTML page. Syntax file(string $fieldName, array $optionsarray() ) Parameters Name of a field, in the form “Modelname.fieldname” Array of HTML attributes. Returns A generated file input. Description Creates file input widget. The following functions are used to create hidden element on HTML page. Syntax hidden( string $fieldName , array $optionsarray() ) Parameters Name of a field, in the form of “Modelname.fieldname” Array of HTML attributes. Returns A generated hidden input Description Creates a hidden input field The following functions are used to generate input element on HTML page. Syntax Input(string $fieldName , array $options array() ) Parameters This should be “Modelname.fieldname” Each type of input takes different options Returns Completed form widget Description Generates a form input element complete with label and wrapper div The following functions are used to generate radio button on HTML page. Syntax Radio(string $fieldName , array $optionsarray() , array $attributesarray() ) Parameters Name of a field, like this “Modelname.fieldname” Radio button options array. Array of HTML attributes, and special attributes above. Returns Completed radio widget set Description Creates a set of radio widgets. Will create a legend and fieldset by default. Use $options to control this. The following functions are used to generate submit button on HTML page. Syntax Submit(string $caption null, array $options array() ) Parameters The label appearing on the button OR if string contains :// or the extension .jpg, .jpe, .jpeg, .gif, .png. Use an image if the extension exists, AND the first character is /, image is relative to webroot, OR if the first character is not /, image is relative to webroot/img. Array of options. Possible options are div, before, after, type etc. Returns An HTML submit button Description Creates a submit button element. This method will generate <input /> elements that can be used to submit, and reset forms by using $options. Image submits can be created by supplying an image path for $caption. The following functions are used to generate textarea element on HTML page. Syntax Textarea(string $fieldName , array $options array() ) Parameters Name of a field, in the form “Modelname.fieldname” Array of HTML attributes, special option like escape Returns A generated HTML text input element Description Creates a textarea widget Example Make changes in the config/routes.php file as shown in the following code. config/routes.php <?php use CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope(”/”, function (RouteBuilder $builder) { $builder->registerMiddleware(”csrf”, new CsrfProtectionMiddleware([ ”httpOnly” => true, ])); $builder->applyMiddleware(”csrf”); //$builder->connect(”/pages”,[”controller”=>”Pages”,”action”=>”display”, ”home”]); $builder->connect(”register”,[”controller”=>”Registrations”,”action”=>”index”]); $builder->fallbacks(); }); Create a RegistrationsController.php file at src/Controller/RegistrationsController.php. Copy the following code in the controller file. src/Controller/RegistrationsController.php <?php namespace AppController; use AppControllerAppController; class RegistrationsController extends AppController{ public function index(){ $country = array(”India”,”United State of America”,”United Kingdom”); $this->set(”country”,$country); $gender = array(”Male”,”Female”); $this->set(”gender”,$gender); } } ?> Create a directory Registrations at src/Template and under that directory, create a View file called index.php. Copy the following code in that file. src/Template/Registrations/index.php <?php echo $this->Form->create(NULL,array(”url”=>”/register”)); echo ”<label for=”country”>Country</label>”; echo $this->Form->select(”country”,$country); echo ”<label for=”gender”>Gender</label>”; echo $this->Form->radio(”gender ”,$gender); echo ”<label for=”address”>Address</label>”; echo $this->Form->textarea(”address”); echo $this->Form->file(”profilepic”); echo ”<div>”.$this->Form->checkbox(”terms”). ”<label for=”country”>Terms &mp; Conditions</label></div>”; echo $this->Form->button(”Submit”); echo $this->Form->end(); ?> Execute the above example by visiting the following URL − http://localhost/cakephp4/register Output Upon execution, you will receive the following output. Print Page Previous Next Advertisements ”;

CakePHP – Cookie Management

CakePHP – Cookie Management ”; Previous Next 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. To work with cookies, add this 2 classes to your controller − use CakeHttpCookieCookie; use CakeHttpCookieCookieCollection; The cookie object has to be created first to register a cookie. $cookie = new Cookie(name,value,expiration time,path,domain); The name and value are mandatory and others are optional param. Write Cookie Following is the syntax to write a cookie. $cookie = new Cookie(name,value,expiration time,path,domain); The cookie created has to be added to cookieCollection as shown below − $cookie = new Cookie(”name”,”XYZ”); $cookies = new CookieCollection([$cookie]); If the cookie collection object is already created, the rest of the cookies can be added as shown below − $cookies = $cookies->add($cookie); Read Cookie To read cookie make use of get() method from cookiecollection. Syntax The syntax for read cookie is as follows − CakeHttpCookieCookieCollection::get($name) This will return you cookiecollection Interface, to get the value of the cookie, you will have to call the method getValue(). CakeHttpCookieCookieCollection Interface::getValue() Check Cookie The has() method from cookieCollection will tell you, if the cookie is present or not. CakeHttpCookieCookieCollection::has($name) Example echo $isPresent = $this->cookies->has(”name”); Delete Cookie The remove() method is used to delete cookie. Following is the syntax of the remove() method. CakeHttpCookieCookieCollection::remove($name) The remove() method will take one argument, the name of cookie variable ($name) to delete. Example 1 $test = $this->cookies->remove(”name”); Example 2 Make changes in the config/routes.php file as shown in the following program. config/routes.php <?php use CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope(”/”, function (RouteBuilder $builder) { $builder->registerMiddleware(”csrf”, new CsrfProtectionMiddleware([ ”httpOnly” => true, ])); $builder->applyMiddleware(”csrf”); //$builder->connect(”/pages”,[”controller”=>”Pages”,”action”=>”display”, ”home”]); $builder->connect(”cookie/testcookies”,[”controller”=>”Cookies”,”action”=>”testCookies”]); $builder->fallbacks(); }); 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 CakeHttpCookieCookie; use CakeHttpCookieCookieCollection; class CookiesController extends AppController{ public $cookies; public function testCookies() { $cookie = new Cookie(”name”,”XYZ”); $this->cookies = new CookieCollection([$cookie]); $cookie_val = $this->cookies->get(”name”); $this->set(”cookie_val”,$cookie_val->getValue()); $isPresent = $this->cookies->has(”name”); $this->set(”isPresent”,$isPresent); $this->set(”count”, $this->cookies->count()); $test = $this->cookies->remove(”name”); $this->set(”count_afterdelete”, $test->count()); } } ?> Create a directory Cookies at src/Template and under that directory create a View file called test_cookies.php. Copy the following code in that file. src/Template/Cookie/test_cookies.php The value of the cookie is: <?php echo $cookie_val; ?> <br/> <?php if($isPresent): ?> The cookie is present. <?php else: ?> The cookie isn”t present. <?php endif; ?> <br/> <?php echo “The count of cookie before delete is :” .$count; ?> <br/> <?php echo “The count of cookie after delete is :” .$count_afterdelete; ?> Output Execute the above example by visiting the following URL − http://localhost/cakephp4/cookie/testcookies Print Page Previous Next Advertisements ”;

CakePHP – Pagination

CakePHP – Pagination ”; Previous Next If we want to show a set of data that is huge, we can use pagination and this feature is available with cake php 4 which is very easy to use. We have a table titled “articles” with following data − Let us use pagination to display the data in the form of pages, instead of showing them all together. Example Make Changes in the config/routes.php file as shown in the following program. config/routes.php <?php use CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope(”/”, function (RouteBuilder $builder) { $builder->registerMiddleware(”csrf”, new CsrfProtectionMiddleware([ ”httpOnly” => true, ])); $builder->applyMiddleware(”csrf”); //$builder->connect(”/pages”,[”controller”=>”Pages”,”action”=>”display”, ”home”]); $builder->connect(”posts”,[”controller”=>”Posts”,”action”=>”index”]); $builder->fallbacks(); }); Create a PostsController.php file at src/Controller/PostsController.php. Copy the following code in the controller file. Ignore, if already created. src/Controller/PostsController.php <?php namespace AppController; use AppControllerAppController; class PostsController extends AppController { public function index(){ $this->loadModel(”articles”); $articles = $this->articles->find(”all”)->order([”articles.id ASC”]); $this->set(”articles”, $this->paginate($articles, [”limit”=> ”3”])); } } ?> The data from articles table is fetched using − $this->loadModel(”articles”); $articles = $this->articles->find(”all”)->order([”articles.id ASC”]); To apply pagination and we would show the data with 3 per records and the same is done as follows − $this->set(”articles”, $this->paginate($articles, [”limit”=> ”3”])); This is enough to activate pagination on the articles tables. Create a directory Posts at src/Template and under that directory create a Viewfile called index.php. Copy the following code in that file. src/Template/Posts/index.php <div> <?php foreach ($articles as $key=>$article) {?> <a href=”#”> <div> <p><?= $article->title ?> </p> <p><?= $article->details ?></p> </div> </a> <br/> <?php } ?> <ul class=”pagination”> <?= $this->Paginator->prev(“<<“) ?> <?= $this->Paginator->numbers() ?> <?= $this->Paginator->next(“>>”) ?> </ul> </div> The pagination for the list of pages is done as follows − <ul class=”pagination”> <?= $this->Paginator->prev(“<<“) ?> <?= $this->Paginator->numbers() ?> <?= $this->Paginator->next(“>>”) ?> </ul> Execute the above example by visiting the following URL − http://localhost/cakephp4/posts Output When you run the code, you will see the following output − Click on the numbers below, to switch to next page, or use the next or previous button. For example You will see that page=2 is appended to the page url in the browser. Print Page Previous Next Advertisements ”;

CakePHP – File upload

CakePHP – File upload ”; Previous Next To work on file upload we are going to use the form helper. Here, is an example for file upload. Example Make Changes in the config/routes.php file, as shown in the following program. config/routes.php <?php use CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope(”/”, function (RouteBuilder $builder) { $builder->registerMiddleware(”csrf”, new CsrfProtectionMiddleware([ ”httpOnly” => true, ])); $builder->applyMiddleware(”csrf”); //$builder->connect(”/pages”,[”controller”=>”Pages”,”action”=>”display”, ”home”]); $builder->connect(”fileupload”,[”controller”=>”Files”,”action”=>”index”]); $builder->fallbacks(); }); Create a FilesController.php file at src/Controller/FilesController.php. Copy the following code in the controller file. Ignore, if already created. Create uploads/ directory in src/. The files uploaded will be saved in uploads/ folder. src/Controller/FilesController.php <?php namespace AppController; use AppControllerAppController; use CakeViewHelperFormHelper; class FilesController extends AppController { public function index(){ if ($this->request->is(”post”)) { $fileobject = $this->request->getData(”submittedfile”); $uploadPath = ”../uploads/”; $destination = $uploadPath.$fileobject->getClientFilename(); // Existing files with the same name will be replaced. $fileobject->moveTo($destination); } } } ?> Create a directory Files at src/Template and under that directory create a View file called index.php. Copy the following code in that file. src/Template/Files/index.php <?php echo $this->Form->create(NULL, [”type” => ”file”]); echo $this-&gtl;Form->file(”submittedfile”); echo $this->Form->button(”Submit”); echo $this->Form->end(); $uploadPath =”../uploads/”; $files = scandir($uploadPath, 0); echo “Files uploaded in uploads/ are:<br/>”; for($i = 2; $i < count($files); $i++) echo “File is – “.$files[$i].”<br>”; ?> The files saved in uploads/ folder is listed for the user. Execute the above example by visiting the following URL − http://localhost/cakephp4/fileupload − Output When you execute the above code, you should see the following output − Print Page Previous Next Advertisements ”;