Wednesday, December 26, 2012

TOP 5 most popular PHP frameworks of 2012

TOP 5: Google Trends 2012

Let’s look at what people were searching for this year. I’ve put five assumingly most-popular frameworks and that’s what I’ve got:



If we look at the exact numbers, the TOP 5 looks like this: Codeigniter: 90 Yii: 62 CakePHP: 61 Symfony: 50 Zend Framework: 44 Of course, we cannot really judge about popularity only from the amount of searches. So we dig deeper.

TOP 5: Google Search Results 2012

Second test I’ve performed was just a search on the keyword in Google and then narrowed it to “Past year”. Here are the approximate amount of the results:

  • Yii: 861 000 
  • Codeigniter: 660 000 
  • CakePHP: 606 000 
  • Zend Framework: 465 000 
  • Symfony: 329 000 

Of course, again, here we have some extra factors. This amount is only approximate and it might depend on my computer – you know, every one of us get slightly different search results on Google. But, as I understand, the difference is in the ordering of the results, but not so much in the total amount of it.

TOP 5: Job search (oDesk + Elance)

The third and final part of my mini-research was job boards for freelancers. I’ve searched two of them – oDesk.com and Elance.com. Again, the test was simple – just putting the keyword into the text-based search field and counting the amount of results. Here we go:

  • Codeigniter: 136 (101 from oDesk + 35 from Elance)
  • CakePHP: 124 (79 + 45)
  • Zend Framework: 54 (39 + 15) Yii: 47 (30 + 17)
  • Symfony: 40 (27 + 13)

As we can see, in this case we have two clear leaders. Overall result and conclusions
So what can we take from these mini-tests?

  • According to the best performance in all these tests, the best framework in the market is CodeIgniter.
  • Zend Framework is on a decline. If we compared the data to 2008-2009, we would have found bigger numbers on that framework. I am not saying it is not worth to check out, but it seems that developers switch to something new and fresh from this old framework. I have worked with it on several projects and can also recommend it for your needs. 
  • Yii is really worth to check out. If we believe these numbers, there are a lot of articles on this one, and perhaps it is only a matter of time for job boards ads to be higher for Yii.
  • CakePHP is a really good perspective in terms of job and project search.
  • Symfony is not that popular. Strong fifth place, of course, is not so bad – none of other frameworks I tried to bring to this survey showed similar results.

How to test your regular expression (regex)?

I found a perfect website for this job. http://regexpal.com/

Jquery, Javascript – .replace is not a function

Basically, I wanted replace some part of a string then trim white space from the beginning and end of a string. The standard answer on the internet is as follows:

var text = "asd (Some text)";
var txt = text.match(/([a-zA-Z0-9 ]*)/g);
txt = txt.replace("text", '');
txt = $.trim(txt);

I eventually realized that “.replace” is only a function when the operand is a string; in my case, selectedtext was an object, and therefore I needed to cast it to a string, as follows:

txt = txt.toString().replace("text", '');

This then gave me the correct result.

Tuesday, November 6, 2012

Debugging in Zend Framework

Perhaps “debugging” is a bit too strong. However when you’re dumping an array in PHP, you’d probably prefer the print_r or var_dump.

echo '<pre>';
print_r($array);
echo '</pre>';

But did you know that in Zend Framework there’s a built in Zend_Debug?

Zend_Debug::dump($array);

Monday, November 5, 2012

POST with Zend_Http_Client

It’s a well know fact that you can preform HTTP requests with CURL. Zend Framework does the same job with Zend_Http. Especially Zend_Http_Client can be used to “replace” the usual client – the browser, and to perform some basic requests.

I’ve seen mostly GET requests, although Zend_Http_Client can perform various requests such as POST as well.

// new HTTP request to some HTTP address
$httpClient = new Zend_Http_Client('http://www.example.com/');
// GET the response
$response = $httpClient->request(Zend_Http_Client::GET);

Here’s a little snippet showing how to POST some data to a server.

// new HTTP request to some HTTP address
$client = new Zend_Http_Client('http://www.example.com/');
// set some parameters
$client->setParameterPost('name', 'value');
// POST request
$response = $client->request(Zend_Http_Client::POST);

Note that the request method returns a response. Thus if you are simulating a form submit action you can “redirect” to the desired page just like the form.

// new HTTP request to some HTTP address
$client = new Zend_Http_Client('http://www.example.com/');
// set some parameters
$client->setParameterPost('name', 'value');
// POST request
$response = $client->request(Zend_Http_Client::POST);
//echo $response->location;
ecgo $response->getBody();

If you want to send Authenticated POST Request with Zend_Http_Client, then you need to add the following parameter.

$client->setAuth('test_usernaem', 'test_password', Zend_Http_Client::AUTH_BASIC);

original post

Thursday, October 11, 2012

Maximum length for MySQL TEXT field types

MySQL supports 4 TEXT field types (TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT) and this post looks at the maximum length of each of these field types.

MyISAM tables in MySQL have a maximum size of a row of 65,535 bytes, so all the data in a row must fit within that limit. However, the TEXT types are stored outside the table itself and only contribute 1 to 4 bytes towards that limit. (For more information about this refer to the MySQL Manual - Data Storage Requirements chapter).

TEXT data types are also able to store much more data than VARCHAR and CHAR text types so TEXT types are what you need to use when storing web page or similar content in a database.
The maximum amount of data that can be stored in each data type is as follows:
TINYTEXT256 bytes
TEXT65,535 bytes~64kb
MEDIUMTEXT 16,777,215 bytes~16MB
LONGTEXT4,294,967,295 bytes~4GB
In most circumstances the TEXT type is probably sufficient, but if you are coding a content management system it's probably best to use the MEDIUMTEXT type for longer pages to ensure there are no issues with data size limits.

HOWTO: Include Base-64 Encoded Binary Image Data (data URI scheme) in Inline Cascading Style Sheets (CSS)


If you've ever looked at the code for some of the more popular mobile web-portals, you might have noticed that many of them include base-64 encoded binary image data in their cascading style sheets.  For example, Google's iPhone portal uses this content delivery mechanism to deliver image content to mobile browsers.  Here's an example using an inline style sheet to define the background-image of a <div>.  Note that the GIF image data itself is embedded inside of the CSS:

<style type="text/css">
 div.wrapper {
   background-image: url(data:image/gif;base64,R0lGODdhAQAgAMIIABstehsv
      fRwwgR4zhB81iiA3jSE6kvf6/ywAAAAAAQAgAAADDji21U1wSClqDRjow08CADs=);
 }
</style>

FWIW, I'm line-wrapping the base-64 encoding binary data above.  However, normally you don't want to line-wrap binary data when including it in an inline CSS declaration.  I'm simply wrapping above for display purposes. Here's a more complete, yet quick example.

As defined by the RFC 2397, the accepted syntax/format of data URI's are as follows:

data:[<mediatype>][;base64],<data>

1 - Why Is This Important/Useful?

You might ask, why would I ever care about this?  Simple: if done correctly, embedding binary image data in your CSS can dramatically improve page loading time on mobile devices.  For example, when a browser downloads and renders a page, it first downloads the HTML.  After parsing the HTML and accompanying CSS, it then begins to load all of the resources that make up the page itself.  These resources may include scripts, other CSS files, and of course, images.  For each additional resource the browser needs to load, it opens another HTTP connection to the web-server, which may or may not be an expensive operation.  If a wireless network is extremely busy, the mobile device may have to wait a few cycles before it can transmit its request.  Further, the device may also need to wait a bit for a response.  All the while, the user is staring at their mobile device waiting for your page to load.

To avoid this HTTP connection overhead on slower wireless networks, many mobile web-portals embed static binary image data directly in their CSS.  This can be very beneficial, because when the device downloads and renders the HTML and inline CSS, it doesn't need to open any additional connections over a slow wireless network.  In other words, everything the device needs to render the page in its browser is downloaded through a single HTTP request/response.  TCP transfers tend to start slowly, so this method helps alleviate the connection cycle bottleneck.

This type of optimization is one of the many reasons why popular mobile portals like Google's iPhone homepage appears to load so quickly on a cell-network.


2 - Base-64 Encoding Images

Before you run out and redo your entire site with images embedded in your CSS, you should know that on average base64-encoded data takes about 33% more space than the original data.  So if your site is ridiculously image heavy, base-64 encoding your image data isn't going to help; in fact, it might even make things worse.  Ideally, you should only base-64 encode and embed image content that's used repeatedly across your site.  Static icons or hover images for an on-mouse-over effect are often ideal candidates.

If your mobile site is using HTTP compression, then you may not even see much of a jump in bandwidth usage even if base-64 encoded images use up to 33% more bandwidth.

In PHP, you can base-64 encode an image using the base64_encode function.  Here's a quick PHP app I wrote up in a few minutes that should work nicely:

<?php

// NOTE: This script is probably not fool proof, so there might be some
// holes in it. I would not recommend you place this app in any publicly
// accessible directory on your web-server. Use at your own risk.

$uploadedFile = (isset($_FILES['uploadedfile']))
                        ? $_FILES['uploadedfile'] : null;

if(empty($uploadedFile)){
 $self = $_SERVER['PHP_SELF'];
 ?>
 <html>
  <body>
  <h2>Base-64 Encode An Uploaded File</h2>
  <form enctype="multipart/form-data" action="<?= $self; ?>" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
    Choose a file to upload: <input name="uploadedfile" type="file" /><br />
    <input type="submit" value="Encode File" />
  </form>
  </body>
 </html>
 <?
}
else {

 $fileToEncode = $_FILES['uploadedfile']['tmp_name'];
 $fp = @fopen($fileToEncode,"r");
 $buffer = "";
 if(!$fp){
    echo "ERROR opening file on server.";
 }
 else {
    while(!feof($fp)) {
      $buffer .= fgets($fp,4096);
    }
 }
 @fclose($fp);

 // Use the base64_encode() function to base-64
 // encode the file contents.
 echo base64_encode($buffer);

}

?>

If you have access to a Linux box with a decent distribution on it, you can use thebase64 command to encode an image file.  The base64 command is included with the GNU coreutils package:

#/> base64 -w0 img.jpg > img.b64

The -w0 argument instructs the base64 command to disable line-wrapping.  When including binary image data in your CSS, you cannot include line breaks.


3 - Browser Support

IE 8, Firefox 2 and 3, Safari, Mobile Safari (iPhone browsers), and Google Chrome support embedded binary image data in CSS files.  Not surprisingly, IE 6 and 7 does NOT.  This means that you probably shouldn't use inline binary image data in your CSS for all versions of your mobile and non-mobile site.  If you run a mobile site that's just for the iPhone, or another browser that supports inline binary image data, then you should be fine.


4 - An Example

I whipped together a very quick example showing you how you can embed binary image data into an inline cascading style sheet.  In the example, I'm using a GIF and a PNG to illustrate my point.  Take a look at the HTML/CSS source of the example to see how I'm embedding binary image data in my inline stylesheet.


5 - Additional Notes

You should also note that the RFC 2397 data URI scheme can be used on <img>'s too:

<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />

Remember, you can pretty much use the data URI scheme anywhere in a browser that supports it.  If you have a mobile web-portal, and want to improve the loading time of your pages, this might be a useful enhancement to consider.

Friday, September 21, 2012

How to improove the performance of your webpage with .htaccess


# ----------------------------------------------------------------------
# Webfont access
# ----------------------------------------------------------------------

# Allow access from all domains for webfonts.
# Alternatively you could only whitelist your
# subdomains like "subdomain.example.com".

<FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>



# ----------------------------------------------------------------------
# Proper MIME type for all files
# ----------------------------------------------------------------------


# JavaScript
#   Normalize to standard type (it's sniffed in IE anyways)
#   tools.ietf.org/html/rfc4329#section-7.2
AddType application/javascript         js

# Audio
AddType audio/ogg                      oga ogg
AddType audio/mp4                      m4a

# Video
AddType video/ogg                      ogv
AddType video/mp4                      mp4 m4v
AddType video/webm                     webm

# SVG.
#   Required for svg webfonts on iPad
#   twitter.com/FontSquirrel/status/14855840545
AddType     image/svg+xml              svg svgz
AddEncoding gzip                       svgz
                                     
# Webfonts                          
AddType application/vnd.ms-fontobject  eot
AddType application/x-font-ttf    ttf ttc
AddType font/opentype                  otf
AddType application/x-font-woff        woff

# Assorted types                                    
AddType image/x-icon                   ico
AddType image/webp                     webp
AddType text/cache-manifest            appcache manifest
AddType text/x-component               htc
AddType application/x-chrome-extension crx
AddType application/x-xpinstall        xpi
AddType application/octet-stream       safariextz
AddType text/x-vcard                   vcf


# ----------------------------------------------------------------------
# Gzip compression
# ----------------------------------------------------------------------

<IfModule mod_deflate.c>

# Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
<IfModule mod_setenvif.c>
  <IfModule mod_headers.c>
    SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
    RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
  </IfModule>
</IfModule>

# HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
<IfModule filter_module>
  FilterDeclare   COMPRESS
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
  FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
  FilterChain     COMPRESS
  FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
</IfModule>

<IfModule !mod_filter.c>
  # Legacy versions of Apache
  AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
  AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
  AddOutputFilterByType DEFLATE image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
</IfModule>
</IfModule>



# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------

# These are pretty far-future expires headers.
# They assume you control versioning with cachebusting query params like
#   <script src="application.js?20100608">
# Additionally, consider that outdated proxies may miscache
#   www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/

# If you don't use filenames to version, lower the CSS  and JS to something like
#   "access plus 1 week" or so.

<IfModule mod_expires.c>
  ExpiresActive on

# Perhaps better to whitelist expires rules? Perhaps.
  ExpiresDefault                          "access plus 1 month"

# cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5)
  ExpiresByType text/cache-manifest       "access plus 0 seconds"

# Your document html
  ExpiresByType text/html                 "access plus 0 seconds"

# Data
  ExpiresByType text/xml                  "access plus 0 seconds"
  ExpiresByType application/xml           "access plus 0 seconds"
  ExpiresByType application/json          "access plus 0 seconds"

# Feed
  ExpiresByType application/rss+xml       "access plus 1 hour"
  ExpiresByType application/atom+xml      "access plus 1 hour"

# Favicon (cannot be renamed)
  ExpiresByType image/x-icon              "access plus 1 week"

# Media: images, video, audio
  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"
  ExpiresByType video/ogg                 "access plus 1 month"
  ExpiresByType audio/ogg                 "access plus 1 month"
  ExpiresByType video/mp4                 "access plus 1 month"
  ExpiresByType video/webm                "access plus 1 month"

# HTC files  (css3pie)
  ExpiresByType text/x-component          "access plus 1 month"

# Webfonts
  ExpiresByType font/truetype             "access plus 1 month"
  ExpiresByType font/opentype             "access plus 1 month"
  ExpiresByType application/x-font-woff   "access plus 1 month"
  ExpiresByType image/svg+xml             "access plus 1 month"
  ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
 
# CSS and JavaScript
  ExpiresByType text/css                  "access plus 1 year"
  ExpiresByType application/javascript    "access plus 1 year"

  <IfModule mod_headers.c>
    Header append Cache-Control "public"
  </IfModule>

</IfModule>



# ----------------------------------------------------------------------
# ETag removal
# ----------------------------------------------------------------------

# FileETag None is not enough for every server.
<IfModule mod_headers.c>
  Header unset ETag
</IfModule>

# Since we're sending far-future expires, we don't need ETags for
# static content.
#   developer.yahoo.com/performance/rules.html#etags
FileETag None


# "-Indexes" will have Apache block users from browsing folders without a default document
# Usually you should leave this activated, because you shouldn't allow everybody to surf through
# every folder on your server (which includes rather private places like CMS system folders).
Options -Indexes


# Block access to "hidden" directories whose names begin with a period. This
# includes directories used by version control systems such as Subversion or Git.
<IfModule mod_rewrite.c>
  RewriteRule "(^|/)\." - [F]
</IfModule>

Analyze Performance of your Webpage


Link: http://gtmetrix.com/

What is a cookie-free domain?

A domain that serves no cookies. The idea here is that you use a cookie-free domain to serve images, CSS files, scripts and whatnot, so that your users don't waste time and bandwidth transmitting cookies for them. SO uses sstatic.net for the purpose, for example.

The main reason the concept is of any note is that most people can't use a subdomain of their main domain to do this (like SO couldn't use static.stackoverflow.com) because they serve cookies that are valid across the entire second-level domain. Source: http://serverfault.com/questions/78227/what-is-a-cookie-free-domain

Tuesday, September 11, 2012

Zend Framework 2.0.0 STABLE Released!

New features, new capabilities, and a new MVC model: the most popular PHP framework is now better than ever! Take advantage of new components like ModuleManager, EventManager and Zend\Crypt to build the best PHP apps ever.

Learn more about  Zend Framework 2.0.0
You can download Zend Framework 2.0.0 from here

Wednesday, August 22, 2012

SVN: Update To Older Revision

This will come in handy if the current revision that you’ve updated to had a problem. svn update -r REV or svn merge -r HEAD:REV, where REV is the previous revision number and HEAD is the head revision before the problem occur.

Tuesday, August 21, 2012

Php: Get dates by week number

Given a week number, how do you calculate the days in that week starting from Monday?

$week_number = 40; 
$year = 2008; 
for($day=1; $day<=7; $day++) { 
       echo date('m/d/Y', strtotime($year."W".$week_number.$day))."\n"; 
}

Thursday, August 9, 2012

meta name="viewport"

Nowadays, the new generations of mobile browsers can render full web pages (desktop version) without any problems and scale them to fit nicely inside the mobile browser’s visible viewport. The user then can zoom in on areas of interest and pan around on the page using touch, or keypad that depending on the mobile devices. This may not sounds user-friendly for mobile users, because if the web page loaded is wider than 320px, everything in the page were too small to read without zooming.
Now, we have a solution to solve it by telling the mobile browsers to render the page according to the mobile devices using “viewport meta tag“.

In order to define mobile’s viewport, you have to include a viewport meta tag in the <head> section of your HTML document as shown below:

<meta name="viewport" content="width=device-width, minimum-scale=0.5, maximum-scale=1.0,
    user-scalable=no, target-densitydpi=device-dpi"/>
<meta name="viewport" content="width=device-width, minimum-scale=0.5, maximum-scale=3.0,
    user-scalable=yes, target-densitydpi=device-dpi"/>
<meta name="viewport" content="width=640,          minimum-scale=0.5, maximum-scale=3.0,
    user-scalable=yes, target-densitydpi=device-dpi"/>
  • width=device-width will tell the browsers to use the native resolution of the phone.
  • target-densitydpi=device-dpi is needed for the phones with Android and a high-resolution (or high-dpi, example screens with 480x800, like Samsung Galaxy S) to not zoom. Note that the target-density is at the end of the content attribute. This is because it is unrecognised by iPhone and if iPhone encounters and unrecognised option in the viewport content attribute it stops parsing and will ignore the rest of the string.
  • device-dpi: Use the device’s native dpi as the target dpi. Default scaling never occurs.
  • high-dpi: Use hdpi as the target dpi. Medium and low density screens scale down as appropriate.
  • medium-dpi: Use mdpi as the target dpi. High density screens scale up and low density screens scale down. This is also the default behavior.
  • low-dpi: Use ldpi as the target dpi. Medium and high density screens scale up as appropriate.
  • maximum-scale=1.0 together with user-scalable=no is there to forbid zooming in. If the page is optimized for the mobile resolution it's ok to disable it.
  • maximum-scale=3.0 together with user-scalable=yes can be used to let the freedom to the users to make the fonts/links/images bigger. Just one note here. Once the user applies his own zoom on the page there is no way with JavaScript to get the native screen resolution.
  • minimum-scale=0.5 is a little bit tricky. The 0.5 is there for the iPhone 4. This device under normal conditions is rendering images 320px wide to the full screen width, which means zooming them in => 320px images is shown on the full width of 640px wide screen. I found just one way to force iPhone 4 to show 640px images natively (without width attribute) and that is to set width=640 in the viewport meta tag. The problem is that the only way to recognize iPhone 3 from iPhone 4 is via JavaScript and window.devicePixelRatio == 2. But the JavaScript is a little bit too late for the content of the page.
  • width=640 setting the proper (fixed) width is also necessary for the windows mobile phones with IE in order to have the native resolution.

This is not all. There are device databases (WURFLDeviceAtlas) that collect user-agent strings and helps to provide screen widths to the mobile page rendering engines, but for an Opera Mini & Opera Mobile the user-agent string is the same/similar for all kinds of devices. And the change of device orientation is also worth to consider, as just by turning the phone around, width of the screen changes from 480px to 800px.The only way to get the screen resolution is in JavaScript, but that is too late, the page is already there...
One solution I've described in the beginning and that is to let the browser scale down the high-resolution pictures. This works for the modern phones and is not too bandwidth friendly (providing 640px wide images to all types of phones) and not so reliable with the old phones either. Another solution, that I'm testing currently, is to try to guess the screen width as good as possible based on user-agent string and then use JavaScript to get the proper screen width, reloading the page with a cookie set if necessary (if the width is not what was expected) or having the proper width set for the next page request.

Monday, July 9, 2012

jQuery 2.0 Drops Support for IE6, 7 and 8

In a surprise announcement on the jQuery blog the team has decided that jQuery 1.9 will be the last edition to support legacy editions of Internet Explorer. jQuery 2.0 — planned for release in 2013 — will no longer support IE6, 7 and 8.

In essence, jQuery 2.0 will be a leaner, faster library without old IE bloat such as DOM selection routines, different event models and HTML5 shims. jQuery 1.9 will continue to be developed and support the older IEs. The team advise that you’ll be able to support every browser using conditional comments, e.g.

<!--[if lt IE 9]>
    <script src="jquery-1.9.0.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
    <script src="jquery-2.0.0.js"><</script>
<!--<![endif]-->
 
No one expects old editions of IE to be supported forever and some will applaud the decision to abandon browsers which have caused development grief for many years. But the statement is surprising for several reasons.
First, while IE6 and 7 usage has fallen to below 2%, they remain the browsers of choice for many large corporations, government departments and the Chinese. IE8 is likely to fall below 10% by 2013 but it’s the latest edition available to those on Windows XP. Almost one in three people use the OS and, while it’s dying, it’s lingering far longer than Microsoft anticipated.

[The following section has been revised. Thanks to everyone who pointed out the error in the original code.]

Second, conditional comments. Really? We’re still resorting to browser detection in 2013? That practice should have died out in 1999. Conditional comments were a temporary hack and have been dropped in IE10. JavaScript or server-side browser sniffing is no better.

It also introduces the problem of having two forked code bases for the same library. Inevitably, there will be bugs and differences between 1.9 and 2.0 — especially as jQuery evolves beyond those editions. What do you do when your code works in one but not the other?

Third: the primary reason developers use jQuery is to circumvent browser compatibility issues. The original purpose of jQuery, Prototype, Mootools, YUI and similar libraries was to provide a consistent set of objects and methods which abstracted the differing browser APIs. Wrappers are placed around features such as DOM selection and event delegation to smooth out implementation wrinkles.

Today, the differences between modern browsers is negligible. Consider the DOM querySelectorAll(CSS selector) method; it’s supported everywhere (even in IE8) and will always be faster than jQuery’s $(CSS selector). Core JavaScript features such as traversal, manipulation, events and Ajax are usable everywhere. jQuery’s animations and effects can also be replaced by CSS3. jQuery 2.0 will still provide useful utilities and compatibility fixes but, without legacy IE support, there’s less reason to use it.

Fourth is the confusion the update will cause. Currently, developers can usually migrate to the latest version without breaking their scripts. It doesn’t matter how much publicity jQuery 2.0 receives, many people will think it’s “better” than version 1.9. They’ll upgrade then complain bitterly when their site fails in IE7.

Saturday, July 7, 2012

Zend Framework 2.0.0beta5 Released!


The Zend Framework community is pleased to announce the immediate availability of Zend Framework 2.0.0beta5. Packages and installation instructions are available at: http://packages.zendframework.com/
This is the fifth and last in a series of planned beta releases. The beta release cycle has followed the "gmail" style of betas, whereby new features have been added in each new release, and backwards compatibility (BC) has not been guaranteed. The desire has been for developers to adopt and work with new components as they are shipped, and provide feedback so we can polish the distribution.
Our plan at this time is to do some cleanup of the repository, fix some outstanding issues and features, migrate documentation to a new repository and format, and then begin the release candidate process. At this time, we anticipate few if any BC breaks between now and the first release candidate (RC). Applications built today on beta5 will operate in the way we expect them to for the stable release.
Beta5 had a rigorous and busy schedule. We tackled a number of consistency issues, and solidified the security the framework offers via several fixes and the new Escaper component. We processed over 400 pull requests again, in a shorter timeframe than we had for beta4; the community really pulled together to get this release out the door.
There are three primary new features for the release:
  • Zend\Escaper, which provides an OWASP-compliant solution for context-specific escaping mechanisms targetting HTML, HTML attributes, URLs, CSS, and JavaScript.
  • Zend\I18n, which leverages PHP's ext/intl extension to provide localization, and also provides a new translation component.
  • Zend\Form now has new annotation support, allowing you to define annotations in your domain entities that can then be used to build a form and its related input filter and hydrator. Annotation support now has a dependency on Doctrine\Common's annotation library, for our default annotation syntax parser.

Monday, July 2, 2012

jQuery 1.8 goes beta and grunts custom versions

Customisation is key to the just announced beta 1.8 version of the jQuery JavaScript library. It is now possible to exclude modules from jQuery using a new build system based on grunt; this allows developers to drop modules for ajax, css, dimensions, effects or offset, depending on what their web application actually needs, reducing the amount of jQuery code downloaded to the browser. With all those modules excluded, jQuery is a lean 21KB (minified and gzipped), but the developers stress this is an optional process and they will continue distributing the complete library through content delivery networks. Details of the build system are available in the README file.

 jQuery 1.8 beta also aims to ease the pain of vendor prefixes for CSS features that aren't yet standardised by automatically expanding property names for the current browser through the .css() function. A cleanup and rework of the animation engine has been so extensive, that there are now new extension points that should make it easier to add or modify animations, but documentation is currently sparse. The Sizzle CSS selector engine has also had a major rewrite resulting in a "widespread performance improvement", enhanced shortcuts and better handing of more edge cases and browser bugs.

The developers are also warning that in jQuery 1.9, the version after 1.8, they will be tightening up on the HTML taken by the $()function. This is because cross site scripting attacks could make use of the behaviour of the function to execute code in <script> tags. jQuery will become more careful about what it accepts as HTML code within $(), only allowing strings which start with "<" to be regarded as such. Preceding that tightening, jQuery 1.8 has a new method, $.parseHTML which lets the system turn strings into HTML and parse HTML into DOM fragments.

jQuery 1.8 beta also marks the removal or deprecation of a number of "trip hazards" including $.browser browser detection, $.sub which failed to be useful or robust enough and global ajax events which had become an inefficient special case. Full details of the changes in jQuery 1.8 beta 1 can be found at the end of the announcement. The MIT or GPLv2 licensed jQuery 1.8 beta 1 can be downloaded and the source is available from the project's Github repository.

Most Used PHP Framework-The Popular Top 7 List in year 2011







You can read the original post here : http://www.php-developer.org/most-used-php-framework-the-popular-top-7-list-in-year-2011/

Tuesday, June 12, 2012

jQuery++

It is a collection of extremely useful DOM helpers and special events for jQuery 1.7 and later. I’m not a UI project likejQuery UI or jQuery Tools. Instead, I’m all about providing low-level utilities for things that jQuery doesn’t support.

Link: http://jquerypp.com/

Wednesday, June 6, 2012

Zend Framework 2 Beta 4 is Available!

The Zend Framework 2 team is proud to announce the next-to-last beta release, with over 400 bug fixes and feature requests. The MVC layer is now stable, so this is your chance to give it a try!


Learn more »
Download packages »

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

Friday, April 27, 2012

How to deny access to .ini files with htaccess?

<Files *.ini>
deny from all
</Files>

or

<Files my.ini>
order deny,allow
deny from all
</Files>

Useful color scheme designer for w3b d3sign3rs


Color Scheme Designer (CSD) is a web application designed to easily create set of matching color. Color theory used by artists for centuries was transformed into algorithms to combine color they go best together while avoiding uncomfortable combinations.

Color scheme designer : http://colorschemedesigner.com/
Color scheme designer blog : http://www.colorschemedesigner.com/blog/