Tuesday, 29 July 2014

Tagged under: , , , , ,

Zend Framework from Scratch Part II: MVC and Creating Zend Project

In the Part I of the 'Zend from Scratch' series, we installed Zend and configured the environment to create our first Zend project. Continuing with our 'Zend from Scratch' series, we will have a look at the MVC framework using Zend and then create our first Zend web application. For those who haven't read the Part I of this series, here's the blog post of it:

Model-View-Controller (MVC) framework:

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.
  • Model - This is the part of your application that defines its basic functionality behind a set of abstractions. Data access routines and some business logic can be defined in the model.
  • View - Views define exactly what is presented to the user. Usually controllers pass data to each view to render in some format. Views will often collect data from the user, as well. This is where you're likely to find HTML markup in your MVC applications.
  • Controller - Controllers bind the whole pattern together. They manipulate models, decide which view to display based on the user's request and other factors, pass along the data that each view will need, or hand off control to another controller entirely.

We will discuss more on MVC and how it fits in the Zend framework once we create our first project.

Create a Zend Framework Project:

Once you have completed all the steps in Part I of this series, we can start with creating of first PHP Zend project.
Open command prompt and navigate to the folder where you want to create your project. It should be the folder where the server points to. If you have XAMPP installed, its 'C:\xampp\htdocs'. Now run the below command:
zf create project zendtest
Here, 'zendtest' is the name of the project.

You may get an error for 'PHPUnit_Framework_TestCase', but this should not be a concern as it will not create any hindrance while working with the development activities. The error is related to Unit Testing.

Once you run the above command, you can find a folder named 'zendtest' (the name of our project) in the 'htdocs' folder. Below is the directory structure of our newly created project:

Now, once we can see the directory structure, we can relate this back to the MVC framework.

Zend Framework and MVC:

Open the 'application' folder in the newly created project:

As you can see, there are three prominent folders: models, views and controllers.


Your application's action controllers contain your application workflow, and do the work of mapping your requests to the appropriate models and views.
Open the IndexController.php file in the controllers folder:


class IndexController extends Zend_Controller_Action

    public function init()
        /* Initialize action controller here */

    public function indexAction()
        // action body


Note the method 'indexAction()'. IndexController is a fallback controller and which also serves the home page of the site. Since there is nothing in the indexAction() method right now, it takes the default view, which is 'C:\xampp\htdocs\zendtest\application\views\scripts\index\index.phtml'. This is nothing but the home page of your project.
Open your browser and goto
This is what you get:
This page is nothing but the index.phtml in 'C:\xampp\htdocs\zendtest\application\views\scripts\index'.
Now, lets have a look into Views.


View scripts are placed in application/views/scripts/, where they are further categorized using the controller names. In our case, we have an IndexController and an ErrorController, and thus we have corresponding index/ and error/ subdirectories within our view scripts directory.

Creating a Layout:

You may have noticed that the view scripts in the previous sections were HTML fragments- not complete pages, and they lack html, head, and body tags. This is purposely done by design, so that all actions return content related to that action only, and not the whole application. This gives a consistent look and feel throughout the application.
To create a layout, open the command prompt and navigate to the project directory. Now run the below command:
zf enable layout
The output is as below:

This will create a 'layout.phtml' file in 'C:\xampp\htdocs\zendtest\application\layouts\scripts'. If we open the file, below is what we see:

<?php echo $this->layout()->content; ?>

This is nothing but echoing the content from the view. We need to wrap this content with proper header and footer files. Replace the code in 'layout.phtml' file with the below code:

<!DOCTYPE html>
        <title>Zend Test</title>
        <div id="wrap">
            <div id="header">
                <p>This is the header</p>
            <div id="content">
                <!-- Echo our content here! -->
                <?php echo $this->layout()->content; ?>
            <div id="footer">
                <p>This is the footer</p>

Now, again goto 'http://localhost/zendtest/public' in your browser. You now have the previous page with a proper header and footer!!

So far, we have created the basic layout of our site using the Zend framework. In the next part, we will cover creating Models and database, creating new controllers and the rest of the things required to create a full-fledged web site.

A summary of what we covered in this tutorial:

  • What is Model-View-Controller framework
  • Zend Framework as an MVC
  • Creating Zend Project
  • Understanding the Controllers and Views in Zend Framework
  • Creating a layout using Zend
Stay tuned for the final segment of this three part Zend from scratch series.
You can subscribe for free or become a follower to get the latest alerts and posts.

Sunday, 27 July 2014

Tagged under: , , ,

Zend Framework from Scratch Part I: Install and Configure PHP Zend Framework

Zend Framework (ZF) is an open source, object-oriented, full-stack PHP framework created by Zend Technologies implemented in PHP 5 and licensed under the New BSD License.

In this 'Zend from Scratch' series, we will try to get the understanding about Zend Framework...not theoretically, but covering things like installing and configuring Zend Framework, understanding the MVC framework and developing a sample application using Zend.

In this series, I would be using XAMPP for all purposes. XAMPP is nothing but a package of PHP, MySQL, Apache and other services. So, the PHP environment at my end is set up with XAMPP. You can download xampp from https://www.apachefriends.org/index.html.

So, lets get started...This part of the series will cover Installing and Configuring the Zend Framework on Windows.

System Requirements:

Zend Framework version 1.7 requires PHP 5.2.4 or later. Previous versions required PHP 5.1.4 or later, although the ZF Programmer's Reference Guide strongly recommended PHP 5.2.3 or later for security and performance improvements included in these versions of PHP.

Step 1: Download Zend Framework

Download the latest version of Zend Framework 1 (Full) from http://framework.zend.com/. At the time of writing this tutorial, the latest version of Zend was 1.12.7.

Step 2: Configure Zend Framework

  • Once you download the .zip file, extract its contents to a folder. The folder structure after extracting should look like this:
  • Now, copy the 'bin' folder and paste it in the 'PHP' folder, which for me (since I'm using xampp) is 'C:\xampp\php'. Rename the copied folder to 'zend-bin'.
  • Open the 'library' folder in the extracted folder. You can find a folder named 'Zend' in it. Copy this 'Zend' folder and paste it in your PHP's include_path. You can find the include_path for your environment in the 'php.ini' file. The default include_path for xampp is:
include_path = ".:/php/includes"

For Windows:
include_path = ".;C:\xampp\php\PEAR"

The format of include_path is "path1;path2". The '.'(dot) in path1 means the current directory. So, there are basically 2 include_path(s).
  • Lastly, we need to configure the Zend CLI tool. To do this, we need to add the 'zend-bin' folder to the path System variables. Right click on My Computer and select Properties. In the Advanced tab, click on 'Environment variables'. Here, in the 'System Variables' section, click on edit, and add the path to 'zend-bin' folder (C:\xampp\php\zend-bin) at the end:
  • Just to ensure that the setup is fine (which it should be if you have followed the steps exactly), open the command prompt and run 'zf --help'. This command gives a list of all the commands you can use with Zend CLI. You should get he below output:

And there you are!! You have just set up the environment for creating your first project using the Zend Framework.

The next part of this series will give a brief idea about the MVC architecture of the Zend framework, and we will create our first project using Zend...So stay tuned!!

You can subscribe for free or become a follower to get the latest alerts and posts.

For the Part II of this series, click here.

Monday, 21 July 2014

Tagged under: , , ,

Print Web Page using JavaScript

Many a times, we come across situations where we have to selectively print only a certain part of a web page. When it comes to a normal print command, it will print the entire web page for you. However, what if you want only a certain section, say a certain <div>...</div> to be printed, and exclude the content of the rest of the page?
This tutorial aims at doing just the thing...

Step 1: Enclose the content that you want to be printed in a <div> tag, and name it, say 'report':

<div id="report">
Your Content goes here...

Step 2: Add a print button:

<input type="button" value="Print Summary" onclick="printContent('report')"/>

As we see in the above snippet, 'printContent()' is the function that would do the printing job for us. To this function, we pass the id of the <div> tag whose content we want to print.

Step 3: Create a javaScript function 'printContent()':
At the bottom of the page, add the below javascript function

<script type="text/javascript">
function printContent(id){
newwin.document.write('function chkstate(){\n')
newwin.document.write('function print_win(){\n')
newwin.document.write('<BODY onload="print_win()">\n')

The above function will take the id of the <div> tag whose content we want to print.
And there you are!! You can now print the page. With the help of software like PDF Creator, now you can also selectively print the page to a PDF file.
This functionality can be used where you want to print reports, receipts etc.

Thursday, 17 July 2014

Tagged under: , , , ,

Forgot Password Functionality in PHP

When you implement a Login functionality, one thing that becomes an obvious inclusion is the 'Forgot Password' functionality. There are several ways to implement the forgot password functionality, some of which may be:

  • Ask the security Question
  • Send a new password to the registered mail, etc etc
But the most popular one is
  • Send an encoded, one time password reset link to the registered mail id
We would be discussing on this, i.e. the password reset link functionality implementation in this tutorial.

Before we get on with the actual coding, we need to create a proper database schema:
In the Table where you store the login credentials, add another column 'forgotpassword', which will store the encoded random string that you would be sending to the registered mail id.

Now comes the code...

Step 1: Ask for the email id with which the user is registered


$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);

if(isset($_POST['submit'])) {
$selectuser="Select * from USERTABLE where emailid='".addslashes($_POST['email'])."'";
$result = mysql_query($selectuser);
$numrows = mysql_num_rows($result);
if($numrows == 1) {
 $row = mysql_fetch_assoc($result);
 for($i = 0; $i < 16; $i++) {
  $randomstring .= chr(mt_rand(1,126));
 $verifyurl = "resetpwd.php";
 $verifystring = urlencode($randomstring);
 $verifyemail = urlencode($_POST['email']);
 $updateuser="Update USERTABLE SET forgotpassword='".addslashes($randomstring)."' WHERE emailid='".addslashes($_POST['email'])."'";
A request has been made to reset the password for your account.
Please click on the following link to go to the password reset page:
 $mailer = new PHPMailer();
 $mailer->Host = ""; //Add smtp details
 $mailer->SMTPAuth = TRUE;
 $mailer->Username = "";  // Change this to your gmail adress
 $mailer->Password = "";  // Change this to your gmail password
 $mailer->From = "";  // This HAVE TO be your gmail adress
 $mailer->FromName = ""; // This is the from name in the email, you can put anything you like here
 $mailer->Body = $mail_body;
 $mailer->Subject = "User Verification";
 $mailer->AddAddress($_POST['email']);  // This is where you put the email adress of the person you want to mail
  echo "Message was not sent<br/ >";
  echo "Mailer Error: " . $mailer->ErrorInfo;
  echo "<center>A link has been
emailed to the address you entered below.
Please follow the link in the email to reset the passwod for 
your account.</center><br>";
 echo "We could not find any registered user with the email id as ".addslashes($_POST['email'])."<br>
 Please Enter the correct mail id & try again";

<div id="content">
<form action="forgotpwd.php" method="post">
<td>Enter the Mail Id you registered with</td>
<td><input type="text" name="email"></td>
<td><input type="submit" name="submit" value="Submit"></td>

In the above snippet of code, We ask the user to enter the mail id he/she registered with. Once the user submits the form, you first check if the email id is present in the database, if not, you notify the user accordingly.
Once you find the email id in the database, the next step is to create a random string, encode it and append it to the password reset page url. Encoding of a string can be done using urlencode() method in PHP.
We also store the encoded randomly generated string to the database. Next, encode the mail id of the user and append it too to the url. The next part is where we send this url to the registered mail id. For this, I have used PHP Mailer.
To know more about PHP Mailer as to how it works, refer to my tutorial on this: Sending Email using PHP

Step 2: Check the encoded url when the user clicks it from his mail


$verify = addslashes(urldecode($_GET['verify']));
$verifymail = urldecode($_GET['email']);

if (isset($_POST['confirmpwdreset'])) {
 $resetpwd="Update USERTABLE SET password='". md5($_POST['newpwd'])."' WHERE emailid='".$verifymail."'"; 
  $removeverifystring="Update USERTABLE SET forgotpwd='' WHERE emailid='".$verifymail."'";
 echo "<b>Your Password has been reset successfully.Login with your new password</b>";
$sql = "SELECT * FROM USERTABLE WHERE forgotpwd= '" . $verify . "' AND emailid = '" .$verifymail . "';";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
if($numrows == 1) {
$row = mysql_fetch_assoc($result);
echo "<br><h3>Hi </h3><br>";
echo "You can now reset your password<br><br>";
<form name="reset" action="resetpwd.php?emailid=<?php echo $_GET['emailid'];?>&verify=<?php echo $_GET['verify'];?>" method="post">
<td>New password: </td><td><input type="password" name="newpwd"></td>
<td>Confirm password: </td><td><input type="password" name="confirmpwd"></td>
<td></td><td><input type="submit" name="confirmpwdreset" value="Confirm"></td>

else {
echo "The link is either invalid or has expired";
else echo "The link is either invalid or has expired";

Once the user clicks the url in the mail, we decode the random string and the email-id in the url. For decoding, we can use the urldecode() method in PHP. Next, all we have to do is to check the database for the combination of the random string and the mail-id. Once we find that combo, we ask the user to enter the new password, which on submission is updated in the database. As we update the database with the new password value, we reset the value of the corresponding 'forgotpassword' field to '' so that the same random string cannot be reused, thus ensuring one time usability of password reset url

Thats it!! We now have a full fledged 'Forgot Password' functionality to make life easy for the users.

Saturday, 14 June 2014

Tagged under: , ,

Java code to remove redundant data / duplicate entries spread across multiple Files

The scenario here was that there are several text files, with redundant data in them. The objective was to remove the redundant data spread across multiple text files, and collate the entire data in a single file. This task can ofcourse be done using excel macros, but not being too fond of excel, I preferred writing a java code for the same.
Below is the Java code to accomplish this task:

package aj;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Load {
 public static void main(String[] args) throws IOException {
  System.out.println("Enter the no of files");
  Scanner scr=new Scanner(System.in);
  int no=scr.nextInt();
  int i=1;
  String source;
  String dest = "Filepath\\Dest.txt";
  String result = "Filepath\\Result.txt";

  source = "Filepath\\File"+i+".txt";
  copyContent(source, dest);
  removeDuplicates(dest, result);
 static void copyContent(String source, String dest)throws IOException {
  File fin = new File(source);
  FileInputStream fis = new FileInputStream(fin);
  BufferedReader in = new BufferedReader(new InputStreamReader(fis));
  FileWriter fstream = new FileWriter(dest, true);
  BufferedWriter out = new BufferedWriter(fstream);
  String aLine = null;
  while ((aLine = in.readLine()) != null) {
 static void removeDuplicates(String dest, String result) throws IOException{

  int flag=0;
  File fin = new File(dest);
  FileInputStream fis = new FileInputStream(fin);
  BufferedReader in = new BufferedReader(new InputStreamReader(fis));

  FileWriter fstream = new FileWriter(result, true);
  BufferedWriter out = new BufferedWriter(fstream);
  String aLine = null;
  String bLine = null;

  int i=1,j=1;
  while ((aLine = in.readLine()) != null) {
   File fin1 = new File(dest);
   FileInputStream fis1 = new FileInputStream(fin1);
   BufferedReader in1;
   in1 = new BufferedReader(new InputStreamReader(fis1));

   if(aLine.equals("***************************************************")==true || i==1)
     bLine = in1.readLine();
     if (bLine!=null && bLine.equals(aLine)) {




The function copyContent() copies the data from all the files to a single text file.
Once this is done, the function removeDuplicates() removes the redundant data from the newly created file. The final cleaned data is now available in the 'Result.txt' file.

Monday, 28 April 2014

Tagged under: , ,

Android Tutorial - First Android App: Flashlight

Ever thought of creating your own mobile application? Well, with Android, creating your own app is no longer a tedious task, something that could be done only by the professionals. All you need is the basic knowledge of java and xml, and the right way to start off.
This tutorial aims at creating a very basic android application, a flashlight.


1. If using PC:
  • Android SDK
  • Eclipse with ADT plugin
2. If using an Android device : Tablet, cell phone (I had built it on a tablet)
  • An Android IDE, for which I used AIDE
Now, lets get started with the tutorial:

Step I: Create a new Android Project in Eclipse. I have named it 'Lumos', something you can expect from a Harry Potter fan :P

Step II: Ask for Permissions
In the AndroidManifest.xml file, you have to specify the permissions that your application would be requiring in order to perform its tasks. In our case, we require the access to the Camera and its functions in order to start the flashlight.
Open the AndroidManifest.xml and change it to the one as below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.aj.flash"     android:versionCode="1"     android:versionName="1.0" >     <uses-sdk         android:minSdkVersion="8"         android:targetSdkVersion="11" />     <uses-permission android:name="android.permission.CAMERA" />     <uses-feature android:name="android.hardware.camera" />     <application         android:icon="@drawable/ic_launcher"         android:label="@string/app_name" >         <activity             android:label="@string/app_name"             android:name="com.aj.lumos.MainActivity" android:screenOrientation="portrait">             <intent-filter >                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application> </manifest>
As you can see, the below two lines are the ones that are used to get the permission to access the camera and its functions:

<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

Step III: The Layout of the App
Eclipse by default creates a file named main.xml in res->Layout. Open the file and paste the following code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    tools:context=".MainActivity" >


    <TextView android:text="Developed by aj"


The 'ImageButton' is nothing but the image of the bulb, which will be used as a button to switch the flashlight on and off. This button is identified by the id: 'btnSwitch'
The 'TextView' field is the one where you can flaunt your name, telling the world that you are the developer of this app :P

Step IV: The actual code
Open the file MainActivity.java and paste the below code:

package com.aj.lumos;

import com.aj.flash.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity{

 ImageButton btnSwitch;
 private Camera camera;
 private boolean isFlashOn;
 private boolean hasFlash;
 Parameters params;

    public void onCreate(Bundle savedInstanceState){

 btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

 hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

 if (!hasFlash) {
 AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
 alert.setMessage("Sorry, your device doesn't support flash light!");
 alert.setButton("OK", new DialogInterface.OnClickListener() {

 public void onClick(DialogInterface dialog, int which) {


 public void switchClicked(View v){
 if (isFlashOn) {
 } else {

 private void getCamera() {
 if (camera == null) {
 try {
  camera = Camera.open();
  params = camera.getParameters();
 } catch (RuntimeException e) {
  Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());

//Turning On flash
 private void turnOnFlash() {
  if (!isFlashOn) {
   if (camera == null || params == null) {

   params = camera.getParameters();
   isFlashOn = true;

//Turning Off flash
 private void turnOffFlash() {
  if (isFlashOn) {
   if (camera == null || params == null) {

   params = camera.getParameters();
   isFlashOn = false;

 private void toggleswitch(){

 protected void onStop() {
  if (camera != null) {
   camera = null;

 protected void onDestroy() {

 protected void onStart() {

 protected void onPause() {

I have tried to modularize the above piece of code by defining separate methods for various tasks. The methods in the above snippet are self explanatory.

You will be requiring a few images that have been used in this tutorial. Download these resources from the download box alongside or use this link: Resources
These images and the xml file in the above zip go into res->drawable-hdpi

Compile the above code and run it on your Android device.
Voila!! We now have our own flashlight app!

I have created an APK of the flashlight app, which can be downloaded from Lumos or from the download box alongside.

Have queries?? Stuck anywhere?? Post all the issues on Compild

Monday, 23 December 2013

Tagged under: , ,

Android Bootloop problem Fixed: The 'Jugaad' way

Having an Android phone arouses that natural inquisitiveness to play around with its firmware, to root the phone, install custom ROMs and do all sorts of crazy things with it. However, sometimes, you might end up messing up your beloved phone, and then start cursing yourself for all the foolishness you did. I was in a similar situation recently. With the craze for Kitkat spreading like a wild fire, I decided to install the latest Android 4.4 on my Samsung Galaxy S2. Be rest assured....this one time Samsung flagship device still holds strong when it comes to installing the latest firmwares. So, on the quest for Kitkat, I downloaded the CM 11 for GT-i9100, and with my phone already rooted, I took the Nandroid backup using the clockworkMod recovery. All set for yet another experiment on my phone (and btw...it has never disappointed me when it comes to flashing custom roms) I flashed the CM 11...but...got an error (Status 7), and the flashing failed. Determined to get Kitkat by hook or by crook, I did a factory reset of my phone...having at the back of my mind that I still have the complete system backup. Then I flashed the stock jelly bean  ROM, just to make sure that the current custom rom on my phone is not causing a problem while flashing a new rom. Again, I tried with Kitkat, but it still gave the same error!! Now, why did the error occur is altogether a different mystery, which I'm yet to figure out. The problem started, when I tried restoring my backup...the phone got stuck in Boot loop...one of the worst nightmares for android users!!

Now, generally, the boot loop problem gets fixed by removing the battery for some time and restarting the phone, or by wiping the cache and Dalvik cache repeatedly. However, it seemed that it wasn't my day, and everything I tried failed to boot my phone. And then I started doing something that almost everyone does at such situations...cursing myself...and more because I had done a factory reset of my phone. So, even though I knew that I can get back my phone by flashing the stock firmware, there was no chance, that I could get back my apps and data, which meant...the painful process of reinstalling everything from scratch. And what about all my messages...and all those levels I had completed in NFS, and what about my highest score in Temple Run...how am I gonna get all those things back??!! I tried googling a lot, but every forum said just one thing...flash the stock rom in case of boot loop problem, but damn!!...you wont get back your data.

And then suddenly, a thought occurred...a way around...a 'Jugaad' that we are so good at!! I had the nandroid backup with me...which meant I had the backup of my apps and data in it. The problem was with booting the phone right? There was still a chance that the apps and data had been restored from the backup. So, firstly, I did a factory reset of my phone...just to wipe out everything that was in there. Then, I restored the nandroid backup (as expected, the phone got stuck in boot loop again). And then came the master stroke...I flashed it with the stock firmware I had with me. And then came the prayers....God...please give me my phone back....please...please!!

It went past the Samsung logo...my heart racing like hell now....'Upgrading Android'....'Initializing the apps'....and Bingo!! Everything was in place...all my apps, all my contacts, messages...everything!! The only problem now was that my phone was not rooted as it was earlier, and it was again filled with all sorts of scrap inbuilt apps from Samsung, which I had previously removed. But that was welcome, as it was just a matter of few minutes and I could root my phone and purge it of those silly apps. The great thing was, that I got back my phone...and I had started loving it all the more now!!

So, for all those who had given up after the boot loop problem....there is always a way....that's the beauty of Android! The only thing that you should have at your disposal is a backup of your phone.

So, here's the jugaad in two simple steps:
Step 1. Restore the nandroid backup(This is where the boot loop problem started for me)
Step 2. Flash the stock firmware over the nandroid backup

You'll have your phone 'almost' as it was earlier, with all your apps and data.

Have Queries?? Post it on our Discussion Forum Compild