Category: PHP

problems uploading large files in php5-fpm and nginx – and solution to that

Today I had encountered a strange error while importing a 10MB XML file in a low end vps, where nginx was configured with php5-fpm and was working pretty nicely. But then, whenever I tried to import that file, after 25% upload the connection drops and page goes blank. It was strange and drove me nuts for some time. I definitely re checked my php.ini settings and everything was fine there, upload_max_filesize was set to 20M and post_max_size was set to 32M. So it was good and definitely not causing any problem. Then I was thinking that something was wrong with nginx config, specially because the connection was dropped in the middle. And guess what, I was actually right 🙂

So I edited the nginx.conf file and added the following values. I actually tried with just “client_max_body_size” but it was not the cause alone. So client_body_timeout fixed it together 🙂

[sourcecode language=”shell”]
client_max_body_size 100m;
client_body_timeout 600s;
[/sourcecode]

After restarting nginx, everything went just perfectly 🙂

Caching Ajax requests in WordPress

In modern WordPress themes, theme developers are serving the page requests via ajax. Both paginated blog page and single posts (might be in full or partial) are served. Though WordPress is very fast if properly tuned, but it’s meaningless to pull the same data from WordPress database again and again unless there is any change. Which means, you can safely cache such ajax requests and reduce loads on your database by adding a few lines of extra code in your theme’s functions.php. In this article, we will learn how to take advantage of such caching in WordPress

Step 1: Register Ajax callback for serving paginated blog pages
Here is a typical codeblock that can serve paginated blog pages via ajax. There is no caching yet
[sourcecode language=”php”]
add_action("wp_ajax_blog", "get_blog");
add_action("wp_ajax_nopriv_blog", "get_blog");

function get_blog(){
global $post;
$page = $_REQUEST[‘page’];
if(!$page) $page=1;
$pp = get_option("posts_per_page");
$offset = ($page*1-1)*$pp;
$args = array(
"posts_per_page"=>$pp,
"offset"=>$offset
);
$posts = get_posts($args); //get the posts
foreach($posts as $post){
setup_postdata( $post );
get_template_part("templates/post",get_post_format($post->ID));
}
die();
}
[/sourcecode]

Now if you go to the url “http://your_blog_url/wp-admin/admin-ajax.php?page=1 ” you can see the latest posts, change the page value to 2,3,4 and so on to see previous posts. Each posts in the loop are rendered via get_templates(). Please note how we used the get_post_format() function in the loop to serve different templates based on post formats.

So what is bad in this code? Nothing, yet Everything! If 100 users are visiting your blog and they are visiting blog pages, each and every time these posts are pulled from database. Each and everytime they are pulling the very same data until you had edited any post, or created a new post. So why this extra load should go to DB? lets minimize it 🙂

Step 2: Add caching layer
here is a revised format of the code block above, but now with caching.
[sourcecode language=”php”]
add_action("wp_ajax_blog", "get_blog");
add_action("wp_ajax_nopriv_blog", "get_blog");

function get_blog(){
global $post;
$page = $_REQUEST[‘page’];
if(!$page) $page=1;

/** supply from cache **/
$page_from_cache = get_option( "artpress_page{$page}", 0 );
if($page_from_cache){
die($page_from_cache);
}
/** cache end **/

$pp = get_option("posts_per_page");
$offset = ($page*1-1)*$pp;
$args = array(
"posts_per_page"=>$pp,
"offset"=>$offset

);
$posts = get_posts($args);

ob_start();
foreach($posts as $post){
setup_postdata( $post );
get_template_part("templates/post",get_post_format($post->ID));
}
$new_cache = ob_get_flush();

/** save the cache **/
update_option( "artpress_page{$page}",$new_cache);
/** end cache **/
die($new_cache);
}
[/sourcecode]

In the code above, we first checked the page number. Then, checked in the wordpress options table if there is a cache present with a key named “artpress_page”. Now, for the first time it wont be there. So we just pull the records from the database as usually and then using the output buffering functions we capture the output, instead of pushing instantly to the browser. And then we update the options table with this output. So next time when same page will be requested, database wont be hit. Ok, database will be hit (this options table data is coming from the db) but you can see it wont touch the posts table again, and avoid running expensive queries (which includes many joins) in that table. It also saves CPU a bit.

Step 3: Invalidate cache whenever a post is edited, or created
This is an important step. We need to flush the cache whenever a new post or page is created to make sure our blog shows the up to date data.

[sourcecode language=”php”]
add_action("save_post","invalidate_cache");
function invalidate_cache(){
$counts = wp_count_posts();
$total_published_posts = $counts->publish;
$posts_per_page = get_option( "posts_per_page");
$total_page = ceil($total_published_posts/$posts_per_page);
for($i=1;$i<=$total_page;$i++){
delete_option( "artpress_page{$i}" );
}
}
[/sourcecode]

Now, we are in good shape. Our ajax requests are served from cache and properly purges whenever necessary. You can serve your single post same way.

If you want to serve single posts from the cache, one thing you need to keep in mind is that you are loading up an important table “options” with a lot of data. So you can change the code above and store the cache in filesystem instead of options table. You should have write permission in the uploads directory by default. So that wont be tough at all.

I hope you enjoyed this article 🙂

Displaying comments template when serving a single post via ajax in wordpress

I ran into this issue this morning, the comment form wasn’t showing up. I was using a custom comment template and I thought that there might be some issue with the custom template. So I tried with default template but the result was same. After googling for a while, I’ve found the workaround. Here is the solution for you

[sourcecode language=”php”]
//functions.php
add_action("wp_ajax_single", "get_single");
add_action("wp_ajax_nopriv_single", "get_single");

function get_single(){
error_reporting(0); //see later to understand why it is here
global $post;
$post_id = $_REQUEST[‘id’];
if($post_id){
$post = get_post( $post_id);
setup_postdata( $post );
get_template_part( "templates/single");
die();
}
}
[/sourcecode]

The code above registers an ajax callback for accepting GET/POST calls at “/wp-admin/admin-ajax.php?action=single&id=” and display the single post using the template file located at “templates/single.php” in your current theme.

Now, in the “templates/single.php” you must include the following code-block at the top to make sure the comments_template() function work

[sourcecode language=”php”]
global $withcomments;
$withcomments = true;
[/sourcecode]

Anyway, it was also mentioned in the codex like this, but I was confused as I thought it was actually inside the “single display” at first 🙂

Loads the comment template. For use in single Post and Page displays. Will not work outside of single displays unless $withcomments is set to 1.

By the way, that error_reporting(0) line is there to suppress a deprecated notice which says that your theme is missing “comments.php” even if it’s there.

Hope you enjoy this article

Saving a HUGE bandwidth cost in WordPress by automatically serving media contents from copy.com

shutterstock_132384233
The title almost says it all. Our mission is to save the bandwidth cost (and ensure better deliverability) by leveraging the power of headless installation of copy.com client in Linux, and then integrating it into WordPress. The integration must work seamlessly so that the viewers don’t see a difference, and at the same time you don’t have to put any extra effort. Beside saving bandwidth, this also reduces extra load from your web server. There’s another surprise which I will tell you later. For now, keep reading 🙂

You need at least a VPS to make this setup working, preferably with root access. These days VPSes are cheap. You can purchase an 128MB VPS for ~14/yr from Ramnode (such a fantastic provider) or may be for ~19/yr from WeLoveServers. Or feel free to use your existing VPSes if you have one.

Step 1: Headless installation of copy.com app
You can use your existing copy.com or register a new one using my referral code http://copy.com?r=Tbcrni, you and I both will be getting an extra 5GB if you do so.

Now log into your linux box via SSH, you need to have root privilege to complete this step.
(more…)

Breakpoint JS – load external javascript for different browser breakpoints

idea

Live Demo: http://hasinhayder.github.io/BreakPoint/

Breakpoint helps you to define multiple breakpoint ranges and load external javascript files when someone resize their browser window to those breakpoints. Beside loading external scripts, Breakpoint also triggers an event whenever browser width falls in any of those predefined breakpoint ranges.

Using Breakpoint
Using BreakPoint is pretty simple. Include jQuery in your web application and then include jquery.breakpoint.js. Now you can define multiple breakpoint ranges and initialize like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$.BreakPoint({
breakpoints:{
mobile:{max:480,load:true},
default:{min:480,max:1024, load:true},
wide:{min:1024,max:1200,load:true},
superwide:{min:1200,load:true},
}
});
});
[/sourcecode]

In the example above, we have defined four different breakpoints. The first one mobile will be used whenever browser is resized from 0px to 480 pixel (all inclusive). The next breakpoint, default will be used whenever browser is resized between 480px to 1024px (all inclusive), and so on.

Now, whenever a breakpoint is reached, BreakPoint jQuery Plugin will load an external javascript file with the same name of the breakpoint. For example, when browser is resized to 400px it will fall under mobile and now an external file named mobile.js will be loaded and executed.

By default BreakPoint will look for external javascript files in the js/ folder in the current path. But you can change this by passing a parameter named prefix, like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$.BreakPoint({
prefix:"scripts/",
breakpoints:{
mobile:{max:480,load:true},
default:{min:480,max:1024, load:true},
wide:{min:1024,max:1200,load:true},
superwide:{min:1200,load:true},
}
});
});
[/sourcecode]

Now BreakPoint will load external js files from the scripts/ folder.

Breakpoint Parameters
prefix: By default, prefix is set to js/ but you can change it to anything you want.
breakpoints: for each breakpoints, there are three paramaters you can pass which are “min”, “max” and “load”. By default min is set to 0, max is set to 9999 and load is set to false. The load parameter is an important one if you want to load external javascript files whenever a breakpoint is reached. If load is set to true, external files will be loaded, otherwise not.

BreakPoint Events
Whenever a breakpoint is reached, BreakPoint plugin will trigger a window event named breakpoint. The event object will have an attribute named breakpoint which will contain the name of the breakpoint that has been reached. Here is an example how you can add an event listener to this breakpoint event

[sourcecode language=”javascript”]
$(document).ready(function(){
$(window).bind("breakpoint",function(e){
if(console)
console.log(e.breakpoint);
});
});
[/sourcecode]

That’s mainly it. Enjoy! Check out the live demo at http://hasinhayder.github.io/BreakPoint/

The Badass List of Essential jQuery Plugins

banner

Check it out here: http://hasinhayder.github.io/essential-jquery-plugins/

I have started curating this list for last couple of weeks and the purpose is to create an one stop place where you can look for the essential jQuery plugin for your project and look no where else. Honestly, sometime it’s really hard to find the perfect plugin in this overwhelming world of jQuery plugins.

I hope you will find it useful. If you want to contribute, you can open an issue and tell me a missing plugin and I will be happy enough to look at it. If it’s worth to be in the list, it will be added back there, no worry. You can also fork this github repo and add the missing plugin in the readme.md file in markdown format and send me a pull request.

So enjoy this badass list of essential jQuery Plugins which is continuously growing.

An Animated Responsive grid with Filtering feature

This is a followup of my previous post, where we had created a beautiful responsive grid with barely 6 lines of javascript code. But this time, we have added filtering feature in it, and added category/tag selector which triggers the filtering. For filtering we have used MixItUp library in this example.

Have a look at the live demo at http://hasinhayder.github.io/ResponsiveGalleryWithFiltering. Resize the browser window and see how the grid items adapt to the new width. Select categories from the dropdown list in the top right corner to see how the filtering works.

Positioning the dropdown list was managed using media queries which you can see at the bottom of the <style> block.

One more thing to note here, a very important note perhaps. If you have used MixItUp before then you probably already know that every time mixitup refreshes the list, it actually removes the old list items and redraws them in the container. This phenomenon removes any events attached to the list items. To fix it up, you need to attach event listeners using $.delegate() method, as done in the example. However, lets have a look at that

[sourcecode language=”javascript”]
$(".grid ul").delegate("li","click",function(){
var src = $(this).find("img").attr("src");
alert(src);
});
[/sourcecode]

Enjoy!

LazyMouse jQuery Plugin – detect mouse inactivity easily :)

LazyMouse

Before jumping into the details, let me hear you asking “WHY?”. To be honest, not all of you will need to detect the mouse inactivity in your web applications. But sometime, it’s useful to do something different after a certain period of inactivity either to grab attention of the viewer, or to help him by improving the UX. For example, hide the sidebar and top navigation when user is reading the content, to emphasis his reading experience. Or show an animation – just do whatever during your user’s mouse is inactive for some time.

And to detect mouse inactivity easily, here comes the LazyMouse jQuery plugin which attaches two new events to the bodyelement, one is mouse.active and another one is mouse.inactive . You can just add two listeners for those events and do whatever you want to do 🙂

Using jQuery LazyMouse is pretty simple. Initialize it like this
[sourcecode language=”javascript”]
$(document).ready(function(){
$.LazyMouse();
})
[/sourcecode]

You can also specify the inactivity threshold in milliseconds, like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$.LazyMouse({
delay:2000 //2 seconds threshold
});
})
[/sourcecode]

Once initialized, as we have mentioned earlier, the body element will be triggered with two new events. Lets add a listener to those, like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$("body").bind("mouse.active",function(){
console.log("Mouse Active");
});
$("body").bind("mouse.inactive",function(){
console.log("Mouse Inctive");
});
})
[/sourcecode]

The events are propagated using jQuery Debounce, and therefore it is rate limited for good. See the live demo at http://hasinhayder.github.io/LazyMouse, and fork the github repo at http://github.com/hasinhayder/LazyMouse

Enjoy 🙂

An awesome animated responsive grid in a few lines of javascript and css3 goodness

Screen Shot 2013-08-15 at 4.36.33 AM

Responsive grid is a pain to many people, because sometime they have to achieve the desired effects either using complex plugins, css layout styling with the help of media queries. And here comes a nifty solution which works perfectly well in all devices. The responsiveness is done using a few lines of Javascript which listens to window resize event. But to save the browser from refreshing the layout, it uses debounce technique which only fires after the resizing is done.

The trick is pretty neat. All you got to do is tell it a minimum width of the grid items. Then, once resized, it divides the window width by that minimum, extract the integer part and displays that many items in a row by setting a width (in percentage) for each of them.

[sourcecode language=”javascript”]
var minWidth = 250;
$(document).ready(function(){
$(window).resize($.debounce(250,function(){
var w = $(window).width();
var numberOfItems = parseInt(w/minWidth);
var itemWidthinPercentage = 100/numberOfItems;
$(".grid ul li").css({width:itemWidthinPercentage+"%"});
}));
});
[/sourcecode]

See the working grid at http://hasinhayder.github.io/responsivegrid and resize the window to check out how it fits perfectly.

The animation is done using the following css3 transition for each list item
[sourcecode language=”css”]
-webkit-transition:all 0.2s ease;
-moz-transition:all 0.2s ease;
-o-transition:all 0.2s ease;
-ms-transition:all 0.2s ease;
transition:all 0.2s ease;
[/sourcecode]

Checkout the demo and fork the github repo to customize it anyway you’d like to 🙂