How to optimize your php website(feat.Gzip Compression)
Tags: php, gzip, loadingtime, webdev
Published: 2019-09-03 02:50:15

<p>Have you ever experienced when you grind your soul to make this website beautiful and once you deploy it online, It just takes forever to load and you feel bloody awkward in front of others cuz they also have to wait for eternal?</p>

<b>common we've all been there</b>

Things get normally worse if it is deployed on free hosting website such as heroku, github.it etc. 

Then, What we can do about it.

<h3> <b>FIRST<b>: a diagnosis</h3>
As simple and obvious as it sounds, we need to first figure out how slow the website is and what are the causes, just like we receive a diagnosis from doctors!
In order to do this, there are some useful links you might want to bookmark. 
Even though I know for a fact that there are hundreds of websites that do the similar works but it is purely the matter of a taste and these two are my favorite in terms of simple and straight forward UI designs and its contents.

a. <a href="https://www.uptrends.com/tools/website-speed-test">uptrends.com/tools/website-speed-test</a>
b. <a href="https://tools.pingdom.com/">tools.pingdom.com/</a>

Well, this is how it looks when you click the second link which is pingdom which helped me a lot to look at the problem clearly. You can simply copy your website url and select the location that you want to test from. And hit the "Start test" button!

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/uhuyev0oblc4glt3mpcl.png)

Let's have a look at the result.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/zb6be83b3ygbuna2iy7u.png)

Seems like the overall performance grade is not so terrible, however I had a "D" grade under the name of 'Compress components'.
It is saying
<h6>"Compression reduces response times by reducing the size of the HTTP response. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today's Internet traffic travels through browsers that claim to support gzip."</h6>

Alright, it sounds like it is time for us to dig into "gzip" part, doesn't it?

<h3> <b>SECOND<b>: Gzip, what are you?</h3>

Before, we get to the Gzip, it would be easier to understand the concept of content encoding with some explanations like this.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ltrvefjf0vnj30g5mdcf.jpg)
<h6>Original</h6>
Browser: Hey dude, can I get index.php file?
Server: Give a sec, wait....Yes! got it!  I’m sending the file to you.
Browser: 200KB? Ouch… waiting, I am gonna need more time… ok, it’s done and loaded.

<h6>After Compression</h6>
Browser: Hey dude, can I get index.php file? I wouldn't mind a compressed version if you have any.
Server: Give a sec, wait....Yes! got it! You said you are good with compressed one? amazing. I’m sending the file to you.
Browser: Great! It’s only 20KB. I’ll unzip it myself!

It is as simple as that! Smaller file can reduce so much time to download so that users don't have to wait for a long time to see the whole websites.


<h3> <b>THIRD<b>: Gzip, How can I have you?</h3>
Okay, let's get to the point right now to actually implement Gzip to our websites. It is going to be quite straight forward yet the syntax can varies so have that in mind!

<b>Firstly,</b> Open your .htaccess file in your root folder. If you don't have it, then you can simply make one. In side of that file, what we can do is to specify the type of file that we want to compress. I would look like this.

```
<IfModule deflate_module>
    # Enable compression for the following file types.
    AddOutputFilterByType            \
     DEFLATE                         \
      application/javascript         \
      text/css                       \
      text/html                      \
      text/javascript                \
      text/plain                     \
      text/xml
</IfModule>
```
But note that Gzip is not able to compress which is already compressed in a way of compressed formats such as PNG, Zip or any other compressed formats.

In Apache, this would work too
```
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
```
If above doesn't work, then try this one here
```
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_include mime ^text/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_include handler ^cgi-script$
</ifModule>
```
<b>Secondly,</b> Put this php code on the top of your main pages

```
<?php
if (!isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
    ob_start();            
}
elseif (strpos(' ' . $_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') == false) {
    if (strpos(' ' . $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') == false) {
        ob_start();
    }
    elseif(!ob_start("ob_gzhandler")) {
        ob_start();
    }   
}
elseif(!ob_start("ob_gzhandler")) {
    ob_start();
}
?>
```

<b>Thirdly,</b> Let's go ahead and check if the compression is working!
<a href="http://www.gidnetwork.com/tools/gzip-test.php">gidnetwork.com/tools/gzip-test.php</a>


![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/3s38ksls9jhb8cd47ylr.jpg)

Horray! it said that is is compressed right and type of compression is gzip. Looks like we've done our job here:)

<b>Lastly, Little extra</b> If you are not still satisfied with the speed.

```
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##
 
```
Put those lines above in  .htaccess file. What it does is the mentioned file will be stored in caching and expire after a certain time so if you visit the website again few days later and you won't need to wait for the browser to load all the files all over again!

<h3> <b>Finally<b>: Let's check again how it worked on the website</h3>

I clicked the first link to check the speed and it is how it turned out!
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/1jux83vpbbdois5p4ozg.jpg)

Wow, looks pretty cool and sounds like I reduce some loading time obviously.
<h3> <b>Conclusion:<b>:</h3>

By compressing your site’s files, you can make sure loading time stay low, and your users don’t suffer from unnecessary slowdowns.
I hope this article would help you somehow and please let me know if you found this content useful Thank you!

If you want to have a look my website 
<a href="https://emmaham-portfolio.herokuapp.com/"> Come and visit here</a>

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/3druws88n6n6c2zmzwjh.png)