Fast Loading web pages - php

We are planning to develop a new website. Our goal is to load web pages
quickly. What are all the techniques we need to follow.
Can anyone give me good suggestions, forums links or articles.
Our platform is PHP, MySQL, Javascript, and AJAX.

One of the best guides for speeding up your website's load times:
http://developer.yahoo.com/performance/rules.html
Update: Google now has an excellent guide as well
http://code.google.com/speed/page-speed/docs/rules_intro.html
Along with an even better addon for Firefox. In my testing so far, Google's Page Speed addon is far and above much better than YSlow. It gives much more detailed analysis and smarter advice (rather than recommending a CDN for small websites like YSlow)

One useful tool is YSlow which is a tool from Yahoo that helps identify web page performance problems. Also, Yahoo's Best Practices for Speeding Up Your Web Site is a good list.
However, see Jeff's blog entry Yahoo's problems are not your problems for some perspective on this issue.

Caching caching caching.
memcached
APC
Pick one, use it. Not having to fetch everything from the database speeds things up hugely.

Yahoo: "Put Stylesheets at the Top", "Put Scripts at the Bottom".
This sped my recent site up more than any other optimisations.

Use CSS sprites to keep your HTTP request count down.
Make sure all your images are a decent size.
Make sure you have a really good host with good upstream and downstream.
Make sure your server can execute your scripts in good time, you can check this using the microtime function.
Make sure your code is optimized properly.

Write as little code as necessary, but not too little.
Less code, less to compile, less to send, less to receive, less to process, less to display.

1) mod_gzip / mod_deflate! This is such an easy fix I'm surprised it isn't turned on by default.
2) Play tricks with your URL's so you can tell browsers to cache your JS and CSS files forever. In other words, construct the URL's to look like:
http://www.yourdomain.com/js/mad_scriptz-v123.js
Then use mod_rewrite and strip out the "-v123":
<IfModule mod_rewrite.c>
# http://www.thinkvitamin.com/features/webapps/serving-javascript-fast
RewriteEngine on
RewriteRule ^/(.*)\-v[0-9.]+\.(css|js|gif|png|jpg|xap)$ /$1.$2 [L]
</IfModule>
Now apache will go looking for "/js/mad_scriptz.js"... Every time you change your static content, just bump up the version number to force browsers to reload the content. I usually have a template variable that contains a global version number that everything gets tied to. Not the most efficient, but works for my purposes. If you can tie the version number to your build system or a hash of the file, that would be extra sweet.
Get mod_expires up so all your static stuff expires years from now:
<IfModule mod_expires.c>
ExpiresActive On
# all in seconds...
ExpiresByType image/x-icon A2592000
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/png A2592000
ExpiresByType application/javascript A2592000
ExpiresByType application/x-javascript A2592000
ExpiresByType application/x-shockwave-flash A2592000
ExpiresByType application/pdf A2592000
ExpiresByType text/css A2592000
ExpiresByType application/rdf+xml A1800
</IfModule>
Update: It has been noted that not all browsers or search engines like gzip'd content. Don't blindly turn it on like I suggest above. Make sure you don't feed antique browsers gzip even if they accept it (some of them will get pissy with compressed javascript). The documentation for mod_gzip and mod_deflate both have examples that should work fine (I assume they do, or people would email them with changes :-).
I should also mention that it has been my experience that if you've got a reverse proxy in between your mod_gzip'd Apache servers and the world, you need to watch out. Squid 2.6 will often fool Apache into not gziping stuff when it should and worse, it will cache the uncompressed versions and feed them to browsers that can handle gzip'd content. Dunno if 3.0 fixes this and I dont know if it is something wrong in my config (doubt it). Just watch out :-)
That said. Turn it on. Seriously :-)

1. Enable Keep-Alive
HTTP Keep Alive refers to the message that’s sent between the client machine and the web server asking for permission to download a file. Enabling Keep Alive allows the client machine to download multiple files without repeatedly asking permission, which helps to save bandwidth.
To enable Keep Alive, simply copy and paste the code below into your .htaccess file.
<ifModule mod_headers.c>
Header set Connection keep-alive
</ifModule>
2. Disable hotlinking of images
When other website’s ‘hot link’ to your images it steals bandwidth, slowing your site down. To prevent other sites from hogging your bandwidth, you can add this snippet of code to your .htaccess file. Remember to change the bit that says your_Domain_name.com!
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?your_Domain_name.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ – [NC,F,L]
3. Compress your website with gzip
Gzip is a simple method for compressing your website’s files to save bandwidth and speed up page load times. Gzip works by compressing your files into a zip file, which is faster for the user’s browser to load. The user’s browser then unzips the file and shows the content. This method of transmitting content from the server to the browser is far more efficient, and saves a lot of time.
You can enable Gzip by simply adding the following code into your .htaccess file:
# 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
# Or, compress certain file types by extension:
SetOutputFilter DEFLATE
To check whether Gzip is enabled or working properly on your site, you can use Gziptest.com.
4. Enable Expires Headers
Expires headers tell the browser whether they should request a specific file from the server or whether they should grab it from the browser's cache.
The whole idea behind Expires Headers is not only to reduce the load of downloads from the server (constantly downloading the same file when it's unmodified is wasting precious load time) but rather to reduce the number of HTTP requests for the server.
So in .htaccess file include the following things
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
5. Replace PHP with static HTML where possible
PHP is great for making your site efficient and reducing the need to enter the same information multiple times. However, calling information through PHP uses up server resource and should be replaced with static HTML where it doesn’t save any time
6. Specify a character set in HTTP headers
For the same reason as above, it’s useful to specify a character set in your HTTP response headers, so that the browser doesn’t have to spend extra time working out which character set you’re using.
You can do this by simply adding a UTF-8 character set tag in your website’ssection.
7. Enable Output Compression
The compression can be done in two ways.
Apache actually has two compression options:
mod_deflate is easier to set up and is standard.
mod_gzip seems more powerful: you can pre-compress content.
Your two options for file compression are Deflate and GZIP.
Deflate is an option which comes automatically with the Apache server and which is simple to set up.
GZIP on the other hand needs to be installed and requires a bit more work to install. However, GZIP does achieve a higher compression rate and therefore might be a better choice if your website uses pages which have a lot of images or large file sizes.
Deflate is quick and works, so I use it; use mod_gzip if that floats your boat. In either case, Apache checks if the browser sent the “Accept-encoding” header and returns the compressed or regular version of the file. However, some older browsers may have trouble (more below) and there are special directives you can add to correct this.
zlib.output_compression Whether to transparently compress pages. If
this option is set to "On" in php.ini or the Apache configuration,
pages are compressed if the browser sends an "Accept-Encoding: gzip"
or "deflate" header.
PHP Default: Disabled
In Php.ini
zlib.output_compression = On
If you can’t change your .htaccess file, you can use PHP to return compressed content. Give your HTML file a .php extension and add this code to the top:
In PHP:
<?php
if (substr_count($_SERVER[‘HTTP_ACCEPT_ENCODING’], ‘gzip’))
ob_start(“ob_gzhandler”); else ob_start();
?>
This section will turn on the apache mod_deflate module, which compresses text, css, and javascript before it is sent to the browser. This results in a smaller download size. Enable it in .htaccess file so that it looks like the following:
<IfModule mod_deflate.c>
############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip
# Insert filter on all content
SetOutputFilter DEFLATE
# Insert filter on selected content types only
AddOutputFilterByType DEFLATE text/html text/plain text/css text/javascript application/javascript application/x-javascript text/xml application/xml application/xhtml+xml image/x-icon image/svg+xml application/rss+xml application/x-font application/x-font-truetype application/x-font-ttf application/x-font-otf application/x-font-opentype application/vnd.ms-fontobject font/ttf font/otf font/opentype
# Netscape 4.x has some problems...
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# Don't compress images
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</IfModule>
**
8. Enable cache, OPcache, and eAccelerator (Another PHP Caching tool)
Memcache is particularly useful for reducing your database load while bytecode caching engines like APC or OPcache are great for saving execution time when scripts get compiled.
9. Take Advantage of Native PHP Functions
Wherever possible, try to take advantage of PHP’s native functions instead of writing your own functions to achieve the same outcome. Taking a little while to learn how to use PHP’s native functions will not only help you write code faster, but will also make it more efficient.
10. Cut Out Unnecessary Calculations
When using the same value of a variable multiple times, calculate and assign the value at the beginning rather than performing calculations for every use.
If you’re looping through an array, for example, count() it beforehand, store the value in a variable, and use that for your test. This way, you avoid needlessly firing the test function with every loop iteration.
11. Use the Strongest Str Functions
While str_replace is faster than preg_replace, the strtr function is four times faster than str_replace.
12. Stick With Single Quotes
When possible, use single quotes rather than double quotes. Double quotes check for variables, which can drag down performance.
13. Try Three Equal Signs
Since “= = =” only checks for a closed range, it is faster than using “= =” for comparisons.
14. Use isset( )
when compared to
count( ), strlen( ) and sizeof( ),
isset( ) is a faster and simpler way to determine if a value is greater than 0.
15. Cut Out Unnecessary Classes
If you don’t intend on using classes or methods multiple times, then you don’t really need them. If you must employ classes, be sure to use derived class methods as they are faster than methods in base classes.
16. Close Database Connections
Un-setting variables and closing database connections in your code will save precious memory.
17. Limit Your Database Hits
Making queries aggregate can reduce the number of hits to your database, which will make things run faster.

Use a profiler for PHP to make sure your code is executing at a decent speed. Refactor (where possible) if performance could be improved.

in addition to what has been said:
obfuscate and compress your css
obfuscate and compress your javascript
less files == less http requests == faster site == put all your css in one file, put all your javascript in one file

Compress all your files, inlcuding css and js files also compress your php files. Do as little database calls as possible and as stated earlier cache all the returns.

Some random points.
Render progressively rather than building it in memory and sending at at the end gives a distinct impression of speed.
There are some advanced caching tricks you can do, like a forward cache (this is what Akamai do on a grand scale) and separating static and dynamic content.
With PHP particularly, be careful about copying huge amounts of data around. PHP 4 was notorious for this due to it's "copy by default", but it's still a bit too easy to have huge amounts of data to hand in PHP 5. In other words: don't copy (or create!) strings, arrays and objects unecessarily; work with them in place and pass references instead.

Here is one tip I always find useful:
If you have a lot of tiny images, put them all in one tiled image. In your CSS declarations, control the viewport of the html element by manipulating the x and y coordinates of the background:
.icon {
background-image:url(static/images/icons.png);
height:36px;
width:36px;
}
.food {
background-position:-52px -8px;
}
.icon_default {
background-position:-184px -96px;
}
The tiling can be done in Python script, or by hand if you have a manageable set.
Gmail does this as well. See: http://mail.google.com/mail/images/2/5/greensky/icons7.png

A project which helps with a few of the points in Yahoo!'s guidelines (http://developer.yahoo.com/performance/rules.html) is Minify which employs minification, package bundling and conditional HTTP serving in the same space, used with good design practices can significantly reduce page loads, especially user experience (which differs from actually page loading times).

Best ways to load webpage faster:
[According to yahoo]
1-Stylesheet should appear on top loads web page faster.
2-Avoiding redirects.
3-Reduce unnecessary code.
4-Put CSS and JS in external files.
5-Removing duplicate scripts.
Source:
https://developer.yahoo.com/performance/rules.html
[According to google]
1-Eliminate render-blocking resources
2-Properly size images
3-Defer offscreen images
4-Efficiently encode images
5-Serve images in modern formats
6-Enable text compression
7-Preconnect to required origins
8-Reduce server response times (TTFB)
9-Avoid multiple page redirects
10-Preload key requests
11-Use video formats for animated content
12-Reduce the impact of third-party code
14-Kill Lazy load third-party resources with facades.
Note: applying the tips can reduce the time significantly. use the points according to your needs.

Related

.php files are not compressing, while GZIP is set in .htaccess

According to checkgzipcompression all my .js and .css are correctly GZIP compressed.
Except for my php webpages:
www.website.nl/webpages.php seem not gzipped, resulting in a 75% increase in "wasted" data transfer. My .htaccess file ends with the following below. What needs to be changed here to get GZIP compression for my php webpages to work properly? (Excluding the .php files from the /includes/ folder ofcourse since those are not "transferred to the browser" and are processed internally so they need no compression). Thanks!
# compress speficic filetypes
<IfModule mod_deflate.c>
<FilesMatch "\.(js|css|txt|php)$">
SetOutputFilter DEFLATE
</FilesMatch>
</IfModule>
Pages served in the browser with .php extension are considered html. PHP uses Content-Type "text/html" as default.
I would say, find out what's your web server, and then find out the correct compression method for it.
Good luck!

Can't resolve Google pagespeed "Enable compression" point using Yii2

Site in question is http://burghleys.com/
Having trouble trying to improve the Google pagespeed score and says I need to enable compression with a 70% improvement on the JS file for example but I can't make the same improvement at all!
https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fburghleys.com%2F
I have GZIP enabled and use the apache mod_deflate to do so, tested as per http://checkgzipcompression.com/?url=http%3A%2F%2Fburghleys.com%2F
I use yii2 https://github.com/rmrevin/yii2-minify-view plugin to compress my files which generally works really well.
I use the HTML5 boiler plate htaccess file.
I tried manually compressing the JS file but can only reach 25%. CSS is even less yet states i can save 80%.
Any thoughts?
ps. I'm working on the other issues too, wanna get that 99 score.
You do have GZIP enabled for some items but if you follow the link to your js you will see that this resource is not being zipped up.
http://checkgzipcompression.com/?url=http%3A%2F%2Fburghleys.com%2Fminify%2Fb329b2d2ce53b5c6be05decfe5e5d723527a666e.js
Add the following line to your .htaccess
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/xml application/xhtml+xml application/rss+xml application/javascript appliction/x-javascript

how to optimize loading time of my website? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am new to php developer and developed a website in magento 1.7.
My website take a too much time to loading.
I deleted caches , re indexing the date comprise images still take lot time for loading.
please suggest me how to optimize the loading time of my website.
thanks in advance .
Enable Output Compression
This section will turn on the apache mod_deflate module, which compresses text, css, and javascript before it is sent to the browser. This results in a smaller download size. To enable, simply uncomment the appropriate lines so that it looks like the following:
<IfModule mod_deflate.c>
############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip
# Insert filter on all content
SetOutputFilter DEFLATE
# Insert filter on selected content types only
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
# Netscape 4.x has some problems...
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# Don't compress images
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</IfModule>
See more at: http://docs.nexcess.net/article/optimizing-magento-performance.html#sthash.ZUpf53Fy.dpuf
Enable Expires Headers
NOTE: This does not work on Litespeed servers.
Browsers use Expires headers to determine how long a page component can be cached. Static components, like images, should have far-future expires headers, but truthfully, all page components should have expires headers. To turn this feature on, just uncomment the appropriate line and add "ExpiresActive On" right above it. See below:
#
Add default Expires header
http://developer.yahoo.com/performance/rules.html#expires
ExpiresActive On
ExpiresDefault "access plus 1 year"
- See more at: http://docs.nexcess.net/article/optimizing-magento-performance.html#sthash.ZUpf53Fy.dpuf
Reference taken from here
This has worked for me to a good extent.
Try looking at these results: http://gtmetrix.com/reports/www.fashiza.com/KLDZeYuI
It seems like you'd gain alot in this case moving some of your javascript down and checking if all of your images have:
1) defined width and height in css.
2) format optimised for the web
EDIT: You are loading almost 500kb of javascript. This is probably the main reason. Try to compress your js and decide if you really need that much.
Tips for Magento site speed up
Summary:
Enable all Magento caching layers.
Configure your web server to enable Connection Keep-Alive, enable mod_expire, gzip compression.
Enable MySQL Query caching.
Install APC or XCache to cache PHP opcode.
Install Memcache and configure Magento to store session and cache to memory.
Install third-party Full Page Cache Magento extension.
Install Varnish cache server for full page caching on system layer.
You can check detailed instruction: http://www.magentocommerce.com/boards/viewthread/36225/
1.http://www.fashiza.com/media/js/1348d08285c79d6cda3eb91987e1942f.js
is too big 100KB
minimify that
2.http://www.fashiza.com/media/css/d2d005572b30b4d004b45f21ee567278.css
is too big
3.no file:productsliderpoint
google:compress js and you will find answer
i.stack.imgur.com/eh1NR.jpg
this is not normal
Create benchmarks to measure what causes the largest time lags. This helps you to narrow down the problem, thus, gain a better understanding, as your question is too broad to enable us to help you.

Looking for custom PHP Content Delivery Network (CDN) script for my server

REF: https://en.wikipedia.org/wiki/Content_delivery_network
A content delivery network or content distribution network is a system of computers where our website is stored so it’s data (images/videos) can be served from multiple locations.
However I dont want to use any online paid/unpaid CDN services but would like to setup CDN on my own high speed server. I did google a lot but dont see any such CDN script which i can install on my server.
I am looking for such script which can support High level cache-control.
Can you please share if you know any good CDN script developed in PHP?
This isn't done in PHP, this done in Apache.
What I've done on my own home server (that's probably what you want) is set up a cookieless sub-domain for serving content, and enable caching and GZip. The following Apache configurations are all located in a .htaccess file in the website directory.
# GZIP compression
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(eot|ico|gif|jpe?g|php|png|ttf|svg|woff)$ no-gzip dont-vary
# Fonts on a cookieless subdomain
<FilesMatch "\.(eot|ttf|svg|woff)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
# Cookieless Static Content
<FilesMatch "\.(css|eot|ico|gif|jpe?g|js|png|ttf|svg|woff)$">
Header unset Cookie
Header unset Set-Cookie
</FilesMatch>
# Caching
ExpiresActive On
ExpiresDefault A0
<FilesMatch "\.(eot|ico|gif|jpe?g|png|ttf|svg|woff)$">
# 2 year caching for images and stuff
ExpiresDefault A31536000
Header append Cache-Control "public"
</FilesMatch>
<FilesMatch "\.(css|js)$">
# 1 week caching for styles and scripts
ExpiresDefault A604800
Header append Cache-Control "public"
</FilesMatch>
#Other Header Manipulation
FileETag MTime Size
Header unset X-Powered-By
AddDefaultCharset UTF-8
DefaultLanguage en-US
So long as you don't mind caching and GZip on your primary domain (which you shouldn't), just link to your cookieless content using your designated cookielesss sub-domain, and Apache takes care of the rest.
Update
I added a few things I've learned about since posting this answer, such as:
Allowing any domain to link to fonts so that they may be served without cookies.
Setting the ETAG header since it should be set.
A few other header fields that aren't bad to include/get rid of.
However, there's one last security concern to keep in mind if you're using HTTPS, and that is BREACH. To protect against this decryption technique, you can remove gzip compression from any page that displays dynamic content (GZIPping static content like static HTML, CSS, or JS is still ok). To avoid compressing a certain file type (like PHP), add it to the SetEnvIfNoCase directive near the start of this config.
Alternatively, you can keep compression enabled and use the GCM cipher method since the BREACH family of attacks only work on the CBC cipher method. As much as I hate to be "that guy", the manual is really the best reference for this if you want to get into configuring such things. It's a fairly complicated topic and the manual does a good job of explaining the basics.

How do I gzip my web files

As prescribed by Yahoo!, gzip'ng files would make your websites load faster. The problem? I don't know how :p
http://www.webcodingtech.com/php/gzip-compression.php
Or if you have Apache, try http://www.askapache.com/htaccess/apache-speed-compression.html
Some hosting services have an option in the control panel. It's not always possible, though, so if you're having difficulty, post back with more details about your platform.
If you are running Java Tomcat then you set a few properties on your Connector ( in conf/server.xml ).
Specifically you set:
compressableMimeType ( what types to compress )
compression ( off | on | )
noCompressionUserAgents ( if you don't want certain agents to receive gzip, list them here )
Here's the tomcat documentation which discusses this:
http://tomcat.apache.org/tomcat-5.5-doc/config/http.html
Edit your httpd.conf file.
Add this line to load the module:
LoadModule deflate_module modules/mod_deflate.so
Add these lines to actually compress the output:
AddOutputFilterByType DEFLATE text/css text/html application/x-javascript application/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Jetty will look for gzip'd versions of static files, as well as it has a GzipFilter for dynamic content.
You could probably pull the GzipFilter over into Tomcat if you wanted more control over compression than just Tomcat's connector-level compression...
http://docs.codehaus.org/display/JETTY/GZIP+Compression
Gzip compresses your webpages and cascade style sheets before sending them over to the client browser.
This drastically reduces transfer time since the files are much smaller.
There are different methods of setting up gzip compression depending on whether or not you've got an IIS or Apache server
Example: this link.
http://developer.yahoo.com/performance/rules.html#gzip
This is the reference if any asks me about my reference loading gzipped files
If you are using Lighttpd, there is mod_compress.
Seeing how most answers here are almost 5 years old, here's some very current and up to date example references.
For example server configs that enable gzip/deflate type compression for iis, lighthttpd, nginx, and even node see: https://github.com/h5bp/server-configs
For a very good current implementation of Apache mod_deflate see
https://github.com/h5bp/html5-boilerplate/blob/master/.htaccess#L156
Gzip compresses your webpages and cascade style sheets before sending them over to the client browser
other example this link

Categories