Using CakePHP Logging Scope

Undoubtedly logging is most important part of an application to debugging, analyzing, measuring performance. So often times we want to handle different logging behavior for different components of our application. Assume that you are developing an e-commerce website and you want to handle logging cart & payment component differently.

So in that way, each log of the different component will store into a different file. So debugging will be easier than generic logging. To do that open config/bootstrap.php file and copy pastes this snippet.

Then you can implement this scope like this way (From controller & model).

Log::error('Product is not added into cart due to internal error', ['scope' => ['cart']]);
Log::emergency('Payment is not received', ['scope' => ['payments']]);

 

Array Chunk based on Key Value in PHP

Sometimes programmer needs to chunk or grouping array based on the array key value. Look at the below code snippet, here I have a multidimensional array, and I want to group all same elements of each category.

OUTPUT:

array (
  'php' => 
  array (
    0 => 
    array (
      'category' => 'php',
      'post_id' => 100,
    ),
    1 => 
    array (
      'category' => 'php',
      'post_id' => 102,
    ),
    2 => 
    array (
      'category' => 'php',
      'post_id' => 104,
    ),
  ),
  'html' => 
  array (
    0 => 
    array (
      'category' => 'html',
      'post_id' => 101,
    ),
    1 => 
    array (
      'category' => 'html',
      'post_id' => 104,
    ),
  ),
  'js' => 
  array (
    0 => 
    array (
      'category' => 'js',
      'post_id' => 103,
    ),
  ),
)

Depreciation Notice Error in Phpmyadmin With Ubuntu16.04

If you see the error notice properly you can understand what does it means. This error notice means some of your PHP has old constructors. So if you replace these old constructors with new constructor then the problem will be solved.

Depreciation Notice Error in Phpmyadmin With Ubuntu16.04

 

To do this, open streems.php file by this command.

sudo gedit /usr/share/php/php-gettext/streams.php

 StringReader Error: To find it go to line number 52 then

//Replace this line
function StringReader ($str='') {

//with
function __construct($str='') {

 

FileReader Error: To find it go to line number 90 then

//Change this
function FileReader ($str='') {

//To
function __construct($str='') {

 

CacheFileReader Error: To find it go to line number 146 then

//Change this
function CacheFileReader ($str='') {

//To
function __construct($str='') {

Then save & close the file. After that open gettext.php file by this command.

sudo gedit /usr/share/php/php-gettext/gettext.php

Go to line number 101 then

// Replace this line
function gettext_reader($Reader, $enable_cache = true) {

//With
function __construct($Reader, $enable_cache = true) {

CakePHP Auth Allow to Specific Actions of Specific Controllers

It’s a common problem to CakePHP developer to auth allow to specific actions of a specific controller. Especially to newbies developer of CakePHP. Honestly, it’s really easy but little tricky. So this article is for whom, who looking for CakePHP auth allow to specific actions of specific controllers.

Assume you have three controllers ClientsController.php, JobsController.php and HomeController.php. Now you want to access:

  • index() action from all controller
  • lists() action of  ClientsController.php controller
  • jobs() action of JobsController.php controller
  • home() action of HomeController.php controller

To accomplish this goal open AuthController.php file and add these following line.

public function beforeFilter(Event $event)
{
   $this->Auth->allow(array('index'));
}

 

Then open ClientsController.php file and add these following line.

public function beforeFilter(Event $event)
{
   parent::beforeFilter($event);
   $this->Auth->allow(array('lists'));
}

 

Then open JobsController.php file and add these following line.

public function beforeFilter(Event $event)
{
   parent::beforeFilter($event);
   $this->Auth->allow(array('jobs'));
}

 

Then open HomeController.php file and add these following line.

public function beforeFilter(Event $event)
{
   parent::beforeFilter($event);
   $this->Auth->allow(array('home'));
}

In this way, you can auth allow to specific actions of specific controllers.

Catch PHP Output Buffering Data Over jQuery AJAX

From last few day’s I was deeply engaged with Output Buffering. I had to catch PHP output buffering responsive over AJAX request. And now I am here to sharing a sample script to catch PHP output buffering data over jQuery AJAX.

Live Demo

 

Implement Non-Blocking Session in PHP

As we all know Session is the most important component in the web application. Before describing the non-blocking session, I would like too little introduce about PHP Session. The session is the way to store data for each user against a unique session ID. By default, session usages file to storing the session data. When session_start() is called then PHP creates a unique identifier number for that particular session. And sent that number to users browser to save that number. Contiguous create a new file with the same name of the unique identification number. And browser will use that unique identification number to communicate with that server. To know more about How Does PHP Session Works read this article.

Non-Blocking Session

What Does Session Locking:

When web server getting the concurrent request which involves with PHP Session. Then the first request will engage the Session file to work with it and locked that Session file. And rest of the request who also have to engage with Session, they will be blocked (waiting for the unlock of the Session file). When the first request did its activities then release the Session file and then the second request will engage with The session. And this happened until the last request is served. This is actually called Session Looking. To understand more about Session Locking read this article.

Non-Blocking Session:

To improve the application performance we need to avoid this problem. To avoid the PHP Session blocking we can start the session and then close the session. This will unlock the session file and allow the remaining requests to engage with Session, even before the previous request has served.

session_write_close(); function need to call to close the session.

This trick works great if you do not need to read anything in session while your another process is engaged with the session. With this technique, you still able to read the $_SESSION data while the session is engaged with another request.

Example Script:

// start the session
session_start();
// read/write to session
$_SESSION['login_time'] = time();
// close the session
session_write_close();
// now do my long-running code.
// still able to read from session, but not write
$twitterId = $_SESSION['userId'];

Search Key Value Pair in Multidimensional Array

Are you Looking for key value search of a multidimensional array? This script will help you to search multidimensional array by key value pair.

You will get following output after executing this script.

Result:

Array
(
    [0] => Array
        (
            [name] => DDD
            [role] => agent
        )

    [1] => Array
        (
            [name] => EEE
            [role] => agent
        )

)

Create and download ZIP file in PHP

Here I am sharing a script for creating and download the ZIP file in PHP. Sometimes we need to create a zip file and download that file that script will helpful for that case.

Look at the above snippet, here you can see a function called createZipAndDownload() which takes $files,  $filesName, and  $zipFileName as a parameter. To use this pretty function, first of all, create an array with the file name. And then pass that files array as the first argument of createZipAndDownload(). The second argument with being directory path of these files and the third argument will be the name of zipping file.

Example:

// Files which need to be added into zip
$files = array('sample.php', 'sample.jpg', 'sample.pdf', 'sample.doc');
// Directory of files
$filesPath = '/ROOT/FILE_PATH';
// Name of creating zip file
$zipName = 'document.zip';
echo createZipAndDownload($files, $filesPath, $zipName);

 

 

Terminate PHP Loop After a Certain Time

We all know every loop has a termination condition (conditions can be anything). And this code snippet is for terminating a while loop after a certain time. This is an actually funny script which is, increasing a value a certain time and then decreasing that value a certain time period.

From the above code snippet, you can see there is variable called $totalTime which carrying the total number of execution time (in second) for loop. Then $totalTime is divided into the two periods, and the first half is using to increasing the $counter value and the second half is using to decreasing that $counter value.

Output:

Terminating a PHP loop after a certain time preiod Raw