This blog - now archived - is read-only.
New blog: Mohammad Emran Hasan.

Category Archives: Programming

Using Twitter for sending server downtime alert

Today I’ve written this simple PHP script to alert me through Twitter whenever our company’s local server is down. The script is called by a cron every 5 mins in my central hosting. Without much babble, here goes the code (if you’re interested to know why I needed this, that’s at the bottom of the post):

<?php

// Specify the target URL in your server
$targetUrl  = 'http://YOUR_SERVER_URL';

// Specify what the response is from the server
$targetText = 'Hello from Daredevil';

// We will be using cURL for fetching the content
$ch = curl_init();

// Set the params
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Get the response
$response = curl_exec($ch);
curl_close($ch);

// Are things in right place ?
if ($response == $targetText) {
    die('Site is up and running!');
}

// Nope, so here are the sender's twitter info
$username = 'SENDER_TWITTER_USERNAME';
$password = 'SENDER_TWITTER_PASSWORD';

// Receiver's twitter username
$receiver = 'RECEIVER_TWITTER_USERNAME';

// Alert message to send
$message = 'Daredevil is not responding, please fix ASAP!';

// The Twitter API address (new direct message)
$url = 'http://twitter.com/direct_messages/new.json';

// We will be using cURL for this
$ch = curl_init();

// Set the params
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$receiver&amp;text=$message");
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

// Send the request
$response = curl_exec($ch);
curl_close($ch);

// Success or failure
if (!empty($response)) {
    echo 'Recipient has been notified.';
} else {
    echo 'No response from twitter.';
}

Why I needed this?

Recently we have setup a server at our office for committing work to a local SVN repository and have the QA test our work whenever they are ready. We also have a staging server where we do SVN update from this repo. Now, for the last few days, I’ve found the local server to be off due to a few reasons – but every time I realized this at night when I am back home and can’t do anything to turn it on. So I thought about this Twitter alert which is sent to my cell phone immediately when the server goes offline.

Btw, if Twitter doesn’t send SMS to your country, don’t worry. Check out the excellent service at Twe2 that I’ve been using for a couple days.

Cheers!

Code Updates (HTTP class, Extended CodeIgniter Model, Cross-domain AJAX transport)

Greetings to all the readers of my blog.

Many of you have been writing to me in the last couple days when I took the site down. The main objective was to add the new theme and push a few code updates of the existing libraries. I really appreciate your concern and would like to reassure you that the site is up and will be up as usual :) Now, besides the slightly customized theme from Elegant Themes, I have put a few code updates. They are detailed below:

Extended Model for CodeIgniter

The original version of the Extended Model for CodeIgniter has been serving many people well. Although most users loved the nifty functions of the Model, many (including me) didn’t like the hacking of CI core to get this functionality. With the release of CodeIgniter 1.7, we can avoid that as we can now overload the Model class of CI like the other libraries. Follow this instruction:

1. Download the updated version from here
2. Put it in your application/libraries folder
3. In your model files, use it this way: class Product extends MY_Model
4. Everything else is same just like the original one

HTTP Class

There is not much update in this class except for a few bug fixes (thanks to you guys). Also, I have included a license file in the package as many of you have asked. It’s released under the MIT license. The original post is here for reference.

Download the update from here and the API reference is here.

Cross-domain AJAX calls using PHP

A minor bug fix in the code. Thanks to a few of you who pointed them out. Original post is here. Download the update from here.

I have accelerated plans for the blog in 2009 so stay tuned for some worthy posts in this month. And do write to me if you feel you have any questions/ideas/suggestions.

Cheers!

Becoming a Kick-ass PHP ninja

Who is this for?

You’ve been developing web applications using PHP for a couple months now and are finding it very enjoyable. Although you feel that you’re doing quite good, you’re not sure whether its the end. Besides, the following questions wonder you often:

  • Where to go from here
  • What new things to learn
  • How to become a Kick-ass PHP Ninja

If that’s the scenario, then this post if for YOU.

Background

A few days back, I read a number of blog posts where people have highlighted the shortcomings they see in newbie developers. Some of them have gone further to narrow down the focus on PHP developers only (as PHP’s nature sometimes allow developers to avoid standards). They did a great job by listing the shortcomings, but their posts missed clear way forwards (these can be inferred though). A number of readers also commented on the posts with their insight as well. So I was thinking how about compiling all these in an easy to follow list? Hence this post.

Btw, due to the volume, I’ve mostly touched the points here and provided few useful resource links for further study. I do have plan to elaborate a few of them in coming posts, with each point becoming a single post. Let me know which ones you’ll prefer most, by entering the poll at the bottom of the post.

Part A : Technical Way Forward

In the first part, let’s shed some light on how you can move forward with your technical abilities.

1. Start using version control

Version control is like a big UNDO button for your coding. You can go back to your previous code revisions and can compare/rollback to specific code areas anytime you see necessary. It will keep track of all your changes and will empower you to track your development changes across your work/team. Also, in a distributed development team, version control helps prevent overwriting of code by team members and keeps all the members code up to date.

Subversion (SVN) is one of the most popular open source version control system. If you’re on windows platform, you can try TortoiseSVN, a client for SVN.

2. Write code in OOP way

If you haven’t already, it’s high time you started writing code in Object Oriented Programming (OOP) way. You may ask why? Well, OOP forces you to write code that is maintainable in nature. If properly followed, OOP code become a lot efficient than procedural code. Also, it allows you to re-use code across your project and/or multiple projects.

If you’re not convinced, have a look at these excellent resources for further study.

3. Adhere to a coding standard

Coding standards allow you to write code in a way which is easily understood by other people. When you adhere to a coding standard used by may others, you actually convey a message that you’re serious in writing code that people will be able to “get” and maintain. Keeping abbreviation type variable names, applying multiple indention types, writing meaningless function names etc will work for you in short term, maybe in personal projects. But when you move to a larger group with a number of developers, you ought to follow a standard so that everybody working with you can get along with your parts.

The following standards are most widely used among PHP developers around the globe:

Although you can define a standard for your team/company, it’s always better to have close relation with what the industry follows. In my company, Right Brain Solution Ltd, we follow a slightly modified version of Zend Framework Coding Standards. You can get that one here.

4. Document your code

Documentation is a virtue of great developers – don’t get me wrong, I’m talking about code documentation, not writing user manuals :) Well documented code prevents other team members from reading each line of your code and understand them by heart. Rather, it tells them exactly what they need to know – purpose of the code, what it requires as input, what it will deliver as output, etc. If you take a look at the above mentioned coding standards, you’ll discover that most of them even specified standard for documentation as well, which is phpDocumentor. It’s the most used standard for PHP code documentation and is widely recognized.

5. Use a good framework

Frameworks give you good structure and helps you build web applications in a fast way, with confidence. Most of today’s popular PHP frameworks (Zend Framework, CodeIgniter, CakePHP, Symfony, Kohana etc) follow the Model-View-Controller (MVC) pattern, which itself is a strong advocate of good practice.

Besides structure, frameworks force you to write code in a structured way. Some of them will also require writing the code in OOP – whose benefit we already discussed above. And frameworks usually come with a number of helpful libraries and helpers, to make your life easy as a web developer.

Josh sharp discusses this in details here and later posts a follow-up here. Both are good reads.

6. Re-use code/libraries

One of the most common advice programmers get is: “Don’t re-invent the wheel”. Well, what’s the point here? It actually means that you should not spend much time on solving a problem that has already been solved, in efficient way, by others. Rather solving it out yourself, you can “google” it and see how others have done it. It will not only save your valuable time, but also will ensure stable code (assuming that people usually post things on web after doing a number of testing and user of the codes usually help iron-out any issues, etc).

However, keep an eye on your target use/objective. If there is not enough good solutions that solves your problem, go ahead and solve yourself. Make it good and give it back to the community so that others facing that problem won’t need to spent the time you’ve spent. The whole open source model runs on this give-give way, so be a part of it.

7. Test your code the right way

In order to make confidence out of your code, you’ll need to test your code the right way. Although you might be used to testing your application using debug messages and browser refreshes, in a real world scenario these won’t work. You’ll need to write unit tests which can do automated testing of your code. The power lies in that you can run these tests almost anytime and can check if anything is broken after each new change.

PHPUnit and SimpleTest are the two most widely used Unit testing suite for PHP. You should also have a look on Test Driven Development (TDD), which is the way of greatly enhancing your chance of deploying application with least bugs.

Part B : Personal Way Forward

Now, even if you’ve improved yourself on the above mentioned points, you’ll still need to work on your personal matters to move forward. Here goes those points.

8. Be Agile

You need to be an agile developer if you want to move forward in your career. What does it mean to be agile? Agility is more of an attitude than a skill set. The common characteristics of agile developers are:

  • They’re open minded and therefore willing to learn new techniques
  • They’re responsible and therefore willing to seek the help of the right person(s) for the task at hand
  • They’re willing to work closely with others, pair programming or working in small teams as appropriate
  • They’re willing to work iteratively and incrementally

Further resources: Agile Software Development, The Agile Manifesto.

9. Keep yourself updated

No matter what, keep yourself updated on whats going on in your field (in this case PHP). Subscribe to the RSS of great PHP blogs and skim over them on a regular basis. Dig into the topics that interest you most and see the author’s point. Also, keep a habit of trying new technologies every now & then. It gives you an edge over others and when any discussion goes about it, you can help others understand as well as make your points.

Btw, if you don’t have a clue where to find good blogs, have a look at here, here and here.

10. Start community involvement

Remember I told above to give your work back to the community ? How to do that ? Start a blog of your own and start writing posts there every now & then. Yes, I know you’d say “Who’s going to read my blog anyway?”, but if you share your experience, someday, somebody will find it useful. And if you can share things that others haven’t done, you’ll slowly see visitors coming on your blog increasing way.

Besides blog, try to participate in tech forums and communities. Help people out in the areas you excel and at the time of your need, other people will be happy to help you out as well. These communities are also great place to learn about many unusual matters, see how situation changes from person to person, place to place, etc. You’ll also be able to make great friends who might come handy later in your life.

Another great way of community involvement is to contributing to open source projects. Share some of your valuable time for an open source project and it may come handy for a huge number of people. Your work might solve the problem of somebody like you. If needed, initiate an open source project yourself and invite others to work on your vision.

11. Use a good IDE

With due respect to Dreamweaver, step forward and use an IDE made for PHP. You’ll notice the difference in a few days when you’ll see that your productivity has increased in great ways. These IDEs provide great number of useful features including but not limited to: syntax highlighting, auto completion, code suggestions, code snippets, contextual help, code templates, debugging, profiling, etc.

The following IDEs mostly have the similar feature set and can boost your productivity in great ways:

Personally I use NuSphere PhpED 5.2 and I love it in every way. They’ve provided me with a complementary license and I am grateful to them for that. If you’re planning to buy it, let me know and I might find you a discount.

12. Be communicative

In your team/company, try to be as communicative as possible. It reduces a lot of confusions, makes you close to other devs so that you understand them, portrays you as a good person in front of management and overall, helps you enjoy your work. When you’re working together with others, make them feel that you’re there and ready to give whatever it takes. Create a personal brand of yourself.

What’s next?

Phew! It’s quite a good amount of writing in a while :) I’ve tried to cover most of the items I found to be important. However, there might be some points I’ve overlooked so feel free to post them in the comments. If this helps any one of the developers I intend it for, then I’ll take that the effort is successful.

Thanks everybody, Happy Eid Mubarak to you!

[poll id="3"]

Increase productivity with Todoist

If you’re like me, you’d want to keep your ever busy life a bit organized. Being a techie, you’d first find a tool that will facilitate you in doing so. Most of us are fan of a number of such tools: RememberTheMilk, BackPack, Ta-Da List, 30boxes, Microsoft OneNote, Stickies etc. I’ve also tried all of them and a few others, stuck with them for a few days, but later lost the interest. This happened until one of colleagues, Anis, suggested me to have a look on Todoist.

At first sight, I thought it as “okay…another web 2.0 brainchild”. It seemed too simple to handle my complicated needs and I did not have high ambition with it. But as days passed, I was discovering new new features of it and gradually it became a part of my life. I’m a big fan of Getting Things Done (GTD) approach and Todoist became my dropbox for all the tasks in my mind.

If you ask me what’s so special about Todoist, I’d mention the following few features:

Simplicity

Todoist is damn simple and hosts one of the most powerful yet sleek web 2.0 interface on the web. It allows you to have an unlimited nested category/project list and under each of them, unlimited nested task list. This is something that most other tools miss. For me, it’s a super MUST feature.

Continue reading

Beware of the so called “Senior PHP Developers”

With the rise of PHP developer as career, many are trying to get their share in the pie. Lately I’ve met a number of developers who have worked for more than one/two years in developing PHP applications in various companies and they consider themselves as “senior” developers. They try to emphasize that they’ve done enough raw programming and they are now in a position where they’ll only design architecture of applications.

When you interview them and ask about complex topics, they’ll reply: “Oh my last company didn’t allow me work with that, but I’ll be able to grab that in a day“. You trust them and think that if they get the chance, they’ll sure be able to excel. After all, they’ve got that Company X’s experience and Guru Y’s reference.
Continue reading

Extended Model for CodeIgniter

Feb 2009: An updated version of the code for CodeIgniter 1.7.x can be found here.

I developed this extension of CodeIgniter’s Model last year, but never had the chance to publish it. The main purpose of this extension is to make a dev’s life easy. This extension has been used by several of my devs at RBS and has been proved to increase productivity and reduce the number of painful small queries to write. Their enthusiasm has driven me to post this for the CI fans out there.

Without much babble, let’s get into point. I’ve explained the process of installing it and then showed some example uses. For starter, click here to download it. Now follow these steps to get started:

Continue reading

Cross-Domain AJAX calls using PHP

AJAX has become the core component of many web applications around us. And its fairly easy to handle AJAX now a days, with the help of various javascript libraries (ex: jQuery, Prototype, Mootools, YUI, etc). But there is one security issue that web browsers impose in doing AJAX calls – they don’t let you do AJAX calls in web servers different than yours. That means, if your script is in www.mydomain.com and you’re trying to do AJAX call to www.anotherdomain.com/get.php, then the browser will through error like: “Error: uncaught exception: Permission denied to call method XMLHttpRequest.open”.

Now, there are a number of solutions to this problem. Instead of explaining them all to you, lemme provide you the simplest one: using a PHP transport file. If you already know the thing and just need the script, download from here.

Others, let’s see an example implementation first.

Example use

   1: xmlHttp.onreadystatechange=function()
   2: {
   3:     if(xmlHttp.readyState==4)
   4:     {
   5:         alert(xmlHttp.responseText);
   6:     }
   7: }
   8:  
   9: xmlHttp.open("GET", 'http://myserver.com/transport.php?action=' + 
  10:                     urlencode('different-server.com/return_call.php') +
  11:                     '&method=get&data1=101&data2=pass', true );
  12:  
  13: xmlHttp.send(null);

Now, lets see how it works:

  1. The script makes an AJAX call to the myserver.com/transport.php with a few parameters:
    • action = the target URL you need to fetch, from a different domain
    • method = the HTTP method (post/get)
    • data1, data2 = sample parameters for using as either query-string or POST fields
  2. When the request is received by transport.php, it uses cURL to make a call to the page mentioned in action.
  3. Based on the method, it either makes a GET request or a POST request. In both cases, it sends the extra parameters that are sent.
  4. After the response is received, transport.php echoes it. So, you have what you need!

Download

transport.php
Cross-Domain AJAX call transporter.
Downloaded: [downloadcounter(transport)] times

Comments and suggestions are most welcomed :)

HTTP Class for PHP (supports both cURL and fsockopen)

Feb 2009: A couple bugs have been fixed and library updated.

This is a wrapper HTTP class that uses either cURL or fsockopen to harvest resources from the web. It supports a handy subset of functionalists of HTTP that are mostly needed in day to day coding. Scripts who need to communicate with other servers will find it useful. If you’re looking to invoke any RESTful API and don’t want to bother adding a bunch of libraries for that simple thing, just put this class and you’re set.

Download

Detailed documentation can be found here. And you can download the source from here.

Update

Class added in Orchid – “PHP framwork for the rest of us”

Features

  • Can use both cURL and fsockopen.
  • Degrades to fsockopen if cURL not enabled.
  • Supports HTTP Basic authentication.
  • Supports defining custom request headers.
  • Supports defining connection timeout values.
  • Supports defining user agent and referral values.
  • Supports both user-defined and persistent cookies.
  • Supports secure connections (HTTPS) with and without cURL.
  • Supports adding requests parameters for both GET and POST.
  • Supports automatic redirection (maximum redirect can be defined).
  • Returns HTTP response headers and response body data separately.

Example 1 – Simple Get (Facebook Application List)

   1: <?php
   2:
   3: include_once('class.http.php');
   4:
   5: $http = new Http();
   6:
   7: $http->execute('http://www.facebook.com/apps/index.php?sort=6');
   8: echo ($http->error) ? $http->error : $http->result;
   9:
  10: ?>

Example 2 – Invoking Yahoo Term Extraction API

   1: <?php
   2:
   3: include_once('class.http.php');
   4:
   5: $http = new Http();
   6:
   7: $http->addParam('appid'   , 'a_really_random_yahoo_app_id');
   8: $http->addParam('context' , 'I am happy because I bought a new car');
   9: $http->addParam('output'  , 'xml');
  10:
  11: $http->execute('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction');
  12: echo ($http->error) ? $http->error : $http->result;
  13:
  14: ?>

Example 3 – Logging into Basecamp (without using cURL!)

   1: <?php
   2:
   3: include_once('class.http.php');
   4:
   5: $http = new Http();
   6:
   7: $http->useCurl(false);
   8: $http->setMethod('POST');
   9:
  10: $http->addParam('user_name', 'emran');
  11: $http->addParam('password', 'hasan');
  12:
  13: $http->setReferrer('https://someproject.projectpath.com/login');
  14: $http->execute('https://someproject.projectpath.com/login/authenticate');
  15:
  16: echo ($http->error) ? $http->error : $http->result;
  17:
  18: ?>

Example 4 – Getting a protected feed

   1: <?php
   2:
   3: include_once('class.http.php');
   4:
   5: $http = new Http();
   6: $http->setAuth('emran', 'hasan');
   7:
   8: $http->execute('http://www.someblog.com/protected/feed.xml');
   9: echo ($http->error) ? $http->error : $http->result;
  10:
  11: ?>

Cake 1.0 released !

Cake PHPI can’t start my day without Coffee. I can’t live my day without Cake ! And now they have a stable Cake !!!

Yes, the long-awaited Cake PHP 1.0 is out ! Not only its the first official stable release, but also its boosted with lots of bugfixes and all the great cake features. Also, the website of Cake PHP is revamped with the new design – looks simple yet appealing. Thanks to Armando Sosa for his contribution.

People, if you havent already tasted Cake, its the best time to start so ! Don’t miss the yummy bites !! Go get it !!!

Cake PHP : The ‘right’ framework!

My search for the right framework has ended today, when I discovered the Cake PHP framework ! By right framework, I am meaning the one:

  • having an easy learning curve,
  • facilitating the MVC pattern,
  • seperating display and business logic in a ‘meaningful’ way, and
  • with which making web apps is possible in considerably low time.

Well, to my surprise, Cake gives me all these and goes beyond my expectation. Maybe becauz the idea of Cake has come from the growingly popular Ruby on Rails. Nevertheless, to me the most important thing is that I am not going to switch to other language frequently (as I’ve built my competency in PHP for some time).

So, whats so special with Cake ? Lemme tell you some:

  • MVC pattern
  • Almost zero configuration (you just need to tell you db config to start)
  • Various application helper (Html, JavaScript, Date, etc)
  • Support for Ajax (using the famous prototype library)
  • In-built validation
  • Access Control Lists (ACL)
  • Security, sanitization, session handler, etc.
  • A very active community !

I hope you’re impressed enough. No, no….don’t take it as other frameworks you’ve tried already….test it out !! You wont regret.

Ok, cya you in the kitchen !! We’re baking yummy cakes !