404 and 500 errors in Zend Framework

First of all, I want to review the several mechanisms that Zend Framework provide to handle exceptions in it’s MVC components.

 

1. Pass the exceptions to Zend_Controller_Plugin_ErrorHandler.

 

2. Using Zend_Controller_Front::throwExceptions(true) :

  

[codesyntax lang=”php”]

$front->throwExceptions(true);

try {
    $front->dispatch();
} catch (Exception $e) {
    // handle exceptions yourself
}

[/codesyntax]

 

3. Using Zend_Controller_Response_Abstract::renderExceptions(true). But it’s not the common way and recommended for non-production environment.

 

4. Using Zend_Controller_Front::returnResponse(true) :

 

[codesyntax lang=”php”]

$front->returnResponse(true);
$response = $front->dispatch();

if ($response->isException()) {
    $exceptions = $response->getException();
    // handle exceptions ...
} else {
    $response->sendHeaders();
    $response->outputBody();
}

[/codesyntax]

 

See more info in manual :

http://framework.zend.com/manual/en/zend.controller.exceptions.html#zend.controller.exceptions.handling

 

Here we will mainly take a look into the 4th mechanism which is considerd to be the best from official.

 

Let’s make some configurations to Zend_Controller_Front :

 

[codesyntax lang=”php”]

$front = Zend_Controller_Front::getInstance();
$front->setParam('noErrorHandler', true)
      ->throwExceptions(false)
      ->returnResponse(true);

[/codesyntax]

 

We have just canceled the error handler plugin and forbade to throw exceptions and store the exceptions within the response :

 

 

[codesyntax lang=”php”]

$response = $front->dispatch();

if ($response->isException()) {
    $exceptions = $response->getException();
    echo handleException($exceptions[0]);
} else {
    echo $response;
}

function handleException(Exception $e)
{
    switch ($e->getCode()) {
        case 500: {
            if (!include_once(PROJECT_ROOT . '/error/500.html')) {
                @header("HTTP/1.x 500 Internal Server Error");
                @header('Status: 500 Internal Server Error');
            }
            exit;
            break;
        }

        default: {
            if (!include_once(PROJECT_ROOT . '/error/404.html')) {
                @header('HTTP/1.x 404 Not Found');
                @header('Status: 404 Not Found');
            }
            exit;
            break;
}

[/codesyntax]

 

At last we write the content of 404.html and 500.html. I will show you how to make the SEO to 404.html for example :

 

[codesyntax lang=”html4strict”]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>kimbs.info - 404 error: Page not found</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="kimbs.info" />
<meta name="keywords" content="kimbs.info" />
<meta name="robots" content="*" />
<style type="text/css">
.STYLE1 {
    color:#0000FF; 
    font-weight:bold; 
    font-size:25px
    font-weight: bold;
}

.STYLE2{
    font-size:15px;
    line-height:25px
}
</style>
</head>
<body style="margin-top:100px;">
    <div style="margin:0 auto; width:650px;">
        <p>
            <h3 class="STYLE1">
                Sorry, the page you are trying to access
                does not exist or perhaps it was removed.
            </h3>
        </p>

        <br />

        <p>
            <h2 class="STYLE2">
                1. Please check your input
            </h2>
        </p>

        <p>
            <h2 class="STYLE2">
                2. Welcome back to home page <a href="http://kimbs.info/">http://kimbs.info/</a>
            </h2>
        </p>

        <p>
            <h2 class="STYLE2">
                3. Thank you for visiting and
                <a href="http://kimbs.info/contract">contract me</a> if any question
            </h2>
        </p>
    </div>
</body>
</html>

[/codesyntax]

 

Posted in Zend Framework | Tagged , | Leave a comment

Sending all css and js in one request

As we all know, one thing which mainly slow down our site is the plenty of css and js files. But very often we have to make them seperate from each other in order to facilitate management.

 

The problem we met in day-to-day practice is that, it’s more faster to send one file which is 50k then to send one file with 10k for 5 times. This is because the http request is very very expensive.

 

When we come to Zend Framework the layout and view helper can be helpful to reduse the numbers of http request for css and js files.

 

Let’s take an example now for css (js is more or less the same) :

 

[codesyntax lang=”php”]

class Kbs_View_Helper_Css extends Zend_View_Helper_Abstract
{
    // Container for css files
    protected $_container = array();

    // Return self object
    public function css()
    {
        return $this;
    }

    // Push into container
    public function append($value)
    {
        array_push($this->_container, $value);
        return $this;
    }

    // Prepend to container
    public function prepend($value)
    {
        array_unshift($this->_container, $value);
        return $this;
    }

    // Return very similar to this html link :
    // <link rel="stylesheet" type="text/css" href="/public/css/css.php?f1=default.css&f2=other.css&" />
    public function __toString()
    {
        $html = '';

        if (!empty($this->_container)) {
            $href = $this->view->pathCss . 'css.php?';
            $i = 0;

            foreach ($this->_container as $item) {
                $i++;
                $href .= "f$i=$item&";
            }

            $html = '<link rel="stylesheet" type="text/css" href="'.$href.'" />';
        }

        return $html;
    }
}

[/codesyntax]

 

We use it in layout then :

 

[codesyntax lang=”php”]

<?php
// layoutDefault.phtml
$this->css()->prepend('default.css');
$this->css()->append('other.css');
?>
<html>

    <head>
        <?php
        echo $this->headTitle();
        echo $this->headMeta();
        echo $this->headLink();
        echo $this->css();
        echo $this->headStyle();
        ?>
    </head>

</html>

[/codesyntax]

 

You can use it anywhere you want to import css. For example in indexAction :

 

[codesyntax lang=”php”]

$this->view->css()->append('index.css');

[/codesyntax]

 

We now reduse the numbers of request and send multi-css at one time.

Posted in Optimization | Tagged , | Leave a comment

htaccess in Zend Framework

How to setting up your .htaccess for your application is always become a question which hard to answer. In this note, we will take a look at it, fully and detail by detail. Hope it to be useful.

 

The url rewrite configurations below will also be suitable for virtual hosting.

 

# Php settings
# ====================
<IfModule php5_module>
 
    # Adjust memory limit
    # ========================
    php_value memory_limit 64M
 
 
    # Adjust exec time to prevent overtime running
    # ================================
    php_value max_execution_time 18000
 
 
    # Make sure the default timezone is set
    # Can also be set within application using date_default_timezone_set
    # =====================================
    php_value date.timezone "Asia/Shanghai"
 
 
    # Short tag for clean view scripts which is still not recommend
    # Because of the xml issue
    # ==========================
    php_value short_open_tag off
 
 
    # Default charset is utf-8 because of multi languages supportting
    # ===============================
    php_value default_charset "utf-8"
 
 
    # To report E_ALL|E_STRICT and show all errors
    # ==============================
    php_value error_reporting "8191"
 
 
    # Disable register globals which means nothing in php6
    # ===========================
    php_flag register_globals off
 
 
    # Disable magic quotes which means nothing in php6
    # ===========================
    php_flag magic_quotes_gpc off
 
 
    # Disable automatic session start but handled by program
    # e.g. Zend_Session::start()
    # =============================
    php_flag session.auto_start off
 
 
    # Turn off compatibility with PHP4
    # To avoid the problem when dealing with objects
    # ======================================
    php_flag zend.ze1_compatibility_mode Off
 
 
    # Gzip output
    # =======================================
    php_flag zlib.output_compression on
    php_value zlib.output_compression_level 9
 
 
    # Disable user agent verification to not break multiple image upload
    # ==================================
    php_flag suhosin.session.cryptua off
 
 
    # output buffering
    # =============================
    php_value output_buffering 4096
 
</IfModule>
 
 
 
# Mime type
# ====================
<IfModule mime_module>
 
    # Add javascript, php and phtml file type if needed
    # =========================================
    AddType application/x-javascript .js
    AddType application/x-httpd-php .php .phtml
 
 
    # For 1and1 hosting issue, we use php5 for all
    # ==========================
    #AddType x-mapp-php5 .php
    #AddHandler x-mapp-php5 .php
 
 
    # For fastcgi mode
    # =========================================
    #Action php5-cgi /cgi-bin/php5-cgi
    #AddHandler php5-cgi .php
    #cgi.fix_pathinfo = 1
 
    # Default character encoding UTF-8
    # =====================
    AddDefaultCharset UTF-8
 
 
    # No ETags for performance optimize
    # ===========
    FileETag none
 
</IfModule>
 
 
 
# Security scan
# =======================
<IfModule mod_security.c>
 
    # Disable POST processing to not break multiple image upload
    # ===================
    SecFilterEngine Off
    SecFilterScanPOST Off
 
</IfModule>
 
 
 
# Expires by type
# ======================
<IfModule mod_expires.c>
 
    # Add further expires for resources
    # ===========================================================
    ExpiresActive On
    ExpiresDefault "access plus 1 year"
    #ExpiresByType text/css "access plus 1 month"
    #ExpiresByType image/gif "access plus 1 month"
    #ExpiresByType image/jpeg "access plus 1 month"
    #ExpiresByType image/png "access plus 1 month"
    #ExpiresByType application/x-javascript "access plus 1 month"
 
</IfModule>
 
 
 
# Compress by type
# ======================
<IfModule mod_deflate.c>
 
    # Default filter : deflate
    # =====================
    SetOutputFilter DEFLATE
 
 
    # 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
 
 
    # Do not compress images
    # ===============================================================
    SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
 
 
    # The compress level 1(lowest)-9(highest)
    # ====================================================
    #DeflateCompressionLevel 9
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/atom_xml
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/x-httpd-php
 
 
    # Make sure proxies do not deliver the wrong content
    # ======================
    <IfModule mod_headers.c>
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
 
</IfModule>
 
 
 
# Make HTTPS env vars available for CGI mode
# ==================
<IfModule mod_ssl.c>
    SSLOptions StdEnvVars
</IfModule>
 
 
 
# default index file
# ===================
<IfModule dir_module>
 
    # By default allow all access
    # ==========================================
    Options -Indexes -MultiViews +FollowSymLinks
    Order allow,deny
    Allow from all
 
    # Directory default index
    # ===========================================
    DirectoryIndex index.php index.html index.htm
 
</IfModule>
 
 
 
# Url rewrite
# ======================
<IfModule mod_rewrite.c>
 
    # Rewrite enable
    # ==============
    RewriteEngine On
 
 
    # Rewrite base path to your site
    # ===========
    RewriteBase /
 
 
    # Forbidden access to htaccess file
    # ============================
    RewriteRule ^.htaccess$ - [F]
 
 
    # Url canonicalization for SEO
    # =====================================================
    RewriteCond %{HTTP_HOST} ^www.kimbs-local.info [NC]
    RewriteRule ^(.*)$ http://kimbs-local.info/$1 [L,R=301]
    RewriteCond %{HTTP_HOST} ^www.kimbs.info [NC]
    RewriteRule ^(.*)$ http://kimbs.info/$1 [L,R=301]
 
 
    # Rewrite for index if request is empty or did not mentioned before
    # ================================================================
    RewriteCond %{REQUEST_URI} =""
    RewriteCond %{REQUEST_URI} !^/(library/dojo)/
    RewriteCond %{REQUEST_URI} !^/(library/fckeditor)/
    RewriteCond %{REQUEST_URI} !^/(library/fckeditorPlugins)/
    RewriteCond %{REQUEST_URI} !^/(library/syntaxhighlighter_2.0.320)/
    RewriteRule ^.*$ /public/index.php [NC,L]
 
 
    # Rewrite for public if request is not the resource under public or did not mentioned before
    # ================================================================
    RewriteCond %{REQUEST_URI} !^/public/.*$
    RewriteCond %{REQUEST_URI} !^/(library/dojo)/
    RewriteCond %{REQUEST_URI} !^/(library/fckeditor)/
    RewriteCond %{REQUEST_URI} !^/(library/fckeditorPlugins)/
    RewriteCond %{REQUEST_URI} !^/(library/syntaxhighlighter_2.0.320)/
    RewriteRule ^(.*)$ /public/$1
 
 
    # Never rewrite for existing files, directories and links
    # ==============================================
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^public/.*$ /public/index.php [NC,L]
 
</IfModule>

 

 

Posted in Zend Framework | Tagged , | 1 Comment

301 Redirect for Url SEO

Let’s make the example of this site :

 

1. www.kimbs.cn

2. kimbs.cn/

3. www.kimbs.cn/index.html

4. www.kimbs.cn/index.php

5. kimbs.cn/index.php

 

They are all the same in fact. We now redirect all of them to http://kimbs.cn in order to raise the PR(PageRange).

 

In .htaccess :

# url canonicalization
RewriteCond %{HTTP_HOST} ^www.kimbs.cn [NC]
RewriteRule ^(.*)$ http://kimbs.cn/$1 [L,R=301]

 

Easy, isn’t it? But also very important and please neglect it though minor issue.

Posted in SEO | Tagged | Leave a comment

Setting Up Zend Framework

How to setting up your Zend Framework environment? This is an old question since 1st version released at 1st July, 2007. Here I will show you some of my experience as much as possible.

 

1.  php set up

 

Php download : http://www.php.net/downloads.php

 

Ver.5.29 is recommended as the steady version before php6.

Requirements here : http://framework.zend.com/manual/en/requirements.html

 

Installing php : http://www.php.net/manual/en/install.php

 

And I won’t teach you how to setting up your apache and mysql(mssql).

Apache docs : http://httpd.apache.org/docs

Mysql docs : http://dev.mysql.com/doc/

 

Ok, you are lazy, then the following softwares must fit you :

xampp : http://www.apachefriends.org/en/xampp.html

Zend Core : http://www.zend.com/en/downloads/

wamp : http://www.wampserver.com/ (only for windows)

 

PS : Please enable your rewrite_module of apache as it’s in use for most scenes. And also expires_module because of performance optimize in furture.

 

2.  Zend Framework download and installation

 

Download latest : http://framework.zend.com/download/latest

 

Installation guide from official : http://framework.zend.com/manual/en/introduction.installation.html

 

The trunk will be really the best for you in getting fresh if you are familiar with SVN :

http://framework.zend.com/svn/framework/standard/trunk

 

Un-zip your Zend Framework package and put the Zend folder within your library as something like :

./library/Zend/

 

Then we should make it into your include_path with several ways :

 

(1) In php.ini :

For unix : include_path = ".:/www/library"

For windows : include_path = ".;c:\www\library"

 

(2) Within .htaccess :

For example : php_value include_path ".:path"  (not for linux)

 

(3) Within your application which is best flexible and optimizing :

For example : set_include_path(‘/www/myproject/library’ . PATH_SEPARATOR . ‘other/path/’ . PATH_SEPARATOR);

 

PS : We usually put the path of Zend Framework at the first place in order to reduse the scanning time.

 

3.  Start with Zend Framework

 

Test in your index.php with :

[codesyntax lang=”php”]

require_once 'Zend/Version.php';
echo Zend_Version::VERSION;

[/codesyntax]

 

Ok, you see it? Then going on to enjoy the powerful Zend Framework library.

 

The nabble community is famous and is the right place to answer your questions :

http://www.nabble.com/Zend-Framework-Community-f16154.html

 

For sure the quickstart from official is basic and helpful : 

http://framework.zend.com/docs/quickstart

 

And the next is <<getting started with the zend framework>> by Rob Allan :

http://akrabat.com/zend-framework-tutorial/

 

What about the books? Here are some of them.

« Zend Framework in action » – http://www.zendframeworkinaction.com

« Guide to Programming with Zend Framework » – http://www.phparch.com/c/books/id/9780973862157

« ZF Certification Study Guide »http://www.zend.com/community/downloads

« ZF Programmer’s Reference Guide »http://www.zend.com/community/downloads

 

The first two are good for newers and the third one is for someone who want to pass the Certification of Zend Framework which is really professional. There is nothing to say about the Reference Guide as you can’t live without it everyday.

 

Posted in Zend Framework | Tagged | Leave a comment