Tuesday, April 30, 2013

why we use .htaccess file in php list

What is the Difference Between Posts and Pages in WordPress

Often WordPress beginners get confused between posts and pages. By default, WordPress comes with two content types, posts and pages. As a beginner, you are probably wondering what is the difference between them? It seems to have similar fields in the dashboard. It seems to look the same on the website. Why do I need both? When should I use posts? When should I use pages? In this article, we will explain the difference between posts vs. pages in WordPress.

Posts

If you are using WordPress as a blog, then you will end up using posts for majority of your site’s content. Posts are content entries listed in reverse chronological order on your blog’s home page. Due to their reverse chronological order, your posts are meant to be timely. Older posts are archived based on month and year. As the post gets older, the deeper the user has to dig to find it. You have the option to organize your posts based on categories and tags.
Because WordPress posts are published with time and date in mind, they are syndicated through the RSS feeds. This allows your readers to be notified of the most recent post update via RSS feeds. Bloggers can use the RSS feeds to deliver email broadcasts through services like Aweber or MailChimp. You can create a daily and weekly newsletter for your audience to subscribe to. The very timely nature of posts make it extremely social. You can use one of the many social sharing plugins to allow your users to share your posts in social media networks like Twitter, Facebook, Google+, LinkedIn etc.
Posts encourage conversation. They have a built-in commenting feature that allows users to comment on a particular topic. You can go to your Settings » Discussion to turn off comments on older posts if you like.

Pages

Pages are meant to be static “one-off” type content such as your about page, privacy policy, legal disclaimers, etc. While the WordPress database stores the published date of the page, pages are timeless entities. For example, your about page is not suppose to expire. Sure you can go back and make updates to it, but chances are you will not have about page 2012, about page 2013 etc. Because there is no time and date tied to pages, they are not included in your RSS feeds by default. Pages are not meant to be social in most cases thus does not include social sharing buttons, or comments.
You don’t want users to comment on your contact page, or your legal disclaimers page. Just like you probably don’t want others to tweet your privacy policy page in most cases.
Unlike posts, pages are hierarchical by nature. For example, you can have a sub pages within a page. A key example of this in action would be our Blueprint page. This feature allows you to organize your pages together, and even assign a custom template to them.
WordPress by default comes with a feature that allows you create custom page templates using your theme. This allows developers to customize the look of each page when necessary. In most themes, post and pages look the same. But when you are using your page to create a landing page, or a gallery page, then this custom page templates feature comes in very handy.
Pages also have this archaic feature called Order which lets you customize the order of pages by assigning a number value to it. However this feature is extended by plugins like Simple Page Ordering that allows you to drag & drop the order of pages.

Posts vs. Pages (Key Differences)

The differences we list below definitely have exceptions. You can use plugins or code snippets to extend the functionality of both content types. Below is the list of key differences by default.
  • Posts are timely vs. Pages are timeless.
  • Posts are social vs. Pages are NOT.
  • Posts can be categorized vs. Pages are hierarchical.
  • Posts are included in RSS feed vs. Pages are not.
  • Pages have custom template feature vs. Posts do not.

Frequently Asked Questions

How Many Posts and/or Pages can I have?
You can have as many posts and/or pages that you want. There is no limit on the number of posts or pages that can be created.
Are there any SEO advantages to one or the other?
Search engines like content to be organized. Timeless content is considered to be more important however there is a lot of priority given to latest timely content. In short, there may be a difference, but as a beginner you do not need to worry about it. Focus on ma
king your site organized for the user

authorize.net SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL (Solve)

Error with Transaction:
SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed


sloutation for php :

add to function in where curl is call

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

Saturday, April 27, 2013

comma separate mysql join query between two table

SELECT a.*,b.album_name FROM #__simplephotogallery_images a inner join #__simplephotogallery_album b on b.id = a.album_id WHERE FIND_IN_SET('11', `a.album_id`) order by title asc LIMIT 0,20

Thursday, April 25, 2013

xml data post to service using curl in php

<?php
$xmlcontent ='<?xml version="1.0" encoding="utf-8"?>
<Leads>
<Lead>
<LeadId>271425875</LeadId>
<BorrFstNm>Daffadil</BorrFstNm>
<BorrMidNm/>
<BorrLstNm>Duck</BorrLstNm>
<BorrSSN>111-11-1111</BorrSSN>
<BorrDOB/>
<BorrAge/>
<BorrSexCd/>
<BorrEmail>DD1@hotmail.com</BorrEmail>
<BorrVeteranInd/>
<BorrComments/>
<BorrEmployementSts/>
<BorrEmployerName/>
<EmploymentLength/>
<BorrAdr1>9999 Victory Loop</BorrAdr1>
<BorrAdr2/>
<BorrCity>Manassas</BorrCity>
<BorrState>CA</BorrState>
<BorrZip>92620</BorrZip>
<BorrCounty/>
<BorrMaritalSts/>
<BorrSpouseFstNm/>
<BorrSpouseLstNm/>
<HomePh>2106707637</HomePh>
<MobilePh/>
<WorkPh>2108063151</WorkPh>
<WorkPhExt/>
<Income/>
<CreditProfileCd>GOOD</CreditProfileCd>
<BankruptcyType/>
<CoBorrFstNm/>
<CoBorrMidNm/>
<CoBorrLstNm/>
<CoBorrSSN/>
<CoBorrDOB/>
<CoBorrAge/>
<CoBorrEmail/>
<CoBorrHomePh/>
<CoBorrMobilePh/>
<CoBorrWorkPh/>
<CoBorrWorkPhExt/>
<CoBorrIncome/>
<CoBorrAdr1/>
<CoBorrAdr2/>
<CoBorrCity/>
<CoBorrState/>
<CoBorrZip/>
<CoBorrCounty/>
<AddlnContactPhone/>
<AddlnContactEmail/>
<ContactMethod/>
<ContactTime/>
<ContactTimeOther/>
<PropertyTypeCd>1FAM</PropertyTypeCd>
<PropertyAdr/>
<PropertyAdr2/>
<PropertyCity/>
<PropertyState/>
<PropertyZip/>
<PropertyZip4/>
<PropertyCounty>Orange</PropertyCounty>
<PropertyValue>770000</PropertyValue>
<PropertyPurchasedYear>2009</PropertyPurchasedYear>
<LoanPurpose>RFRT</LoanPurpose>
<InterestRate>3.5</InterestRate>
<DesiredRate/>
<CashOut/>
<ExtraCashOut/>
<QualFico/>
<LiabilitiesPaid/>
<LiabilitiesNotPaid/>
<ReasonForAmount>Lower My Monthly Payment</ReasonForAmount>
<MortgageAmount>420001</MortgageAmount>
<RequestedAmount>417501</RequestedAmount>
<AmortTypCd>FIXD</AmortTypCd>
<RequestedAmortType/>
<DesiredMonthlyPayment/>
<DownPaymentAmt/>
<MonthlyDebtPayments/>
<CreditCardDebt/>
<PurchasePrice/>
<ConsumerComments/>
<MortgageProvider/>
<MortgageType>CONV</MortgageType>
<RequestedMortgageTypeCd>VA</RequestedMortgageTypeCd>
<OriginalLeadDtm>2012-05-08T10:59:29</OriginalLeadDtm>
<SubmittedIP>140.194.192.100</SubmittedIP>
<WebBrowser/>
<InvestorName/>
<InvestorLoanNum/>
<ServicerName/>
<ServicerLoanNum/>
<LoanTypeCd>FRWD</LoanTypeCd>
<BorrEthnicityCd/>
<CoBorrEthnicityCd/>
<BorrowerRace>
<RaceCd/>
<RaceCd/>
</BorrowerRace>
<CoBorrowerRace>
<RaceCd/>
<RaceCd/>
</CoBorrowerRace>
<PullCreditFlag/>
<MonthlyPropTaxes/>
<TotalLiquidAssets/>
<MonthlyHazardInsurance/>
<MonthlyMortgageInsurance/>
<MonthlyHOAFees/>
<LeadSourceCd>140268</LeadSourceCd>
<AdditionalInformation>
<Item>
<ItemName>LeadManagement</ItemName>
<ItemValue>140268</ItemValue>
</Item>
</AdditionalInformation>
</Lead>
</Leads>';
$URL = "http://service.com";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xmlcontent");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
print_r($output);
curl_close($ch);

Tuesday, April 23, 2013

WordPress Creating Admin Menu and Sub Menu

WordPress Creating Admin Menu and Sub Menu


I am working on a wordpress plugin nowadays and would like to share few concepts with you. One of those is to create Admin Menu and Sub Menus.
Menus are integral part of any website, let alone wordpress. Ok so lets get started.
Now with wordpress good thing is that you can take your plugin to any limit. WordPress offers such flexibility that I sometime am overwhelmed with just a thought about what can be achieved. So finally I decided to write my first wordpress plugin.
This post is not about developing plugin from scratch but is more on topic about how to go about creating Admin Menu and Sub Menu on the main left Navigation. WordPress version I am using is 3.3.2
There are 3 topics I will cover in this post.
  1. Hooks required for creating Admin Menu
  2. Admin Sub Menu
  3. A basic landing page when you click on a Menu Item.
Ok so lets get started.
I assume that you already know what hooks and filters are, If not then you are better off reading this article
http://codex.wordpress.org/Plugin_API
Ok so you read the above article and now ready to groove.
I am in fovor of showing with example so its better If I take that opportunity and create a basic wireframe Plugin and I call this Plugin as “jcorgtestplugin“. We will however will just be concentrating on Admin Menu and Sub Menus. You can download the source for what I’ve done later.
Ok first create a folder under plugins directory of your WordPress Install  /path/to/wordpress/root/wp-content/plugins/jcorgtestplugin, below is how it looks on my machine.
Wordpress Menu and Submenus Tutorial

Now create a file called jcorgtestplugin.php under the newly created folder and insert the lines below into that file.
  1. <?php
  2. /*
  3. Plugin Name: My test Plugin
  4. */
  5. ?>

Advertisement


Now goto WordPress administration and the Check you Plugins, Your new plugin will show up in the list as shown below
Wordpress Admin Menu and Submenu
Now if you Activate/Deactivate this plugin Nothing happens. Well that’s true because we haven’t done anything cool yet. This Post is about showing you how to Add you Menu and Submenu under the Admin panel.
Ok so lets look into that now, I’ve covered the above mentioned things just so that you know what I am talking about.
The hook that is required for your Admin Menu and Submenu to appear on Left is called admin_menu
So in the above created file add this line of code.
  1. add_action("admin_menu","jcorgcr_create_menu_test");
add_action function accepts 4 parameters, here is an explanation in case you don’t know about this function already add_action( $tag, $callback_fn, $priority, $accepted_args ); Parameters
$tag -(required) The name of the action Default: None. In our case we are using admin_menu $callback_fn (required) The name of the function that will handle our menu. Default: None, We are using “jcorgcr_create_menu_test$priority (optional) Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. Default: 10 $accepted_args (optional) The number of arguments the function accepts. Default: 1
Now lets create function called jcorgcr_create_menu_test, its shown below
  1. function jcorgcr_create_menu_test(){
  2. //create new top-level menu
  3. add_menu_page('My Test Plugin Settings', 'Test Plugin',
     'administrator', 
    __FILE__, 'jcorgcr_settings_page',plugins_url('/path/to/p;ugin/icon',
      __FILE__));
  4. // create a new submenu
  5. add_submenu_page( __FILE__, 'Categories Page', 'Manage Categories',
     'administrator', __FILE__.'_categories_settings',  
    'jcorgcr_settings_categories');
  6.  
  7. }
Now if you save your Plugin file and try to activate it you will see a Menu and Submenmu for your test Plugin as shown below.
Wordpress Menu And submenu
In the above pic Icon is not showing up because /path/to/p;ugin/icon is invalid path in above function. But you get the Idea.
Now lets see whats happening in above function line by line
// declare the handler function and is required because this is
// expected by WP because of this call,
// add_action("admin_menu","jcorgcr_create_menu_test");
function jcorgcr_create_menu_test(){
        //create new top-level menu
        add_menu_page('My Test Plugin Settings', 'Test Plugin','administrator',
 __FILE__, 'jcorgcr_settings_page',plugins_url('/path/to/p;ugin/icon', __FILE__));
add_menu_page is essential to create top level navigational menu. lets go through parameters of this function
definition of add_menu_page is shown below
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
 below is what this function parameters mean
$page_title (required) The text to be displayed in the title tags of the page when the menu is selected Default: None
$menu_title (required) The on-screen name text for the menu Default: None. We used “Test Plugin” in our example
$capability (required) The capability required for this menu to be displayed to the user. User levels are deprecated and should not be used here! Default: None. Read more about capabilities here http://codex.wordpress.org/Roles_and_Capabilities
$menu_slug  (required) The slug name to refer to this menu by. This should be Unique name for your menu. In our case we are using PHP file that will handle the display. Default: None
$function The function that displays the page content for the menu page. As you see that we are using jcorgcr_settings_page which will be used to create the markup for our main settings page.
$icon_url (optional) The url to the icon to be used for this menu. This parameter is optional. Icons should be fairly small, around 16 x 16 pixels for best results.
$position (integer) (optional) The position in the menu order this menu should appear. The higher the number, the lower its position in the menu. Try to use unique number every time else your Menu can be overwritten by another carying the same number
// Now lets check the sub menu function
        add_submenu_page( __FILE__, 'Categories Page', 'Manage Categories'
,'administrator', __FILE

Read more: http://jaspreetchahal.org/wordpress-creating-admin-menu-and-sub-menu/#ixzz2RIv5ze8W

Sunday, April 21, 2013

top php testing tools list

PHP is one of the most widely used open-source server-side scripting languages that exist today. With over 20 million indexed domains using PHP, including major websites like Facebook, Digg and WordPress, there are good reasons why many Web developers prefer it to other server-side scripting languages, such as Python and Ruby.
PHP is faster (updated), and it is the most used scripting language in practice; it has detailed documentation, a huge community, numerous ready-to-use scripts and well-supported frameworks; and most importantly, it’s much easier to get started with PHP than with other scripting languages (Python, for example). That’s why it makes perfect sense to provide the huge community of PHP developers with an overview of useful tools and resources that can make their development process easier and more effective.
This post presents 50 useful PHP tools that can significantly improve your programming workflow. Among other things, you’ll find a plethora of libraries and classes that aid in debugging, testing, profiling and code-authoring in PHP.
You may also want to take a look at the following related posts:
(Smashing’s note: If you are looking for a good book on mobile, this is the one. A truly smashing book on best design and coding practices for mobile, Responsive Web design and UX design for mobile. Get it now!)

Debugging Tools

  • Webgrind
    Webgrind is an Xdebug profiling Web front end in PHP 5. It implements a subset of the features of kcachegrind, installs in seconds and works on all platforms. For quick ‘n’ dirty optimizations, it does the job. Webgrind
  • Xdebug
    Xdebug is one of the most popular debugging PHP extensions. It provides a ton of useful data to help you quickly find bugs in your source code. Xdebug plugs right into many of the most popular PHP applications, such as PHPEclipse and phpDesigner.
  • Gubed PHP Debugger
    As the name implies, Gubed PHP Debugger is a PHP debugging tool for hunting down logic errors.
  • DBG
    DBG is a robust and popular PHP debugger for use in local and remote PHP debugging. It plugs into numerous PHP IDE’s and can easily be used with the command line.
  • PHP_Debug
    PHP_Debug is an open-source project that gives you useful information about your PHP code that can be used for debugging. It can output processing times of your PHP and SQL, check the performance of particular code blocks and get variable dumps in graphical form, which is great if you need a more visual output than the one given to you by print_r() or var_dump().
  • PHP_Dyn
    PHP_Dyn is another excellent PHP debugging tool that’s open-source. You can trace execution and get an output of the argument and return values of your functions.
  • MacGDBp
    MacGDBp is a live PHP debugger application for the Mac OS. It has all the features you’d expect from a fully featured debugger, such as the ability to step through your code and set breakpoints.

Testing and Optimization Tools

  • PHPUnit
    PHPUnit is a complete port of the popular JUnit unit testing suite to PHP 5. It’s a tool that helps you test your Web application’s stability and scalability. Writing test cases within the PHPUnit framework is easy; here’s how to do it.
  • SimpleTest
    SimpleTest is a straightforward unit-testing platform for PHP applications. To get up and running with SimpleTest quickly, read through this pragmatic tutorial that shows you how to create a new test case. Simpletest
  • Selenium
    Selenium Remote Control (RC) is a test tool that allows you to write automated Web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser. It can be used in conjunction with PHPUnit to create and run automated tests within a Web browser.
  • PHP_CodeSniffer
    PHP_CodeSniffer is a PHP 5 script for detecting conformance to a predefined PHP coding standard. It’s a helpful tool for maintaining uniform coding styles for large projects and teams.
  • dBug
    dBug is ColdFusion’s cfDump for PHP. It’s a simple tool for outputting data tables that contain information about arrays, classes and objects, database resources and XML resources, making it very useful for debugging purposes. dBug - Screenshot
  • PHP Profile Class
    PHP Profile Class is an excellent PHP profiling tool for your Web applications. Using this class will help you quickly and easily gain insight into which parts of your app could use some refactoring and optimization.

Documentation Tools

  • phpDocumentor
    phpDocumentor (also known as phpdoc and phpdocu) is a documentation tool for your PHP source code. It has an innumerable amount of features, including the ability to output in HTML, PDF, CHM and XML DocBook formats, and has both a Web-based and command-line interface as well as source-code highlighting. To learn more about phpDocumentor, check out the online manual.
  • PHP DOX
    An AJAX-powered PHP documentation search engine that enables you to search titles from all PHP documentation pages.

Security Tools

  • Securimage
    Securimage is a free, open-source PHP CAPTCHA script for generating complex images and CAPTCHA codes to protect forms from spam and abuse.
  • Scavenger
    Scavenger is an open-source, real-time vulnerability management tool. It helps system administrators respond to vulnerability findings, track vulnerability findings and review accepted and false-positive answered vulnerabilities, without “nagging” them with old vulnerabilities.
  • PHP-IDS
    PHP-IDS (PHP-Intrusion Detection System) is a simple-to-use, well-structured, fast and state-of-the-art security layer for your PHP-based Web application.
  • Pixy: PHP Security Scanner
    Pixy is a Java program that performs automatic scans of PHP 4 source code, aimed to detect XSS and SQL injection vulnerabilities. Pixy takes a PHP program as input and creates a report that lists possible vulnerable points in the program, along with additional information for understanding the vulnerability.

Image Manipulation and Graphs

  • PHP/SWF Charts
    PHP/SWF Charts is a powerful PHP tool that enables you to create attractive Web charts and graphs from dynamic data. You can use PHP scripts to generate and gather data from databases, then pass it to this tool to generate Flash (SWF) charts and graphs.
  • pChart – a chart-drawing PHP library
    pChart is a PHP class-oriented framework designed to create aliased charts. Most of today’s chart libraries have a cost; this one is free. Data can be retrieved from SQL queries or CSV files or can be manually provided. Chart - Screenshot
  • WideImage
    WideImage is a PHP library for dynamic image manipulation and processing for PHP 5. To be able to use the library, you should have the GD PHP extension installed on your Web server.
  • MagickWand For PHP
    MagickWand For PHP is a PHP module suite for working with the ImageMagick API, which lets you create, compose and edit bitmap images. It’s a useful tool for quickly incorporating image-editing features in your PHP applications.

PHP Code Beautifier

  • PHP_Beautifier
    PHP Beautifier is a PEAR package for automatically formatting and “beautifying” PHP 4 and PHP 5 source code.
  • PHPCodeBeautifier
    PHPCodeBeautifier is a tool that saves you from hours of reformatting code to suit your own way of presenting it. A GUI version allows you to process files visually; a command-line version can be batched or integrated with other tools (like CVS, SubVersion, IDE, etc.); and there is also an integrated tool of PHPEdit.
  • GeSHi – Generic Syntax Highlighter
    GeSHi is designed to be a simple but powerful highlighting class, with the goal of supporting a wide range of popular languages. Developers can easily add new languages for highlighting and define easily customizable output formats.

Version-Control Systems

  • Phing
    Phing is a popular project version-control system for PHP. It is a useful tool for organizing and maintaining different builds of your project.
  • xinc
    xinc is a continuous integration server version-control system written in PHP 5 (i.e. continuous builds instead of nightly builds). It works great with other systems such as Subversion and Phing.

Useful Extensions, Utilities and Classes

  • SimplePie
    SimplePie is a PHP class that helps you work with RSS feeds. Check out the online RSS and Atom feed reader, which demonstrates a simple Web application that uses SimplePie. SimplePie - Screenshot
  • HTML Purifier
    HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier not only removes all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive white list, it also makes sure your documents are standards-compliant. Open source and highly customizable.
  • TCPDF
    TCPDF is an open-source PHP class for generating PDF documents.
  • htmlSQL
    htmlSQL is a unique tool. It is a PHP class for querying HTML values in an SQL-like syntax. Check out the live demonstration of how htmlSQL works.
  • The Greatest PHP Snippet File Ever (Using Quicktext for Notepad++)
    “A little something for all coders: a snippets file that I use for PHP coding. This is designed to be used with Quicktext for Notepad++, but feel free to adapt it to whatever text editor you prefer.”
  • Creole
    Creole is a database abstraction layer for PHP5. It abstracts PHP’s native database-specific API to create more portable code while also providing developers with a clean, fully object-oriented interface based loosely on the API for Java’s JDBC.
  • PHPLinq
    LINQ is a component that adds native data querying capabilities to PHP using a syntax reminiscent of SQL. It defines a set of query operators that can be used to query, project and filter data in arrays, enumerable classes, XML, relational databases and third-party data sources. [via]
  • PHPMathPublisher
    With PhpMathPublisher, you can publish mathematical documents on the Web using only a PHP script (no LaTeX programs on the server and no MathML). Math - Screenshot
  • phpMyAdmin
    If you’re working with PHP, there’s a big chance you’re set up in a LAMP configuration. phpMyAdmin is Web-based tool for managing, building, importing, exporting and exploring MySQL databases.
  • PHPExcel
    PHPExcel is a set of useful PHP classes for working with Microsoft Excel files. PHPExcel allows you to read Excel files and write to them. This is useful for dynamically generating Excel spreadsheets for downloading.
  • Phormer
    Phormer is a PHP-based photo gallery management application that helps you to store, categorize and trim your photos online.
  • xajax PHP Class Library
    xajax is a PHP class for easily working with PHP AJAX applications. It gives you an easy-to-use API for quickly managing AJAX-related tasks. Check out the xajax Multiplier demo and the Graffiti Wall demo to see the xajax PHP class in action.
  • PHP User Class
    PHP User Class is an excellent script that helps you create a system for user authentication (i.e. registration, log in, account profile, etc.). It’s a useful utility to have around if you require user registration for your Web applications.
  • PHP-GTK
    PHP-GTK is a PHP extension for the GTK+ toolkit (a robust toolkit for developing GUIs). It is a suite of useful OOP functions and classes to help you rapidly build cross-platform, client-side GUI’s for your application.

PHP Online Tools and Resources

  • Minify!
    Minify is a PHP 5 app that can combine multiple CSS or JavaScript files, compress their content (i.e. remove unnecessary white space and comments) and serve the results with HTTP encoding (via Gzip/deflate) and headers that allow optimal client-side caching. This will help you follow several of Yahoo!’s Rules for High Performance Websites. minify - Screenshot
  • HTTP_StaticMerger: Automatic “merging” of CSS and JavaScript files
    This library automatically merges sets of static files (CSS or JavaScript) and speeds up page loading (by lowering the number of HTTP queries). It is recommended to use this together with caching reverse-proxy to minimize the response time.
  • PHP Object Generator
    PHP Object Generator is an open-source Web-based tool that helps you quickly construct PHP objects and leverage object-oriented programming (OOP) principles in your code. Php Object Generator - Screenshot
  • gotAPI/PHP
    gotAPI is a useful online tool for quickly looking up PHP functions and classes. Also check out the Quick PHP look-up widget example in case you’d like to include this awesome look-up feature on your website. gotAPI/PHP - Screenshot
  • koders
    koders is a search engine for open-source and downloadable code. It currently has over a billion lines of code indexed and isn’t limited to just PHP.
  • PECL
    PECL is a directory of all known PHP extensions and a hosting facility for downloading and developing PHP extensions.

In-Browser Tools (Firefox Add-Ons)

  • FirePHP
    FirePHP is a Firefox extension that allows you to log data in Firebug. It has a variety of useful logging features, such as the ability to change your error and exception handling on the fly and to log errors directly to the Firebug console. To learn more about what FirePHP can do, check out the FirePHP guide on how to use FirePHP. For developers using the Zend PHP framework, you might find this guide on using FirePHP with Zend useful. FirePHP - Screenshot
  • phpLangEditor
    phpLangEditor is a very handy Firefox add-on for translating language files and variables in your script. phpLangEditor - Screenshot
  • PHP Lookup
    PHP Lookup is a built-in search bar to help you quickly look up references to PHP syntax.
  • PHP Manual Search
    PHP Manual Search is a handy search bar that searches official PHP documentation from within your Web browser.

Frameworks for PHP

  • Dwoo
    Dwoo is a PHP 5 template engine positioned as an alternative to Smarty. It is (nearly) fully compatible with its templates and plug-ins, but it is being written from scratch and is aimed to go one step further with a cleaner code base.
  • CodeIgniter
    CodeIgniter is a powerful, high-performance, open-source PHP framework that helps you author PHP applications rapidly. CodeIgniter is known for having a light footprint, thereby reducing your server’s work. You can get up and running with CodeIgniter in a jiffy: it has an awesome online manual, a couple of helpful video tutorials and an active user forum. CodeIgniter - Screenshot
  • YII Framework
    Here is a high-performance component-based PHP framework that is supposed to be more efficient than CodeIgniter, CakePHP, ZF and Symfony. An optimal solution for developing large-scale Web applications. Yii supports MVC, DAO/ActiveRecord, I18N/L10N, caching, jQuery-based AJAX support, authentication and role-based access control, scaffolding, input validation, widgets, events, theming and Web services.
  • NetBeans
    A dedicated PHP coding environment and complete integration with web standards. The NetBeans PHP editor is dynamically integrated with NetBeans HTML, JavaScript and CSS editing features such as syntax highlighting and the JavaScript debugger. NetBeans IDE 6.5 fully supports iterative development, so testing PHP projects follows the classic patterns familiar to web developers.
  • Solar
    Solar is a PHP 5 development framework for Web applications derived from the Savant templating engine. Solar uses the MVC architectural pattern and has a host of classes and functions for securing your Web app against SQL injection, cross-website scripting (XSS) and other common exploits. Solar - Screenshot
  • symfony
    symfony is an open-source PHP 5 Web application framework that is well known for its modularity and useful library of classes. To get up and running as fast as possible, you should check out the pragmatic symfony online tutorial called “The symfony 1.2 advent calendar tutorial,” which takes you through a step-by-step example of building your own symfony-based Web application.
  • PEAR – PHP Extension and Application Repository
    PEAR is a popular framework and distribution system for reusable PHP components. The purpose of the framework is to provide a structured library of open-source code for PHP users, a system for code distribution and package maintenance and a standard style for PHP code.
  • Propel
    Propel is an Object-Relational Mapping (ORM) framework for PHP 5. It allows you to access your database using a set of objects, providing a simple API for storing and retrieving data.
  • {{macro}} template engine
    {{macro}} compiles initial templates into executable PHP scripts with very clean syntax (much cleaner than WACT and Smarty) and executes them very fast. The engine doesn’t use an XML-like syntax; there are only two data scopes, global and local, and no more data sources (all data is displayed with regular PHP variables); and the system supports all WACT features such as templates wrapping and including.minify - Screenshot
  • Zend Framework
    The Zend Framework by Zend Technologies (the creators of PHP’s scripting engine) is a popular PHP Web application framework that embraces the principles of PHP OOP; it’s very extensible and has built-in utilities for working with free Web service APIs, such as those of Google, Flickr and Amazon.
  • Qcodo
    Qcodo is an excellent open-source PHP Web application framework. It’s subdivided into two parts: (1) Code Generator, and (2) Qforms. Code Generator handles the creation of object code and PHP and HTML front-end code from your data model. Qforms is an intuitive system for handling and creating complex PHP-driven HTML Web forms. Check out demos of applications that use Qcodo and presentational material that covers Qcodo. Qcodo - Screenshot
  • SAJAX
    SAJAX is a JavaScript and AJAX application framework that works well with PHP (as well as several other server-side scripting languages). See SAJAX at work by going to Wall live demonstration.
  • Smarty
    Smarty is a popular PHP templating system to help you separate PHP logic and front-end code (HTML, CSS, JavaScript). It will keep your projects modular and easier to maintain.
  • CakePHP
    CakePHP is one of the leading PHP frameworks for creating robust, fully-featured Web applications. CakePHP has an extensive and well-organized online manual. If you want to learn via video tutorials, check out the CakePHP screencasts. CakePHP - Screenshot
  • Savant2
    Savant2 is another popular object-oriented PHP templating system. Instead of a special syntax unique to Savant2, you use PHP syntax to develop your project’s template.
  • PHPSpec
    PHPSpec is a simple and intuitive PHP framework. It follows the Behavior-Driven Development principle and therefore allows you to write behavior-oriented code, oftentimes in plain English.

PHP IDEs and Editors

  • PHPEclipse
    PHPEclipse is a popular PHP source-code editor that is open source and runs on all the major operating systems, such as Windows, Linux and Mac OS. It has all the features you’d expect from a PHP source-code editor, such as code-folding, syntax highlighting, hover-over tool tips and support for XDebug and DBG. PHPEclipse - Screenshot
  • PhpED
    PhpED is an excellent IDE for Windows users. It is one of the most robust and feature-packed IDEs currently out on the market and has useful features such as a built-in source-code profiler to find bottlenecks in your PHP source code and excellent integration with third-party apps and services just as front-end code validation. PhpED - Screenshot
  • phpDesigner
    phpDesigner is a lightweight PHP editor/IDE that also handles front-end code and markup remarkably well. Check out the phpDesigner online tutorials, as well as screencasts on phpDesigner to help you learn more about the IDE. phpDesigner - Screenshot
  • Zend Studio
    Zend Studio is an excellent PHP IDE for Eclipse. It’ll help you develop, deploy and manage Rich Internet Applications (RIAs) in an intuitive interface. Zend Studio - Screenshot
  • Aptana PHP
    Aptana PHP is an open-source IDE extension/plug-in to be used in conjunction with Aptana Studio. To learn more, be sure to check out the online documentation about Aptana PHP.
  • PDT
    PDT is a PHP Development Tools framework that’s part of the Eclipse project. PDT includes all the necessary tools for you to create PHP-based Web applications.
  • VS.Php
    VS.Php is a PHP IDE for MS Visual Studio, making it a great IDE for recently converted ASP developers who have used MS VS to develop Web applications. To get you up and running ASAP with VS.Php, check out Jcx.Software’s online tutorials as well as its online documentation.
  • PHPEdit
    PHPEdit is an excellent PHP editor/IDE with a ton of useful features and a very intuitive user interface. To learn more about why PHPEdit is a good IDE, read the 10 reasons to use PHPEdit and view the introductory screencast about PHPEdit.

Friday, April 19, 2013

Android Login and Registration with PHP, MySQL and SQLite

Android Login and Registration with PHP, MySQL and SQLite


In my previous article Android Login and Registration Screen Design i explained designing the login and registration interfaces, but it has no functionality. In this tutorial i am explaining how to build complete login and registration system in android using PHP, MySQL and SQLite. Also this tutorial covers how to build simple API using PHP and MySQL.
Download Code

Prerequisites

This tutorial is combination of some of my previous tutorials. I hope you covered these tutorials before.
Android making HTTP Requests
Android JSON Parsing Tutorial
Android SQLite Database Tutorial
Android Login and Registration Screen Design

API (Application Programming Interface)

⇒ Accepting requests by GET/POST methods
⇒ Interact with PHP classes to get data from database or store in database
⇒ Finally will give output in JSON format
Android Mysql PHP connect

1. Creating MySQL Database and Tables

As I am writing API in PHP I selected MySql database to maintain users and other related information. Open your mysql console or phpmyadmin and run following query to create database and users table.
create database android_api /** Creating Database **/
use android_api /** Selecting Database **/
create table users(
   uid int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
); /** Creating Users Table **/

2. Building PHP API Classes

To make it minimum i tried to use less number of php files. Following are the files are required to build API in php. You can find description of each file in the below image.
android php api directory structor
config.php – This file contains constant variables to connect to database.
<?php
/**
 * Database config variables
 */
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "android_api");
?>
DB_Connect.php – This file is used to connect or disconnect to database.
<?php
class DB_Connect {
    // constructor
    function __construct() {
    }
    // destructor
    function __destruct() {
        // $this->close();
    }
    // Connecting to database
    public function connect() {
        require_once 'config.php';
        // connecting to mysql
        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        // selecting database
        mysql_select_db(DB_DATABASE);
        // return database handler
        return $con;
    }
    // Closing database connection
    public function close() {
        mysql_close();
    }
}
?>
DB_Functions.php – This file contains functions to store user in database, get user from database. You can also add methods like update user, delete user.

user unique id – I am generating unique user id in php using uniqid(”, true) function. Sample user id will be like 4f074eca601fb8.88015924

Encrypted Password – This password is stored using base64_encode method. Each password will need two columns to store in database. One is to store encrypted password and second column is to store salt used to encrypt the password.
<?php
class DB_Functions {
    private $db;
    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }
    // destructor
    function __destruct() {
    }
    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
            return false;
        }
    }
    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {
        $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
        // check for result
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            $salt = $result['salt'];
            $encrypted_password = $result['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
            return false;
        }
    }
    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysql_query("SELECT email from users WHERE email = '$email'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed
            return true;
        } else {
            // user not existed
            return false;
        }
    }
    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {
        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }
    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {
        $hash = base64_encode(sha1($password . $salt, true) . $salt);
        return $hash;
    }
}
?>
index.php – This file plays role of accepting requests and giving response. This file accepts all GET and POST requests. On each request it will talk to database and will give appropriate response in JSON format.
<?php
/**
 * File to handle all API requests
 * Accepts GET and POST
 *
 * Each request will be identified by TAG
 * Response will be JSON data
  /**
 * check for POST request
 */
if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // get tag
    $tag = $_POST['tag'];
    // include db handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);
    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];
        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }
    } else if ($tag == 'register') {
        // Request type is Register new user
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } else {
            // store user
            $user = $db->storeUser($name, $email, $password);
            if ($user) {
                // user stored successfully
                $response["success"] = 1;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else {
        echo "Invalid Request";
    }
} else {
    echo "Access Denied";
}
?>

Types of API JSON Responses

The following are the different types of JSON responses generated by API.
Registration Success Response – Success Code = 1 (User Successfully Stored)
{
    "tag": "register",
    "success": 1,
    "error": 0,
    "uid": "4f074ca1e3df49.06340261",
    "user": {
        "name": "Ravi Tamada",
        "email": "ravi8x@gmail.com",
        "created_at": "2012-01-07 01:03:53",
        "updated_at": null
    }
}
Registration Error Response – Error Code = 1 (Error in storing)
{
    "tag": "register",
    "success": 0,
    "error": 1,
    "error_msg": "Error occured in Registartion"
}
Registration Error Response – Error Code = 2 (User Already Existed)
{
    "tag": "register",
    "success": 0,
    "error": 2,
    "error_msg": "User already existed"
}
Login Success Response – Success Code = 1 (User Logged in)
{
    "tag": "login",
    "success": 1,
    "error": 0,
    "uid": "4f074eca601fb8.88015924",
    "user": {
        "name": "Ravi Tamada",
        "email": "ravi8x@gmail.com",
        "created_at": "2012-01-07 01:03:53",
        "updated_at": null
    }
}
Login Error Response – Error Code = 1 (Login Error – Incorrect username/password)
{
    "tag": "login",
    "success": 0,
    "error": 1,
    "error_msg": "Incorrect email or password!"
}
Here it completes the API part and start the Android Project.

3. Starting Android Project

Until now we wrote server side programming to build simple api. Next thing is build android app to interact with the API. In this project i am coding simple app which will have three screens Login Screen, Registration Screen and a welcome Dashboard Screen. So let’s get started by creating new project in you Eclipse IDE.
1. Create a new project by going to File ⇒ New Android Project. Fill all the details and name your activity as DashboardActivity.
2. Next step is to create a new package to store all our library files. Right Click on ⇒ src ⇒ New ⇒ Package and name it as library.
Android create new package

JSON Parser Class

3. Next we need parser class to parse api response JSON. So create a new class in your library package name it as JSONParser.java and fill it with following code.
JSONParser.java
package com.example.androidhive.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}

SQLite Database Handler Class

4. In the application to store user information i am using SQLite Database. So create new class in you library package folder and name it as DatabaseHandler.java and fill the class with following code. This class file has functions to handle database operations like storing user and getting user.
Android sqlite table structor
DatabaseHandler.java
package com.example.androidhive.library;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "android_api";
    // Login table name
    private static final String TABLE_LOGIN = "login";
    // Login Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_UID = "uid";
    private static final String KEY_CREATED_AT = "created_at";
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
                + KEY_ID + " INTEGER PRIMARY KEY,"
                + KEY_NAME + " TEXT,"
                + KEY_EMAIL + " TEXT UNIQUE,"
                + KEY_UID + " TEXT,"
                + KEY_CREATED_AT + " TEXT" + ")";
        db.execSQL(CREATE_LOGIN_TABLE);
    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
        // Create tables again
        onCreate(db);
    }
    /**
     * Storing user details in database
     * */
    public void addUser(String name, String email, String uid, String created_at) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, name); // Name
        values.put(KEY_EMAIL, email); // Email
        values.put(KEY_UID, uid); // Email
        values.put(KEY_CREATED_AT, created_at); // Created At
        // Inserting Row
        db.insert(TABLE_LOGIN, null, values);
        db.close(); // Closing database connection
    }
    /**
     * Getting user data from database
     * */
    public HashMap<String, String> getUserDetails(){
        HashMap<String,String> user = new HashMap<String,String>();
        String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if(cursor.getCount() > 0){
            user.put("name", cursor.getString(1));
            user.put("email", cursor.getString(2));
            user.put("uid", cursor.getString(3));
            user.put("created_at", cursor.getString(4));
        }
        cursor.close();
        db.close();
        // return user
        return user;
    }
    /**
     * Getting user login status
     * return true if rows are there in table
     * */
    public int getRowCount() {
        String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int rowCount = cursor.getCount();
        db.close();
        cursor.close();
        // return row count
        return rowCount;
    }
    /**
     * Re crate database
     * Delete all tables and create them again
     * */
    public void resetTables(){
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_LOGIN, null, null);
        db.close();
    }
}

User Functions Class

5. Create a new class file under library package and name it as UserFunctions.java. This class will have functions to handle all user events like
loginUser()
registerUser()
getLoginStatus()
logoutUser().
android testing app localhost vs online
In this class all the functions will interact with JSONParser, DatabaseHandler classes. I am testing API in localhost using xampp software. Normally localhost will run on port http://127.0.0.1 or http://localhost/. In AVD to connect to localhost you need to use url http://10.0.2.2/ instead of http://localhost/. If you want deploy your api on website the use the url http://yoursite.com/api/
UserFunctions.java
package com.example.androidhive.library;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.content.Context;
public class UserFunctions {
    private JSONParser jsonParser;
    // Testing in localhost using wamp or xampp
    // use http://10.0.2.2/ to connect to your localhost ie http://localhost/
    private static String loginURL = "http://10.0.2.2/ah_login_api/";
    private static String registerURL = "http://10.0.2.2/ah_login_api/";
    private static String login_tag = "login";
    private static String register_tag = "register";
    // constructor
    public UserFunctions(){
        jsonParser = new JSONParser();
    }
    /**
     * function make Login Request
     * @param email
     * @param password
     * */
    public JSONObject loginUser(String email, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", login_tag));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));
        JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
        // return json
        // Log.e("JSON", json.toString());
        return json;
    }
    /**
     * function make Login Request
     * @param name
     * @param email
     * @param password
     * */
    public JSONObject registerUser(String name, String email, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", register_tag));
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));
        // getting JSON Object
        JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
        // return json
        return json;
    }
    /**
     * Function get Login status
     * */
    public boolean isUserLoggedIn(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        int count = db.getRowCount();
        if(count > 0){
            // user logged in
            return true;
        }
        return false;
    }
    /**
     * Function to logout user
     * Reset Database
     * */
    public boolean logoutUser(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        db.resetTables();
        return true;
    }
}

Designing the Screens

6. Until now we have developed the library classes needed in this application. Next thing is build screens. We need three screens Login Screen, Registration Screen and Dashboard Screen.
Create 3 xml files under res ⇒ layout folder and name them as login.xml, register.xml and dashboard.xml
login.xml – login screen design layout
login.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#3b3b3b" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="10dip" >
        <!--  View Title Label -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"
            android:text="LOGIN"
            android:textSize="25dip"
            android:textStyle="bold" />
        <!--  Email Label -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Email" />
        <!--  Email TextField -->
        <EditText
            android:id="@+id/loginEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <!--  Password Label -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dip"
            android:text="Password" />
        <!--  Password TextField -->
        <EditText
            android:id="@+id/loginPassword"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:password="true" />
        <!--  Error message -->
        <TextView android:id="@+id/login_error"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#e30000"
                    android:padding="10dip"
                    android:textStyle="bold"/>
        <!--  Login Button -->
        <Button
            android:id="@+id/btnLogin"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:text="Login" />
        <!--  Link to Registration Screen -->
        <Button
            android:id="@+id/btnLinkToRegisterScreen"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="I don&apos;t have account. Register Me!"
            android:textColor="#21dbd4"
            android:textStyle="bold" />
    </LinearLayout>
</ScrollView>
android login screen
register.xml – registration screen design layout
register.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#3b3b3b" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="10dip" >
        <!--  View Title Label -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"
            android:text="REGISTER"
            android:textSize="25dip"
            android:textStyle="bold" />
        <!--  Name Label -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Full Name" />
        <!--  Name TextField -->
        <EditText
            android:id="@+id/registerName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <!--  Email Label -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Email" />
        <!--  Email TextField -->
        <EditText
            android:id="@+id/registerEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <!--  Password Label -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dip"
            android:text="Password" />
        <!--  Password TextField -->
        <EditText
            android:id="@+id/registerPassword"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:password="true" />
        <!--  Error message -->
        <TextView android:id="@+id/register_error"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#e30000"
                    android:padding="10dip"
                    android:textStyle="bold"/>
        <!--  Login Button -->
        <Button
            android:id="@+id/btnRegister"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:text="Register" />
        <!--  Link to Login Screen -->
        <Button
            android:id="@+id/btnLinkToLoginScreen"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="Already registred. Login Me!"
            android:textColor="#21dbd4"
            android:textStyle="bold" />
    </LinearLayout>
</ScrollView>
android registration screen
dashboard.xml – dashboard screen design layout
dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#3b3b3b">
    <TextView android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="WELCOME"
              android:textSize="40dip"
              android:gravity="center"
              android:layout_marginTop="20dip"/>
    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Logout Me"
        android:textSize="20dip"
        android:textColor="#21dbd4"
        android:textStyle="bold"
        android:id="@+id/btnLogout"
        android:layout_marginTop="80dip"
        android:background="@null"/>
</LinearLayout>
Android welcome screen

Switching between Activites

7. Now the designing part of the app is done next thing is to create activities for each layout and write functionality to achieve login and registration process.
Create new activities LoginActivity.java and RegisterActivity.java and fill them with respective code below.
LoginActivity.java – Activity to handle login event
LoginActivity.java
package com.example.androidhive;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
public class LoginActivity extends Activity {
    Button btnLogin;
    Button btnLinkToRegister;
    EditText inputEmail;
    EditText inputPassword;
    TextView loginErrorMsg;
    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";
    private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        // Importing all assets like buttons, text fields
        inputEmail = (EditText) findViewById(R.id.loginEmail);
        inputPassword = (EditText) findViewById(R.id.loginPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
        loginErrorMsg = (TextView) findViewById(R.id.login_error);
        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.loginUser(email, password);
                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        loginErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS);
                        if(Integer.parseInt(res) == 1){
                            // user successfully logged in
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");
                            // Clear all previous data in database
                            userFunction.logoutUser(getApplicationContext());
                            db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                       
                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(dashboard);
                            // Close Login Screen
                            finish();
                        }else{
                            // Error in login
                            loginErrorMsg.setText("Incorrect username/password");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });
    }
}
RegisterActivity.java – Activity to handle registration event
LoginActivity.java
package com.example.androidhive;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
    Button btnRegister;
    Button btnLinkToLogin;
    EditText inputFullName;
    EditText inputEmail;
    EditText inputPassword;
    TextView registerErrorMsg;
    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";
    private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        // Importing all assets like buttons, text fields
        inputFullName = (EditText) findViewById(R.id.registerName);
        inputEmail = (EditText) findViewById(R.id.registerEmail);
        inputPassword = (EditText) findViewById(R.id.registerPassword);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
        registerErrorMsg = (TextView) findViewById(R.id.register_error);
        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String name = inputFullName.getText().toString();
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.registerUser(name, email, password);
                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        registerErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS);
                        if(Integer.parseInt(res) == 1){
                            // user successfully registred
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");
                            // Clear all previous data in database
                            userFunction.logoutUser(getApplicationContext());
                            db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(dashboard);
                            // Close Registration Screen
                            finish();
                        }else{
                            // Error in registration
                            registerErrorMsg.setText("Error occured in registration");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        // Link to Login Screen
        btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                startActivity(i);
                // Close Registration View
                finish();
            }
        });
    }
}
DashboardActivity.java – Activity to handle dashboard event
LoginActivity.java
package com.example.androidhive;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.androidhive.library.UserFunctions;
public class DashboardActivity extends Activity {
    UserFunctions userFunctions;
    Button btnLogout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * Dashboard Screen for the application
         * */
        // Check login status in database
        userFunctions = new UserFunctions();
        if(userFunctions.isUserLoggedIn(getApplicationContext())){
       // user already logged in show databoard
            setContentView(R.layout.dashboard);
            btnLogout = (Button) findViewById(R.id.btnLogout);
            btnLogout.setOnClickListener(new View.OnClickListener() {
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    userFunctions.logoutUser(getApplicationContext());
                    Intent login = new Intent(getApplicationContext(), LoginActivity.class);
                    login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(login);
                    // Closing dashboard screen
                    finish();
                }
            });
        }else{
            // user is not logged in show login screen
            Intent login = new Intent(getApplicationContext(), LoginActivity.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);
            // Closing dashboard screen
            finish();
        }
    }
}

Finally Updating AndroidManifest.xml

Don’t forget to update you AndroidManifest.xml file. Change following modifications
⇒ Add Internet Persmissions
⇒ Add Entries of each Activity
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".DashboardActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!--  Login Activity -->
        <activity
            android:label="Login Account"
            android:name=".LoginActivity"></activity>
        <!--  Register Activity -->
        <activity
            android:label="Register New Account"
            android:name=".RegisterActivity"></activity>
    </application>
    <!-- Allow to connect with internet -->
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>
8. Make sure that you have the files placed as in the following image
android app directory structor
Run your project by right clicking on your project folder ⇒ Run As ⇒ 1 Android Application.