Friday, May 25, 2012

CSS Sprites: What are they are, why they’re cool, and how to use them

Sprite example

The name might be a little misleading, because sprites aren't little images like you might be picturing, a sprite is actually one big image. Have you ever seen the CSS technique where the "on" and "off" states of a button are contained within the same image and are activated by shifting the background-position?

Think of CSS Sprites as an extension of that technique. The difference is that instead of just two or three images being combined into one, you can combine an unlimited number of images into one. The origin of the term "sprites" comes from old school computer graphics and the video game industry. The idea was that the computer could fetch a graphic into memory, and then only display parts of that image at a time, which was faster than having to continually fetch new images. The sprite was the big combined graphic. CSS Sprites is pretty much the exact same theory: get the image once, shift it around and only display parts of it, saves the overhead of having to fetch multiple images.

Url to post: http://css-tricks.com/css-sprites/

How to detect browser version with jquery

var detectBrowserVersion = function() {
    var userAgent = navigator.userAgent.toLowerCase();
    $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
    var version = 0;

    // Is this a version of IE?
    if($.browser.msie){
        userAgent = $.browser.version;
        userAgent = userAgent.substring(0,userAgent.indexOf('.'));   
        version = userAgent;
    }

    // Is this a version of Chrome?
    if($.browser.chrome){
        userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
        userAgent = userAgent.substring(0,userAgent.indexOf('.'));   
        version = userAgent;
        // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
        $.browser.safari = false;
    }

    // Is this a version of Safari?
    if($.browser.safari){
        userAgent = userAgent.substring(userAgent.indexOf('safari/') +7);   
        userAgent = userAgent.substring(0,userAgent.indexOf('.'));
        version = userAgent;   
    }

    // Is this a version of Mozilla?
    if($.browser.mozilla){
        //Is it Firefox?
        if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
            userAgent = userAgent.substring(userAgent.indexOf('firefox/') +8);
            userAgent = userAgent.substring(0,userAgent.indexOf('.'));
            version = userAgent;
        }
        // If not then it must be another Mozilla
        else{
        }
    }

    // Is this a version of Opera?
    if($.browser.opera){
        userAgent = userAgent.substring(userAgent.indexOf('version/') +8);
        userAgent = userAgent.substring(0,userAgent.indexOf('.'));
        version = userAgent;
    }
    //return version;
}

How to use:

detectBrowserVersion();

    if ($.browser.chrome || $.browser.safari) {
        //navigation detection in Chrome browser
        $(document).keydown(function(e){
            dokeypress(e);
        });
   
    } else {
        //detect keypress
        $(document).keypress(function(e){
            dokeypress(e);
        });
    }

Thursday, May 24, 2012

Css3 PIE



PIE makes Internet Explorer 6-9 capable of rendering several of the most useful CSS3 decoration features.

Documentation & Demo: http://css3pie.com/
You can download from : http://css3pie.com/download-latest

Thursday, May 17, 2012

What is an API?

An API, or “Application Program Interface”, is a set of routines and protocols that provide building blocks for computer programmers and web developers to build software applications. In the past, APIs were largely associated with computer operating systems and desktop applications. In recent years though, we have seen the emergence of Web APIs (Web Services).

Web API (Web Service)

Web APIs allow developers to build web pages and web based applications (known as “mashups”) using data from multiple online sources. Although there are Web APIs available for many different types of industries, some of the most popular and widely used ones are in the categories of social networking, mapping, shopping and music.

You can read the full article here : http://net.tutsplus.com/articles/news/the-increasing-importance-of-apis-in-web-development/

Tuesday, May 15, 2012

How to center a div in the middle of the window?

It is very simple. You just have to make a new function like this:

jQuery.fn.center=function(){
    this.css("position","absolute");
    this.css("top",(($(window).height()-this.outerHeight())/2)+$(window).scrollTop()+"px");
    this.css("left",(($(window).width()-this.outerWidth())/2)+$(window).scrollLeft()+"px");
    return this;
}

Now we can just write:
$(element).center();

Monday, May 14, 2012

Remove “.php” extension from URL with .htaccess

In order to have nice URLs you could use various techniques. But in case you have a really simple website with pages written in PHP, and URLs pointing to those PHP files like www.example.com/my-page.php, you could set nice URLs using .htaccess only. Using following snippet will let you have URLs like www.example.com/my-page, and still open your file.

Just use following snippet in order to remove “.php” extension from URL.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/$ $1.php

Use .htaccess to remove double slash from URL

In order to remove double or multiple slash from your URL using only .htaccess you can use following code:

RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]

Use .htaccess to remove www

If you want to have your domain without www, you should consider using htaccess 301 redirection. Using htaccess to remove www is quickest way to setup your domain having unique address, and redirecting users to a non-www address. To achieve this use:

RewriteEngine On 
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

.htaccess redirection

Considering that you want to have nice URLs that are SEO optimized, you would have to pass parameters without using “?”. In this case we can use redirection htaccess. To make simple example, see snippet below:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1
 

Use redirection htaccess:

This redirection snippet will work very well if you have a smaller website, where you have smaller frame written inside of index.php, and you are including some page, by page name. You just need a PHP script that will include this file:

include('/pages/' . $_GET['page'] . '.php');
 
So, by using snippets shown, you will be able to have nice URLs on your website lile: http://example.com/about-us

Security notice on redirection htaccess

Users can trick you by sending URL request like “http://example.com/../../../some-system-data” therefore you should take care of input you are getting through param “page”.

.htaccess block IP

If you have a need to block person or a bot on your website, there is an easy way to do this using htaccess.

order allow,deny
deny from 4.4.4.4
deny from 22.22.22.22
allow from all

After deny from, you will add IP address that you want to block. You can add unlimited number of rows with IP addresses that you want to block.

ErrorDocument 404 with .htaccess

In order to setup custom 404 page, and prevent user from viewing default error page, you can use ErrorDocument 404 in htaccess. Just copy/paste following snippet into your .htaccess file:

ErrorDocument 404 /pages/errorDocument/error404.php
 

More about ErrorDocument directive

ErrorDocument directive doesn’t have to be used only for errors 404, and it can do couple of things except from redirecting your visitor. Using ErrorDocument directive, you can redirect users to another website, as well as print custom message to the user.

Syntax Example :

ErrorDocument error-code some-error-document-file
Here is a snippet with ErrorDocument examples:

ErrorDocument 500 http://example.com/
ErrorDocument 404 /pages/errorDocument/error404.php
ErrorDocument 403 "You are forbidden to access this page!"


.htaccess prevent hotlinking

If you have problems with other websites stealing your bandwidth, and you want to prevent hotlinking, use following snippet and place code in your htaccess file:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mywebsiteurl\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpg|gif|bmp|png)$ http://hotlnk.mywebsiteurl.com/hotlnkingisnotallowed.jpg [L]

Force .htaccess to add www

In order to force your domain using www, you can use following .htaccess snippet. This snippet makes htaccess add www to your domain name.

RewriteEngine on
 
rewritecond %{http_host} ^stuntsnippets.com [nc]
rewriterule ^(.*)$ http://www.stuntsnippets.com/$1 [r=301,nc]

.htaccess force https

To have your website going through secure connection, you can use htaccess redirect. You can redirect all visits from that are not going through https, and force your website to use secure connection by using only htaccess. Us following htaccess snippet to force https.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

ETags and disable ETags with .htaccess

About Etags (text fom Wikipedia):
An ETag, or entity tag, is part of HTTP, the protocol for the World Wide Web. It is one of several mechanisms that HTTP provides for cache validation, and which allows a client to make conditional requests. This allows caches to be more efficient, and potentially saves bandwidth, as a web server does not need to send a full response if the content has not changed. ETags can also be used for optimistic concurrency control, as a way to help prevent simultaneous updates of a resource from overwriting each other.

An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource content at that URL ever changes a new and different ETag is assigned. Used in this manner ETags are similar to fingerprints, and they can be quickly compared to determine if two versions of a resource are the same or are different. Comparing ETags only makes sense with respect to one URL – ETags for resources obtained from different URLs may or may not be equal and no meaning can be inferred from their comparison.

To setup ETags on your server, use following htaccess snippet:

FileETag MTime Size
<ifmodule mod_expires.c>
  <filesmatch "\.(jpg|gif|png|css|js)$">
       ExpiresActive on
       ExpiresDefault "access plus 1 year"
   </filesmatch>
</ifmodule>

Sometimes you want to be sure to have ETags disabled. To disable ETags, make sure to include following snippet in your .htaccess file.

Header unset ETag
FileETag None

.htaccess permanent redirect 301

When moving your website from one domain to another, or just simply changing URLs and link, it is a good idea to use htaccess permanent redirect 301, as you users won’t be looking at 404 page. This is not the only benefit from htaccess permanent redirect 301, you get bonus from Google as well. If you are using Google Webmasters Tools, you probably know it is good for your SEO to keep those 301 redirection.

If redirecting to a new domain:
Redirect 301 /one-page.html http://another-domain.com/one-page.html

If doing permanent redirect 301 within a website:
Redirect 301 /one-page http://same-domain.com/?page=one-page

.htaccess increase upload file size

Sometimes we face limitations of file size allowed to be uploaded using our PHP script. To overcome these problems we can simply add following lines to our .htaccess file and increase allowed size of files being uploaded using PHP (or some other scripts).

php_value upload_max_filesize 10M
php_value post_max_size 10M
php_value max_execution_time 300
php_value max_input_time 300
There is an easy way to get current domain name in Zend Framework. To get domain name in Zend Framework – use following snippet

in your view file:
echo $this->serverUrl();

in your controller:
echo $this->view->serverUrl();

Tuesday, May 8, 2012

How to delete all files older than 10 days with PhP?

$basedir = BASE_DIRECTORY . "/logs/";
$count = 0;

$files = glob($basedir . "/*");
if(!empty($files)){
    foreach($files as $file) {
        if(is_file($file) && time() - filemtime($file) >= 10*24*60*60) { // 10 days
            unlink($file);
            $count++;
            //print $file."\n";
        }
    }
}
print "\n -------- Files deleted : $count ---------- \n";die;

Monday, May 7, 2012

How to import csv file in PHP?

$row = 1;
if (($handle = fopen("path_to_your_csv_file", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

How to use Zend_Date?

# Example 1 
$datetime = Zend_Date::now(); 

# Example 2 
Zend_Date::now()->toString(); 
Zend_Date::now()->getTimestamp(); 

# Example 3 
$myDate = new Zend_Date(strtotime('2007-07-13'));
$myDate->toString("dd.MM.YYYY");

# Example 4 
$date = new Zend_Date(); 

// Setting of a new time 
$date->set('13:00:00',Zend_Date::TIMES); 
print $date->get(Zend_Date::W3C);

Documentation on framework.zend.com