Tuesday, 29 July 2014

Zend Framework from Scratch Part II: MVC and Creating Zend Project
Ajinkya Mandhare10:06 am 0 comments

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.

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:

<?php

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
http://localhost/zendtest/public
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.

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

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

Zend Framework from Scratch Part I: Install and Configure PHP Zend Framework
Ajinkya Mandhare10:57 am 0 comments

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:
For UNIX:
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

Print Web Page using JavaScript
Ajinkya Mandhare11:06 am 0 comments

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...
.
.
</div>

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){
str=document.getElementById(id).innerHTML
newwin=window.open('','printwin','left=100,top=100,width=400,height=400')
newwin.document.write('<HTML>\n<HEAD>\n')
newwin.document.write('<TITLE>Summary</TITLE>\n')
newwin.document.write('<script>\n')
newwin.document.write('function chkstate(){\n')
newwin.document.write('if(document.readyState=="complete"){\n')
newwin.document.write('window.close()\n')
newwin.document.write('}\n')
newwin.document.write('else{\n')
newwin.document.write('setTimeout("chkstate()",2000)\n')
newwin.document.write('}\n')
newwin.document.write('}\n')
newwin.document.write('function print_win(){\n')
newwin.document.write('window.print();\n')
newwin.document.write('chkstate();\n')
newwin.document.write('}\n')
newwin.document.write('<\/script>\n')
newwin.document.write('</HEAD>\n')
newwin.document.write('<BODY onload="print_win()">\n')
newwin.document.write(str)
newwin.document.write('</BODY>\n')
newwin.document.write('</HTML>\n')
newwin.document.close()
}
//-->
</script>

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

Forgot Password Functionality in PHP
Ajinkya Mandhare12:49 am 0 comments


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

<?php

$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);
 $validusername=$result['username'];
 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'])."'";
 mysql_query($updateuser);
 
 $mail_body=<<<_MAIL_
Hi,
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:
$verifyurl?email=$verifyemail&verify=$verifystring
_MAIL_;
 
 require("class.phpmailer.php");
 $mailer = new PHPMailer();
 $mailer->IsSMTP();
 $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
 if(!$mailer->Send()){
  echo "Message was not sent<br/ >";
  echo "Mailer Error: " . $mailer->ErrorInfo;
 }
 else{
  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>";
 }
}
else{
 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";
}
}
else{
?>

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


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

<?php

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

if (isset($_POST['confirmpwdreset'])) {
 $resetpwd="Update USERTABLE SET password='". md5($_POST['newpwd'])."' WHERE emailid='".$verifymail."'"; 
 if(mysql_query($resetpwd))
 {
  $removeverifystring="Update USERTABLE SET forgotpwd='' WHERE emailid='".$verifymail."'";
  mysql_query($removeverifystring);
 }
 echo "<b>Your Password has been reset successfully.Login with your new password</b>";
}
else{
if($verify!=''){
$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">
<table>
<tr>
<td>New password: </td><td><input type="password" name="newpwd"></td>
</tr>
<tr>
<td>Confirm password: </td><td><input type="password" name="confirmpwd"></td>
</tr>
<tr>
<td></td><td><input type="submit" name="confirmpwdreset" value="Confirm"></td>
</tr>
</table>
<?php
} 

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

Java code to remove redundant data / duplicate entries spread across multiple Files
Ajinkya Mandhare1:58 pm 0 comments

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";


  while(i<=no)
  {
  source = "Filepath\\File"+i+".txt";
  copyContent(source, dest);
  ++i;
  }
  
  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) {
   out.write(aLine);
   out.newLine();
  }
  out.newLine();
  out.newLine();
 
  out.write("***************************************************");
  out.newLine();
  out.newLine();
  
  in.close();
 
  out.close();
  
 }
 
 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) {
   j=i;
   flag=0;
   File fin1 = new File(dest);
   FileInputStream fis1 = new FileInputStream(fin1);
   BufferedReader in1;
   in1 = new BufferedReader(new InputStreamReader(fis1));

   if(aLine.equals("***************************************************")==true || i==1)
   {
    out.write(aLine);
    out.newLine();
    
   }
   else{
    while(j>1)
    {
     bLine = in1.readLine();
     if (bLine!=null && bLine.equals(aLine)) {
      flag=1;
     }
     --j;
    }

    if(flag==0)
    {
     out.write(aLine);
     out.newLine();

    }
   }
   ++i;
   in1.close();

  }
  
  in.close();
  out.close();
  
  
 }
}


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

Android Tutorial - First Android App: Flashlight
Ajinkya Mandhare11:40 pm 1 comments

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.

Pre-requisites:

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"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/radial_background"
    tools:context=".MainActivity" >

    <ImageButton
        android:id="@+id/btnSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dip"
        android:src="@drawable/btn_switch_on"
        android:background="@null"
        android:contentDescription="@null"
 android:onClick="switchClicked"/>

    <TextView android:text="Developed by aj"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_centerHorizontal="true"
         android:gravity="center"
         android:padding="15dip"
         android:textSize="13dip"
         android:textColor="#3b3b3b"
         android:layout_marginBottom="15dip"/>

</RelativeLayout>

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;

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 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.setTitle("Error");
 alert.setMessage("Sorry, your device doesn't support flash light!");
 alert.setButton("OK", new DialogInterface.OnClickListener() {

 public void onClick(DialogInterface dialog, int which) {
  finish();
 }
 });
 alert.show();
 return;
 }

 getCamera();
 toggleswitch();
 }

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

 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) {
    return;
   }

   params = camera.getParameters();
   params.setFlashMode(Parameters.FLASH_MODE_TORCH);
   camera.setParameters(params);
   camera.startPreview();
   isFlashOn = true;
   toggleswitch();
  }
 }

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

   params = camera.getParameters();
   params.setFlashMode(Parameters.FLASH_MODE_OFF);
   camera.setParameters(params);
   camera.stopPreview();
   isFlashOn = false;
   toggleswitch();
  }
 }

 private void toggleswitch(){
  if(isFlashOn){
   btnSwitch.setImageResource(R.drawable.btn_switch_on);
  }else{
   btnSwitch.setImageResource(R.drawable.btn_switch_off);
  }
 }

 @Override
 protected void onStop() {
  super.onStop();
  if (camera != null) {
   camera.release();
   camera = null;
  }
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
 }

 @Override
 protected void onStart() {
  super.onStart();
  getCamera();
 }

 @Override
 protected void onPause() {
  super.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

Android Bootloop problem Fixed: The 'Jugaad' way
Ajinkya Mandhare10:07 am 1 comments

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


Monday, 9 September 2013

Read an Excel file using PHP
Ajinkya Mandhare9:55 pm 10 comments

Reading an excel file using some server-side scripting language is something that should be in the ammo of any developer. Now, Excel is something which I have always stayed away from...blame it on the insipid UI, or lack of various other features which databases like Oracle, MySql etc provide. However, one cannot deny the fact that Excel is rampantly used to maintain records, and at some point or other, you may have to use excel as an input to your code.

I had faced such a situation recently, and after some googling, I managed to find a way to read the excel sheet and insert the corresponding entries to a MySql database. So, this post of mine will help you in reading an excel sheet using PHP. Once it is read and you have the values of the entries with you, its up to you as to what you like to do with it. In my case, I simply inserted those values in a MySql database.

Have queries?? Get them resolved...

What you need to get started:
PHPExcelReader
SpreadsheetExcelWriter

Download the above two packages. Extract both the packages. Now, in the PHPExcelReader package, find the oleread.inc. Copy this file, and paste it to Spreadsheet\Excel\Reader folder in the SpreadsheetExcelWriter package. It does not have the Reader folder by default. Create that folder and paste the oleread.inc file in it. Now, save the oleread.inc file in the same folder as OLERead.php.
Now, copy the entire Spreadsheet folder from SpreadsheetExcelWriter package, and paste it in the Excel folder in PHPExcelReader package. This 'Excel' folder in the PHPExcelReader package is what we will be using for reading from an excel file using PHP. Once you have done all this copying and pasting, you are all set to read an Excel sheet!!

Step I: Create a simple HTML file 'importexcel.html' to take the excel sheet as an input:
<form action="import.php" enctype="multipart/form-data" method="post">
File Name: <input type="file" name="file" id="file">

<input type="submit" name="Submit" value="Submit" />
</form>

Step II: Create a PHP file 'import.php', where we write the action part for the above form:

<?php

mysql_connect(hostname,username, password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db(dbname);
include 'Excel/reader.php';
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$data->read($_FILES["file"]["tmp_name"]);

//columns:
$sql = "INSERT INTO `TABLENAME` (";

for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++)
{
$sql .= "`" . mysql_escape_string($data->sheets[0]['cells'][1][$j]) . "`,";
}
$sql = substr($sql, 0, -1) . ") VALUES\r\n";
//cells
for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++)
{
  $sql .= "(";
  for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++)
  {
  $sql .= "" . mysql_escape_string($data->sheets[0]['cells'][$i][$j]) . ",";
  }
$sql = substr($sql, 0, -1) . "),\r\n";
}
$sql =  substr($sql, 0, -3) . ";";
echo $sql;

mysql_query($sql);

?>


Make sure that you have the 'Excel' folder in the root directory.

If you look at the output of the code, it will print the INSERT query, which is then used in mysql_query to execute the query.

Whats a take away from this tutorial is that, you can access the entries from the Excel sheet by creating an object ('$data' in our example) of Spreadsheet_Excel_Reader class, and then use this object as $data->sheets[<sheet number>]['cells'][<row number>][<column number>] to access the (row,column)th entry of  the corresponding sheet number in the excel.
Once you can access these entries, you can use them in whichever way you want....creating a table in html, or inserting those entries in a database, or any other processing.

Thats it!! Simple it was, wasn't it? Now, go ahead...use this code to read an Excel sheet....njoy!!

Have Queries?? Post it on our Discussion Forum Compild

Monday, 29 April 2013

Root Samsung Galaxy S2 GT-i9100 Jelly Bean and install Clockwork Recovery Mod
Ajinkya Mandhare6:28 pm 5 comments

With the official Jelly Bean update now available for Galaxy SII, one thing that any android fan would be looking for would be 'How to Root it?'. Rooting the phone unleashes the true power it withholds, making the Android experience all the more exiting! Also, once you root your phone, one very basic thing you need is the Clockwork Recovery Mod.
The below tutorial gives the detailed steps for doing just the same.
The advantage of this method is that, as in the normal rooting, there is no yellow triangle that appears on your booting screen.

Make sure you have following things in place:
  • This guide is for Samsung Galaxy SII GT-i9100 (international version) only. I have not tried this out on any other version
  • Take a backup of whatever you can...ie contacts, messages etc. You  may not be able to take a system backup, as this requires rooted phone
  • Ensure that the phone has atleast 85% battery charge
Have queries?? Get them resolved...


If you have the above things set, then you are ready for what follows...

But first thing first:
Disclaimer: The instructions provided in this guide are meant for reference purpose only. I will not be held liable if the device is damaged during the installation. Users must proceed at their own risk.

This thing hardly takes about 5-10 minutes:

Files needed:
1. SU-BB-Installer.zip(download it from the download box alongside)
2. Clockwork Recovery Mod

And here are the steps:
  1. Place both the files in SD card and boot the phone in recovery mode. To do this, power off your phone & then long press the Volume down + Power + Home buttons simultaneously
  2. You would now be in the stock recovery mode. Now select 'Apply Update from External Storage' and then navigate to the 'SU-BB-Installer.zip' file, and select it using the Power button. Select Yes in the next step...This would now root your phone
  3. Once done, again navigate back to the home screen of the stock recovery, and select 'Apply Update from External Storage'....this time, select the Clockwork Recovery Mod file
  4. This would now replace your stock recovery by the Clockwork Recovery Mod
  5. You can now play around with the various options available in the CWM, like taking a Nandroid backup
  6. Now, reboot your phone
  7. In the list of your applications, you would now see a 'Super User' App. If you are able to see this app...congrats!!... your phone is successfully rooted!
You can now install various apps like the Titanium backup, and other such apps, to tweak the performance of your phone. Once rooted, you also have the luxury to install a number of cool custom firmwares, which would have otherwise required a rooted phone...njoy:)

Now, if you wish to unroot your phone, all you need to do is flash the official Jelly Bean Rom using Odin, and there would be no traces, to prove that your phone was ever rooted!!

Have queries?? Get them resolved on our Discussion Forum Compild

Friday, 8 March 2013

Multi Window and Ripple Lock Screen for Samsung Galaxy S2 GT-i9100 Jelly Bean(4.1.2)
Ajinkya Mandhare10:05 am 71 comments

Samsung recently rolled out the JellyBean 4.1.2 update for Galaxy S2. The S2 users, including myself were eagerly awaiting this upgrade, and the cellphone giant Samsung did not disappoint. The JB for S2 breathes in a new life in the phone with the new Nature UX interface, Google Now, and many other exciting things added to the already feature filled Samsung flagship device Galaxy S2.

Have queries?? Get them resolved...


All said and done, there was still a major update that the S2 users were looking forward to....the much famed 'Multi-Window' feature, as in Galaxy S3 and Note2. This was not included in the JB update for S2, which for me was a let down!!
I tried to search for methods to get multi window for my phone....did so much things in that process that at one time, my phone refused to boot back!!
But then I found out these two methods....

  • 'Installing Mods for the Stock JB firmware'(This method is for the Stock JellyBean)
  • Using Deodexed XWLS8 ROM and applying the MODs on it
 by virtue of which I installed Multi window on S2 successfully....and it is running great!!

There are other methods too, but for that, you need a custom ROM(deodexed XXLSJ).

In this post I would share both these methods of installing the Mods for Galaxy S2 for Multi Window and Ripple Lock Screen.




This process requires the following things in place:
  • It was tried and tested only for the International version of galaxy S2(GT-i9100), running XWLS8 Jelly Bean 4.1.2. I'm not sure about the rest of the versions
  • The Galaxy S2 must be Rooted
  • You must have the Clockwork Recover Mod (CWM) installed (You can download the CWM form: http://www.clockworkmod.com/rommanager)
  • Take a NANDROID backup of your phone, just in case some unexpected problem arises
  • Ensure that the phone has atleast 85% battery charge
As usual, comes the disclaimer:
The instructions provided in this guide are meant for reference purpose only. I will not be held liable if the device is damaged during the installation. Users must proceed at their own risk.

Though I have given two methods to get Multi Window for Galaxy SII, I personally prefer Method 2.

Method 1: 'Installing Mods for the Stock JB firmware'

Files Required:
Alliance Mods for Galaxy S2

Step 1: Download the Mods from MultiWindowMods
Step 2: Place the downloaded file in your Sdcard.
Step 3: Now, reboot into Recovery mode. To do this, Power off your phone, and then press the
Volume Up+ Home+ Power button simultaneously.
Step 4: Now, once you are in Clockwork recovery, select 'Install from Zip' option
Step 5: Now, select the file that we downloaded in step 1
The features will now be installed
Step 6: Now, go back and select Reboot
Step 7: Your phone will now reboot

And, its done!! You will now be graced with a Ripple Lock screen. You now need to enable the Multi Window option from the Display Section and you are all set to boast of a Multi Window!!
Also, a section called Alliance Control will be added to the Settings, wherein you can customize the lock screen and other features. Take care not to select the Alliance OTA option as it may mess up your phone.
Snapshots from Method 1


Method 2: Using Deodexed XWLS8 ROM and applying Multi Window Mods


Files Required:
Deodexed XWLS8 ROM
Multi Window Mods

Step 1: Download the Deodexed XWLS8 ROM from DeodexedXWLS8
Step 2: Place the downloaded zip file in sdcard
Step 3: Reboot into Clockwork Recovery Mode
Step 4: Select install from zip, & then select the zip folder downloaded in Step 1
            The deodexed ROM will now be flashed
Step 5: Once done, reboot the phone....you would be graced with the Ripple Lock Screen
Step 6: Download the Multi Window Mod from Multi_Window_Mods
Step 7: Place the zip file in sdcard and again Reboot into Clockwork recovery mode
Step 8: Select install from zip, and select the zip file for mods downloaded in Step 6
Step 9: The Mods will now be installed
Step 10: Once done, reboot the phone

Thats it!! Select the Multi Window option from Settings ->Display section and you are all ready to start enjoying the magic of Multi Window!!

I preferred Method 2 over 1 for the simple reason, as I now have a deodexed ROM, which gives me greater freedom to play around with my phone, and I don't need to worry about the Alliance Mods!!
Snapshots from Method 2:



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

Tuesday, 2 October 2012

Creating a Barcode in PHP
Ajinkya Mandhare11:53 am 0 comments



A barcode is an optical machine-readable representation of data relating to the object to which it is attached. Originally barcodes represented data by varying the widths and spacings of parallel lines, and may be referred to as linear or one-dimensional (1D).
A Barcode is generally used to map a product to its characteristics. For example, a barcode is commonly used to identify the product code, and map the unique code to the price of the product in the database. This barcode is a widely used technique.
Creating a barcode is a fairly easy job, provided you have the right font for it. I found one, with relative ease, and guess what....it was free of cost!! I have added the font file in free3of9.zip folder, which can be downloaded from the download box present in the sidebar. I really want to thank the creator of this font, for his hardwork, and also making his work available free of charge.
Once you have the right font, the rest is quite an easy job. we will use the basic function in PHP, viz

imagettftext($img, $fontsize, $angle, $xpos, $ypos, $color, $fontfile, $text);
Now, create a PHP file, which I have named as index.php in my case.

Include the following code in the file:

<?php

$number = '*8108137*';

$barcode_font = 'FRE3OF9X.TTF';

$width = 200;
$height = 80;

$img = imagecreate($width, $height);

// First call to imagecolorallocate is the background color
$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);

// Reference for the imagettftext() function
// imagettftext($img, $fontsize, $angle, $xpos, $ypos, $color, $fontfile, $text);
imagettftext($img, 36, 0, 10, 50, $black, $barcode_font, $number);

//imagettftext($img, 14, 0, 40, 70, $black, $plain_font, $number);

header('Content-type: image/png');

imagepng($img);
imagedestroy($img);

?>
Here, in this code, the code for which barcode needs to be generated is stored in the $number variable. Care needs to be taken that the code starts and ends with an asterisk (*). The barcode scanner starts looking for an asterisk, and then scans ahead of * till it reaches the ending *.
For example, if the code is 1234567, it is represented as *1234567*.
Now, this number, or code can be passed from another page, using the GET method of PHP.
Your code is now ready!! Open your project in localhost, and see your code generating a Barcode!! 

If you found the post helpful, please share!!

Saturday, 14 July 2012

Secure Login Code using PHP and MySQL / Preventing SQL Injection using PHP
Ajinkya Mandhare8:37 pm 10 comments

Many Web pages accept parameters from web users and generate SQL queries to the database. SQL Injection is a trick to inject SQL script/command as an input through the web front end.

Your application may be susceptible to SQL Injection attacks when you incorporate invalidated user input into the database queries. Particularly susceptible is a code that constructs dynamic SQL statements with unfiltered user input.



Consider the following example code:
Sql DataAdapter myCommand = new SqlDataAdapter(
"Select * from Users
Where UserName = ' "+txtuid.Text+" ", conn);

Attackers can inject SQL by terminating the intended SQL statement with the single quote character  followed by a semicolon character to begin a new command and then executing the command to their choice. Consider the following character string entered into the .txtuid field.
' OR 1=1
This results in the following statement to be submitted to the database for execution:
SELECT * FROM Users WHERE UserName = ' ' OR 1 = 1;

Because 1=1 is always true, the attacker retrieves very row of data from the user table.

Now, to prevent such an attack, a secure login technique is required. Here, in this article, we discuss the coding of a secure login script using PHP and MySQL.


Step I: Create a database and a table 'members' in it:

CREATE TABLE `members` (
  `username` varchar(20),
  `password` varchar(128)
)



Step II: Create a Login Form:

<form action="process_login.php" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Login" />
</form>


Connect to MySQL Server:

$host = 'localhost'; // Host name Normally 'LocalHost'
$user = 'root'; // MySQL login username
$pass = ''; // MySQL login password
$database = 'test'; // Database name
$table = 'members'; // Members name
 
mysql_connect($host, $user, $pass);
mysql_select_db($database);


Step III: Now, you need to provide mechanism to avoid SQL Injection. For this, escape special characters like ", ', \

We can escape special characters (prepend backslash) using mysql_real_escape_string or addslashes functions. In most cases PHP will this do automatically for you. But PHP will do so only if the magic_quotes_gpc setting is set to On in the php.ini file.
If the setting is off, we use mysql_real_escape_string function to escape special characters. If you are using PHP version less that 4.3.0, you can use the addslashes function instead.

name = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
 
$result = mysql_query("SELECT * FROM $table WHERE username = '$username' AND password = '$password'
");


Here, we use the MD5(Message Digest 5) Algorithm, that generates the message digest for the password. So, while writing the script for registration page, care must be taken that the md5 of the password entered by the user must be stored in the database, instead of the actual text password.

Validating the login:

if(mysql_num_rows($result))
{
  // Login
  session_start();
  $_SESSION['username'] = htmlspecialchars($username); 
}
else
{
  // Invalid username/password
  echo '<p><strong>Error:</strong> Invalid username or password.</p>';
}
 
// Redirect
header('Location: http://www.example.com/loggedin.php');
exit;


You are done!! This code will help prevent the SQL injection problem. However, it must be noted that no script is 100% secure. So, it is advisable to provide multilevel security process, which make the login more secure.

Wednesday, 11 July 2012

Auto Refresh a Web Page using AJAX
Ajinkya Mandhare10:19 am 5 comments

AJAX is nothing but Asynchronous JavaScript and XML. It is not a new programming language, but a new way to use the existing standards. It is the art of exchanging data with a server, and updating parts of a web page without reloading the whole page!!

Ajax is not a single technology, but a group of technologies. HTML and CSS can be used in combination to mark up and style information. JavaScript and XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

 Using JavaScript for periodically refreshing a page can be quite annoying, as the entire page reloads time to time. Hence, a better option would be to use AJAX.
Include the following code in the <head> section of the page....

<script src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
 $.ajaxSetup({ cache: false });
$('#loaddiv').fadeOut('slow').load(window.location.href).fadeIn("slow");
}, 20000);
</script>


The section now refreshes after every 20 seconds. You can change the 20000 value to suite your requirements.
You can remove the ".fadeOut('slow')" and ".fadeIn(Slow)" parts if you want the page to be refreshed unnoticed.

Now, whichever section you want to be refreshed, must be included within the <div id="loaddiv"> tags as follows:

<div id="loaddiv">
<!--Your Content goes here-->
</div>


You are now done!! Enjoy as your page refreshes without you noticing!!

Sunday, 8 July 2012

Checking if your Computer has been violated and infected with DNS Changer
Ajinkya Mandhare9:42 am 0 comments

Domain name system (DNS) is the part of the internet that links a website name (say example.com) to its numerical internet protocol equivalent (say 123.456.789.098). As the cyber world awaits Monday, when the FBI will shut down servers affected by the DNS changer malware, there is still a day to check if your system has been affected.
Various cyber security firms are offering free solutions. You can visit www.mcafee.com/dnsdetect to check if your computer is infected.
You can also manually check if your DNS server has been changed.

Step I: Open Command Prompt.
           Navigate to Start-> Run.  Type cmd and hit enter.


StepII: (For Windows XP)Type ipconfig/all and hit enter.
           (For Windows 7) Type ipconfig/allcompartments/all and hit enter.


Step III: (For Windows XP) The command you entered displays information about your computer’s network settings. Read the line starting with "DNS Servers". There might be two or more IP addresses listed there. These are the DNS servers your computer uses. Write down these numbers.

(For Windows 7) The output will be very long, since Windows7 by default has support for IPv6. Most likely, you want to look for the IPv4 information under the section entitled “Ethernet adapter…”. Look for the “DNS Servers” line, and write down these numbers. There may be two IP addresses listed there.

Step IV: Check if your DNS settings are OK

Compare your DNS settings with the known malicious Rove DNS settings listed below:
Starting IP Ending IP CIDR
85.255.112.0 85.255.127.255 85.255.112.0/20
67.210.0.0 67.210.15.255 67.210.0.0/20
93.188.160.0 93.188.167.255 93.188.160.0/21
77.67.83.0 77.67.83.255 77.67.83.0/24
213.109.64.0 213.109.79.255 213.109.64.0/20
64.28.176.0 64.28.191.255 64.28.176.0/20

 What if you are infected?
If you computer is infected, please refer the page that list tools to clean DNS Changer and other self help guides to clean your computer – http://www.dcwg.org/fix/

Monday, 2 July 2012

How to create CAPTCHA using PHP
Ajinkya Mandhare12:10 pm 6 comments

CAPTCHA:  Completely Automated Public Turing Test To Tell Computers and Humans Apart.

A CAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot. For example, humans can read distorted text as the one shown alongside, but current computer programs can't:

The term CAPTCHA (for Completely Automated Public Turing Test To Tell Computers and Humans Apart) was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas Hopper and John Langford of Carnegie Mellon University.

Generating a simple CAPTCHA and its verification is quiet a simple task using PHP. In this post, I would do the same, but the CAPTCHA generated would be a simple one, while the reader can add his own creativity to it later!!

  • Step I: Create a file captchaimg.php, and add the following code to it:

<?php 
session_start(); 
header("Content-Type: image/png");
$text=substr(md5(uniqid(rand(), true)),0,5);
$_SESSION["vercode"] = $text; 
$height = 25; 
$width = 65; 
  
$image_p = imagecreate($width, $height); 
$black = imagecolorallocate($image_p, 0, 0, 0); 
$white = imagecolorallocate($image_p, 255, 255, 255); 
$font_size = 14; 
  
imagestring($image_p, $font_size, 5, 5, $text, $white); 
imagejpeg($image_p, null, 80); 
?>


You can check the above file by opening it in your browser. Everytime you refresh, a new, random alphanumeric string is generated in the CAPTCHA.
  • Step II: Create a form form.php, and add the following code to it:
<?php 
session_start(); 
if ($_POST["vercode"] != $_SESSION["vercode"] OR $_SESSION["vercode"]=='')
  { 
     echo  '<strong>Incorrect verification code.</strong>'; 
  } else { 
     // add form data processing code here 
     echo  '<strong>Verification successful.</strong>'; 
}; 
?>
<form action="form.php" method="post"> 
Comment: <input type="text" name="coment"> 
Enter Code <img src="captchaimg.php" /><input name="vercode" type="text" /> 
<input name="Submit" type="submit" value="Submit" /> 
</form>


Now, this is it!! Your basic CAPTCHA is ready!! It will look like below:

Another Example:
For this, you need to include a font file in your project folder. I have used AngelicWar.ttf. Download the font from the download box alongside.
Now, Overwrite the file captchaimg with the following code:

<?php
session_start();
header("Content-type: image/png");
$_SESSION["vercode"]="";
$im = imagecreate(105, 50); //Size of the image Width, Height

imagecolorallocate($im, 167, 218, 239);  //Set background color 
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);        

$font = 'AngelicWar.ttf'; // You can replace font by your own        
for($i=0;$i<=5;$i++) {
    $numb=substr(md5(uniqid(rand(), true)),0,1);
    $_SESSION["vercode"].=$numb;
    $angle=rand(-25, 25);
    imagettftext($im, 20, $angle, 8+15*$i, 30, $black, $font, $numb);    
    // Add shadow to the text    
    imagettftext($im, 20, $angle, 9+15*$i, 34, $grey, $font, $numb);    
}
imagepng($im);
imagedestroy($im);
?>

Now, this will result in following CAPTCHA:


For the following CAPTCHA use cheapink.ttf from the download box alongside.



You can enhance it by using two different strings in a single CAPTCHA image, or using some string characteristics.

Want help in creating more creative CAPTCHA?? Feel free to Contact Me.