Change an Array Value if Duplicate

I have an array which holds the multiple same values in same categories. And I want to If the data is duplicate and the category is ‘Sales’ I want 1 of them to change to ‘Service’ and vice versa.

From above snippet, you can see ‘Lane Assist’ is duplicate in ‘Sales‘ category and ‘Bandenafdichtset’ is duplicate in ‘Service‘ category and I changed them as vice versa.

Configure Email Transporter in CakePHP Runtime

If you are looking for a solution to configure email transporter from CakePHP controller, components in run-time. This script will help you lot. This script is working for CakePHP 3.1.X – 3.3.9.

Email::configTransport('transporter_name', [
            'className' => 'Smtp',
            'host' => 'SMTP_HOST',
            'port' => 'SMTP_PORT',
            'timeout' => 30,
            'username' => 'SMTP_USERNAME',
            'password' => 'SMTP_PASSWORD',
        ]);
        
        $email = new Email();
        $email->transport('transporter_name');
        
        $email->from('no-replay@example.com')
            ->to('to@example.com')
            ->subject('Dummy Subject')
            ->message('This is a test message')
            ->send();

Simply copy paste this snippet and modified with real information and test it.

Avoid Too Much Complexity to the Code, Instead of Returning Often and Early.

Code readability is really important part of programming. The readable and cleaner code is easily manageable and customizable. The programmers don’t take it seriously but it’s important.  Actually, there is always an ongoing debate, but returning often, and returning early will make your code much cleaner looking and readable.

public function saveUser($data = [], $sendEmail)
    {
        // Checking data is exiest or not
        if ($data) {
            $isSaved = $this->UserModel->save($data);

            // Checking if the data is successfully stored or not.
            if ($isSaved) {
                //  If stored then doing some other work

                // send the email to the user
                if ($sendEmail) {
                    // send the email
                }

            } else {
                // Otherwise return false
                return false;
            }
        } else {
            // Otherwise return false
            return false;
        }
    }

If you look over the above code snippet, then you can see there is some nested if-else. And code quickly becomes unreadable and complex. You have to have a deep look to understand this sort of code.

public function saveUser($data = [], $sendEmail)
    {
        if(!$data)
        {
            // If data not exiest then return.
            return false;
        }

        $isSaved = $this->UserModel->save($data);
        if (!$isSaved) {
            // If data not saved then return.
            return false;
        }

        if (!$sendEmail) {
            // send the email
        }
        
        // If everything good, then return true.
        return true;
    }

Now see this code snippet, this code is much easier to read and very cleaner look. Both snippets are doing same work but the second one is much more readable and clearer than first one. And this can be easily manageable & customizable. so that avoid too much complexity to the code, instead of returning often and early.

Loading Model Inside Another Model and Controller in CakePHP 3

Sometimes it necessary to load a model inside another model as well as another controller in CakePHP. This article will help you to load a model from another model & controller with CakePHP 3

Load From Model:
$anotherTable = TableRegistry::get('AnotherTable');
$data = $anotherTable->find('list');

CakePHP TableRegistry is a factory of the Table object. It comes with a lot of static function and get() one of them. TableRegistry::get() provides an instance of Table. You can see an example from above snippet.

Load From Controller:
$this->loadModel('AnotherModel');
$data = $this->AnotherModel->find('list');

If you need to load a model from the controller which does not default model of the controller. You can use loadModel() function to get an instance of another model.

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);

 

 

Concurrency Issues With PHP Session

Concurrent connection means how many request sending/calling at the same time. It influences the application performances rapidly. When your application can handle as much as concurrent connections your application will become more stable, high scalable and faster as well. But concurrency might be a problem when you deal with PHP Session. It is the biggest challenges to avoiding concurrency issue in PHP, especially in PHP Session.

Most of the modern web browser sent concurrent connections to a specific domain to between 4 or 6. That means if your application has a lot of static assets (JS, CSS, Images, Fonts, etc), then these will be queued until browser get the response from the server for its first set of a request (4/6 concurrent request).

Concurrency Issues With PHP Session

PROBLEM:

By default, PHP uses files to storing the Session data. PHP either create a new Session or retrieve existing Session on each request when called session_start() function. So in this case, if your user sending multiple concurrent requests to the server which involves with Session data. PHP Session will lock and block your application’s concurrent request for that particular client. And every request will be served as sequentially instead of processing them concurrently.

BEHIND THE SENCE:

For the new user, PHP sent the unique identifier number to users computer and create a new file with the same unique identifier name for handle the session for that particular user. Otherwise, PHP retrieves existing session for that user. See this article to know how does session works.

Now assume, a user sent 6 concurrent requests to server and 4 of them involved with session data. So what happened that case? PHP will take the first request and open the session file and lock it. And other 3 requests will be queued until session file will be released. So that means your application will be blocked. After your first request’s done, it will release the session file and the second request will take it. It’s will happen for rest of the request.

Now think every request taken 400-500 ms to execute, that means your last (4th) request completed after 1600 ms cause it waited 1200 ms to complete first 3 requests. So in this way PHP Session blocked the application.

However, this concurrent issue happened for the same user only. Request from a user cannot block another user’s request.

You will be able to understand how this thing can affect your application performance. To improve application performance every developer needs to avoid this issue.

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

 

How Does PHP Session Works

Basically, the session is the system or way to store information for individual users. It’s storing individual users information against a unique session ID. So in this way, user’s data can be accessible across all pages of a website. PHP follow simple workflow for manage session, and that is when a session is started, then PHP either retrieve existing session or create a new session. If PHPSESSID is passed then PHP retrieved existing session otherwise creates a new session

By default, session creates a file in a temporary directory (which determined in php.ini file) on a server. All all the variables & value are stored there.

How Does PHP Session Works

How is Works:

  • Firstly PHP creates a unique identifier number (a random string of 32 hexadecimal number, e.g 3c7foj34c3jj973hjkop2fc937e3443) for an individual session.
  • PHPSESSID cookie passes that unique identification number to users’ browser to save that number.
  • A new file is created on the server with the same name of unique identification number with sess_ prefix (ie sess_3c7foj34c3jj973hjkop2fc937e3443.)
  • The browser sends that cookie to the server with each request.
  • If PHP gets that unique identification number from PHPSESSID cookie (on each request), then PHP searches in the temporary directory and compares that number to the file name. If both are the same, then it retrieves the existing session, otherwise it creates a new session for that user.

A session gets destroyed when the user closes the browser or leaves the site. The server also terminates the session after the predetermined period of session time expires. These are the simple mechanism steps that PHP is using to handle the session. I hope this article with help you to understand how PHP SESSION is working.