Host Static Website in Google App Engine

This article is for hosting your static website into Google App Engine. This article provides an app.yaml file so you can host your static website into Google App Engine. Before do anything make your website’s folder structure like that (see below image). So put all the static files inside assets folder (css, js, images, fonts) and all HTML files in project’s root directory. Inside assets folder css, js, img, and fonts are sperate folders for holding separate files (ex. css file stylesheets, img for images)

Host Static Website in Google App Engine

Then copy-paste this snipped in your YAML file. And then deploy (gcloud app deploy) your application.

You can also make your project structure your own way, then you have to change YAML content based on your changes. So that means need to change YAML information according to your project’s structure.

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.

Getting Query String Values Without a Hash in the URL

$location.search() returns empty? Angular does not remove the query before the hash bang in URL. According to AngularJS documentation,  hash bang URL format is:

http://example.com/#!/bar?baz=23

So if you have no hash bang in your URL (e.g. http://example.com/bar?baz=23), and try to get query string value, then you can use this snippet.

function getQueryParams(queryParam, url) 
{
        var pageUrl = url || window.location.search.substring(1);
        var urlVariables = pageUrl.split(/[&||?]/);
        var response = null;

        for (var i = 0; i < urlVariables.length; i += 1) {
            var param = urlVariables[i];
            var paramName = (param || '').split('=');

            if (paramName[0] === queryParam) {
                response = paramName[1];
            }
        }
        return response;
}
    
console.log(getQueryParams('baz', 'http://example.com/bar?baz=23'));

This code is also with pure JavaScript (withour AngularJS).

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.

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

 

Understanding of PHP Traits

As we know PHP is a single inheritance language, so what does it mean? It means one class can only inherit from another one class. So it doesn’t allow to inheriting from multiple class. But sometimes it’s might be beneficial to inherit from multiple classes.

To take care of this problem PHP introduced Traits in their 5.4 release. With the using traits, the developer can avoid the problems of multiple inheritances.

What is Traits:

Traits are something like a group or bundle of methods which you want to use within other classes. PHP introduced traits to reduce code duplication and overcome the limitations of single inheritance.

Using PHP Traits

From the above code snippet, you can see we have traits called Common and two different classes called Article and Comments.
Both Article and Comments use Common traits. So when a class uses any traits then all of the methods will available within that class. So the socialSharing() method of Common traits is now available within of these two classes.

In this way, you can reduce your code and avoid multiple inheritances.

Return Image as response by PHP

Return Image as response By PHP

To return an image as a request response by PHP you fpassthru function of PHP. I have included a sample code snippet, which will help you to understand how to do this.

From the above code snippet, you can see I have opened an image with binary mode by fopen($image, rb). And then send that with appropriate headers by header(“Content-Type: image/png”). After that dumping that image by using fpassthru, and finally stop the execution of PHP. It’s really easy to return image as response by PHP