Friday, January 29, 2016

Java: Convert a Number Between Any Base (Example + Code)

One of my friend was looking for a Java program which can convert the given number of any base to any desired base number. So I thought to write a simple program for this.

Overview

This post shows a compact Java example that converts a number given in one base to another base. The simple implementation uses Integer.parseInt and Integer.toString, which is convenient for numbers that fit in a 32-bit signed int. Below you'll find the original code, an explanation, example I/O, and a recommended improved version that supports arbitrarily large integers using BigInteger.

How it works (quick summary)

  • Read the number as a String and the source and target bases as integers.
  • Use Integer.parseInt(str, fromBase) to parse the input string into an int.
  • Use Integer.toString(value, toBase) to convert the integer into the target base representation.

Note: Integer.parseInt and Integer.toString support bases from 2 to 36. Digits greater than 9 are represented as letters a–z (for example, 10 -> 'a').

Short example I/O

  • Input number: 1010
  • From base: 2
  • To base: 10
  • Converted value: 10

Original (simple) code examples and explanation

The essential one-line conversion the post demonstrates is:

Integer.toString(Integer.parseInt(str, fromBase), toBase)

This converts the string str from base fromBase to a string representation in base toBase.

Below is the whole program as presented in the original post (kept unchanged):

package com.chapter2;

import java.util.Scanner;

public class conversion {

 /**
  * @param args
  */
 public static void main(String[] args) {
  System.out.println("Enter the number");
  Scanner marut= new Scanner(System.in);

     String number=marut.nextLine();
     System.out.println("Enter the Base of the number");
     int fromBase = marut.nextInt();
     System.out.println("Enter the Base to convert");
     int toBase = marut.nextInt();

     String result=convertFromBaseToBase(number,fromBase,toBase);
     System.out.println("Converted value is: "+result);


 }


 public static String convertFromBaseToBase(String str, int fromBase, int toBase){
     //convert from one base to another
     return Integer.toString(Integer.parseInt(str, fromBase), toBase);
 }

}

Example screenshot

Program output screenshot

Download

You can download this program here:

conversion.java

Limitations and notes

  • Range: Integer.parseInt returns a 32-bit signed int. Very large numbers will cause NumberFormatException or incorrect results if they exceed integer range.
  • Supported bases: 2–36. Characters beyond 'z' are not supported by these methods.
  • Input validation: The original example does not catch parsing exceptions; consider wrapping parsing in try/catch and validating base range.

Improved version (supports large numbers using BigInteger)

If you expect numbers larger than 32-bit range, use BigInteger. The following method converts between bases using BigInteger for arbitrary-precision integers:

// Example conversion using BigInteger
import java.math.BigInteger;

public static String convertUsingBigInteger(String str, int fromBase, int toBase) {
    // Validate bases
    if (fromBase < Character.MIN_RADIX || fromBase > Character.MAX_RADIX
            || toBase < Character.MIN_RADIX || toBase > Character.MAX_RADIX) {
        throw new IllegalArgumentException("Bases must be between " + Character.MIN_RADIX + " and " + Character.MAX_RADIX);
    }

    // Parse with BigInteger and reformat
    BigInteger value = new BigInteger(str, fromBase);
    return value.toString(toBase);
}

Add simple validation and exception handling around user input in the main method:

Scanner sc = new Scanner(System.in);
try {
    System.out.print("Enter the number: ");
    String number = sc.nextLine().trim();
    System.out.print("Enter the Base of the number: ");
    int fromBase = Integer.parseInt(sc.nextLine().trim());
    System.out.print("Enter the Base to convert: ");
    int toBase = Integer.parseInt(sc.nextLine().trim());

    String result = convertUsingBigInteger(number, fromBase, toBase);
    System.out.println("Converted value is: " + result);
} catch (NumberFormatException | IllegalArgumentException e) {
    System.err.println("Invalid input: " + e.getMessage());
}

This approach:

  • Avoids Integer overflow by using arbitrary precision.
  • Ensures cleaner input handling (use nextLine + parse to avoid Scanner newline quirks).
  • Validates base ranges with Character.MINRADIX and Character.MAXRADIX (2–36).

Summary / Recommendations

  • The original code is concise and useful for small integers; keep it as a quick snippet.
  • For production or larger numbers, replace Integer.parseInt/Integer.toString with BigInteger to avoid range issues.
  • Add simple validation and exception handling so users get friendly error messages.
  • Improve on-page SEO by adding this structured content, a short meta description, and internal links to related Java topics.

That's it. The examples and download link above are the same as in the original post.

Thursday, January 28, 2016

Creating REST API to generate OTP in PHP — request_sms.php & verify_otp.php (Part 2)

In continuation with my previous blog Creating-Rest-API-to-generate-otp-part-1, this post covers the rest of the procedure to generate the OTP and exposes the two PHP endpoints used: requestsms.php and verifyotp.php.

Prerequisites

  • Working LAMP/LEMP stack with PHP and cURL enabled.
  • include/DbHandler.php present in your project root. The article assumes DbHandler provides functions invoked below (createUser() and activateUser()).
  • Constants defined somewhere safe (not committed to source): MSG91AUTHKEY and MSG91SENDERID. Prefer environment variables or a protected config file.
  • Database tables: Users and sms_codes (see Part 1 for full schema). The code below expects the createUser(…) and activateUser(…) methods in DbHandler to manage rows and statuses.

What this part covers

  • Creating the request_sms.php endpoint that receives name, email, mobile via POST, creates a user row (initially inactive), generates a 6-digit OTP, saves it and requests an SMS via MSG91.
  • Creating the verify_otp.php endpoint that receives an OTP via POST, matches the user, and activates the user (sets status to 1 in users and sms_codes table).

Notes: The examples below are the original code as used in my test project. I kept the code intact but added security and implementation notes in the sections that follow. Before deploying to production, apply the security improvements listed earlier in this article.

request_sms.php (endpoint to register user and request OTP)

The endpoint receives name, email, and mobile as POST parameters, creates a user with status 0 (inactive) via createUser() in DbHandler, then calls sendSms() which connects to MSG91 REST API and sends a 6-digit OTP.

Below is the code used in request_sms.php:

<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();

if (isset($_POST['mobile']) && $_POST['mobile'] != '') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $mobile = $_POST['mobile'];
    $otp = rand(100000, 999999);

    $res = $db->createUser($name, $email, $mobile, $otp);
    if ($res == USER_CREATED_SUCCESSFULLY) {
        // send sms
        sendSms($mobile, $otp);
        $response["error"] = false;
        $response["message"] = "SMS request is initiated! You will be receiving it shortly.";
    } else if ($res == USER_CREATE_FAILED) {
        $response["error"] = true;
        $response["message"] = "Sorry! Error occurred in registration.";
    } else if ($res == USER_ALREADY_EXISTED) {
        $response["error"] = true;
        $response["message"] = "Mobile number already existed!";
    }
} else {
    $response["error"] = true;
    $response["message"] = "Sorry! mobile number is not valid or missing.";
}

echo json_encode($response);

function sendSms($mobile, $otp) {
    $otp_prefix = ':';
    //Your message to send, Add URL encoding here.
    $message = urlencode("Welcome to Tech Thoughts. Your OTP is '$otp_prefix $otp'");

    $response_type = 'json';

    //Define route
    $route = "4";

    //Prepare you post parameters
    $postData = array(
        'authkey' => MSG91_AUTH_KEY,
        'mobiles' => $mobile,
        'message' => $message,
        'sender' => MSG91_SENDER_ID,
        'route' => $route,
        'response' => $response_type
    );

    //API URL
    $url = "https://control.msg91.com/sendhttp.php";

    // init the resource
    $ch = curl_init();

    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData
        //,CURLOPT_FOLLOWLOCATION => true
    ));

    //Ignore SSL certificate verification (demo only) - do NOT use in production
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    //get response
    $output = curl_exec($ch);

    //Print error if any
    if (curl_errno($ch)) {
        echo 'error:' . curl_error($ch);
    }

    curl_close($ch);
}
?>

Notes and improvements for request_sms.php

  • OTP generation: Use random_int(100000, 999999) (PHP7+) instead of rand(), and implement OTP expiry (timestamp) and attempt counters in the DB.
  • Credentials: Do not hardcode MSG91AUTHKEY and MSG91SENDERID. Use environment variables or a server-side protected config file that is not committed.
  • SSL verification: The example disables SSL verification for demo. In production, remove CURLOPTSSLVERIFYHOST/PEER settings and trust the provider's certificate or provide CA bundle path.
  • Input validation: Validate mobile format and sanitize name and email. Ensure DbHandler uses prepared statements to avoid SQL injection.
  • Response structure: Consider sending HTTP status codes (400 for bad request, 201 for created, 500 for server errors) in addition to JSON.
  • Rate limiting: Implement per-mobile rate limiting to avoid SMS abuse.

Sample outgoing SMS message

Below is the sample SMS message the user will receive to their mobile. The OTP should be prefixed by ":" and space in the message.

"Welcome to Tech Thoughts. Your OTP is : 217798"

verify_otp.php (endpoint to verify OTP)

This endpoint receives otp as a POST parameter, calls activateUser() in DbHandler which should find the matching user and set status to 1 in users and sms_codes table. If the OTP matches and activation succeeds, the complete user profile is returned.

Below is the code used in verify_otp.php:

<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
$response["error"] = false;

if (isset($_POST['otp']) && $_POST['otp'] != '') {
    $otp = $_POST['otp'];

    $user = $db->activateUser($otp);

    if ($user != NULL) {
        $response["message"] = "User created successfully!";
        $response["profile"] = $user;
    } else {
        $response["message"] = "Sorry! Failed to create your account.";
    }
} else {
    $response["message"] = "Sorry! OTP is missing.";
}

echo json_encode($response);
?>

Notes and improvements for verify_otp.php

  • Brute-force protection: Implement rate limiting on OTP verification attempts per mobile/IP and consider increasing lockout after N failed attempts.
  • OTP expiry: Verify that the OTP hasn't expired (store expiration timestamp in sms_codes).
  • Secure responses: Return clear error codes and appropriate HTTP status codes.
  • Atomic activation: Ensure activateUser updates both users and sms_codes in a transaction to avoid inconsistent state.

API testing and download

Now you can test this REST API using Postman (Chrome extension) or use the sample PHP pages supplied in the download. I created two small test files in the sample zip: index.php (collects name, email, mobile and calls requestsms.php) and another verification page (calls verifyotp.php).

Request examples (endpoints)

Request SMS

The below JSON is produced when SMS is queued successfully:

{
    "error": false,
    "message": "SMS request is initiated! You will be receiving it shortly."
}

Verifying user OTP

When the OTP is verified successfully, the full user profile is produced in JSON (example):

{
    "error": false,
    "message": "User created successfully!",
    "profile": {
        "name": "G T Karjol",
        "email": "karjol@gmail.com",
        "mobile": "0000000000",
        "apikey": "4a6ed225209632e5467b237c6b00d310",
        "status": 0,
        "created_at": "2016-01-27 15:12:22"
    }
}

Security and production checklist (summary)

  • Move MSG91 credentials to environment variables (e.g., $_ENV or getenv()).
  • Use randomint() for OTP, store a createdat and expires_at, and hash OTPs if you want to avoid plain-text storage.
  • Re-enable SSL verification and validate provider certificate.
  • Use prepared statements in DbHandler and validate all inputs server-side.
  • Implement rate limiting and lockouts on repeated requests and verification attempts.
  • Use HTTPS for the API endpoints and ensure CORS and authentication policies are appropriate for your clients.

Troubleshooting and next steps

  • If SMS delivery fails, inspect the $output returned by the MSG91 API call and log it to a secure file. Do not echo or expose raw API responses or credentials in production logs.
  • Verify that include/DbHandler.php implements the expected return codes: USERCREATEDSUCCESSFULLY, USERCREATEFAILED, USERALREADYEXISTED, and that activateUser($otp) returns the full user profile on success.
  • Consider adding an audit table for OTP sends and verification attempts to support analytics and abuse detection.

References and downloads

That's it. Happy Coding.

Create a PHP REST API to Generate OTPs (SMS) — Part 1

Now a days Most of the sign in, registration or any bank transactions happen over a OTP security (Over the air pin). So in this article we will see how to create a REST API for generating the OTP.

Going forward, we can use this APIs for the registration purpose from an Android APP. Before you go through this blog, you make sure that you have the basic knowledge of PHP, MySQL and Apache on Windows or Linux. If you are going to work on Windows you need to install WAMP or on Linux you install LAMP.

I am going to use WAMP i.e Window-Apache-MySql-PHP. Before we start, we need to have the third party SMS gateway information to send the SMS as the OTP. You can use MSG91 (http://control.msg91.com/) or sms.serverbasket (http://sms.serverbasket.com/default.asp) or any third party sms gateways. I tried with both the above mentioned gateways.

Work Flow

  1. User Mobile Number will be sent to our Server. If you are using this for the website, the user mobile will be sent from the website. Or if you are using this API in Mobile Application, App sends the user mobile number to our hosted Server.
  2. Our Server requests the SMS Gateway for an SMS to the Mobile number with a verification Code (OTP).
  3. SMS Gateway send the SMS with the verification code to the mobile number.
  4. Verification code will be sent back to the server again for verification (If it's website, user has to type it in the mentioned edit box. or if it's a app, app reads the SMS and sends back the code to the Server).
  5. Our server verifies the code and activates the user or take appropriate action if the code matches with the generated one.

What this tutorial covers

  • Database schema for storing users and OTP codes.
  • PHP code files: config.php, DbConnect.php, DbHandler.php (implementation shown below).
  • How to generate and persist an OTP and send it via an SMS gateway.

This post is Part 1 — continued to part 2 for endpoint wiring and Android client examples.

Requirements

  • WAMP or LAMP stack (Apache, PHP, MySQL).
  • A third-party SMS gateway account (MSG91, SMS Server Basket, etc.) and its API credentials.
  • Basic PHP and MySQL knowledge.

Test your local server

You can test your server by opening the address http://localhost/ in your browser or http:// if remote. Also open http://localhost/phpmyadmin to manage the MySQL database.

Create MySql Database

Open http://localhost/phpmyadmin and execute the below queries to create required database and tables.

Create a database named user_registration.

Once database is created, you can go to that database and click on SQL tab.

Create tables SQL

CREATE TABLE `sms_codes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `code` varchar(6) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(250) NOT NULL,
  `mobile` varchar(10) NOT NULL,
  `apikey` varchar(32) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=64 ;

ALTER TABLE `sms_codes`
  ADD CONSTRAINT `sms_codes_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

phpmyadmin create database screenshot

phpmyadmin SQL tab screenshot

SQL execution success screenshot

Project structure

Create directory c:\wamp\www\OTP_SMS (Windows) and inside it create an include directory. We will place configuration and DB handler files there.

Config.php

Create include/Config.php. This file contains DB constants and SMS gateway constants.

<?php
/**
 * Database configuration
 */
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'user_registration');

/**
 * MSG91 configuration
 */
// auth key
define('MSG91_AUTH_KEY', "");
// sender id should 6 character long
define('MSG91_SENDER_ID', '');

define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);
?>

DbConnect.php

Create include/DbConnect.php. This file handles the database connection.

<?php
/**
 * Handling database connection
 */
class DbConnect {
    private $conn;

    function __construct() {
    }

    function connect() {
        include_once dirname(__FILE__) . '/Config.php';
        $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            exit;
        }
        return $this->conn;
    }
}
?>

DbHandler.php

Create include/DbHandler.php. This file contains the main database operations used by the REST API: creating a user, generating OTPs, checking duplicates and activating users. Below is the code provided in this article (kept intact but reorganized into copyable blocks):

<?php
/**
 * Class to handle all db operations
 * This class will have CRUD methods for database tables
 */
class DbHandler {
    private $conn;

    function __construct() {
        require_once dirname(__FILE__) . '/DbConnect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    /* ------------- `users` table method ------------------ */

    /**
     * Creating new user
     * @param String $name User full name
     * @param String $email User login email id
     * @param String $mobile User mobile number
     * @param String $otp user verificaiton code
     */
    public function createUser($name, $email, $mobile, $otp) {
        $response = array();
        // First check if user already existed in db
        if (!$this->isUserExists($mobile)) {
            // Generating API key
            $api_key = $this->generateApiKey();
            // insert query
            $stmt = $this->conn->prepare("INSERT INTO users(name, email, mobile, apikey, status) values(?, ?, ?, ?, 0)");
            $stmt->bind_param("ssss", $name, $email, $mobile, $api_key);
            $result = $stmt->execute();
            $new_user_id = $stmt->insert_id;
            $stmt->close();

            // create OTP for new user
            $otp_result = $this->createOtp($new_user_id, $otp);

            if ($result) {
                // User successfully inserted
                return USER_CREATED_SUCCESSFULLY;
            } else {
                // Failed to create user
                return USER_CREATE_FAILED;
            }
        } else {
            // User with same mobile already existed in the db
            return USER_ALREADY_EXISTED;
        }

        return $response;
    }

    public function createOtp($user_id, $otp) {
        // delete the old otp if exists
        $stmt = $this->conn->prepare("DELETE FROM sms_codes where user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();

        // insert new otp
        $stmt = $this->conn->prepare("INSERT INTO sms_codes(user_id, code, status) values(?, ?, 0)");
        $stmt->bind_param("is", $user_id, $otp);
        $result = $stmt->execute();
        $stmt->close();
        return $result;
    }

    /**
     * Checking for duplicate user by mobile number
     * @param String $mobile
     * @return boolean
     */
    private function isUserExists($mobile) {
        $stmt = $this->conn->prepare("SELECT id from users WHERE mobile = ? and status = 1");
        $stmt->bind_param("s", $mobile);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
        return $num_rows > 0;
    }

    public function activateUser($otp) {
        $stmt = $this->conn->prepare("SELECT u.id, u.name, u.email, u.mobile, u.apikey, u.status, u.created_at FROM users u, sms_codes WHERE sms_codes.code = ? AND sms_codes.user_id = u.id");
        $stmt->bind_param("s", $otp);
        if ($stmt->execute()) {
            $stmt->bind_result($id, $name, $email, $mobile, $apikey, $status, $created_at);
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                $stmt->fetch();
                $this->activateUserStatus($id);
                $user = array();
                $user["name"] = $name;
                $user["email"] = $email;
                $user["mobile"] = $mobile;
                $user["apikey"] = $apikey;
                $user["status"] = $status;
                $user["created_at"] = $created_at;
                $stmt->close();
                return $user;
            } else {
                $stmt->close();
                return NULL;
            }
        } else {
            return NULL;
        }
    }

    public function activateUserStatus($user_id){
        $stmt = $this->conn->prepare("UPDATE users set status = 1 where id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
    }

    public function updateOtpStatus($user_id){
        $stmt = $this->conn->prepare("UPDATE sms_codes set status = 1 where user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
    }

    /**
     * Generating random Unique MD5 String for user Api key
     */
    private function generateApiKey() {
        return md5(uniqid(rand(), true));
    }
}
?>

Note: The code above uses prepared statements. Keep these files under the include folder.

DbHandler code screenshot

Important production & security considerations (must read)

This tutorial provides a starting implementation. Before using any OTP system in production, consider the following:

  • Always use HTTPS/TLS for API endpoints — never send OTPs or credentials over plaintext HTTP.
  • OTP lifetime: set a short expiry (e.g., 2–10 minutes). The sample schema stores created_at; enforce expiry when validating OTPs.
  • Do not reuse OTPs — generate cryptographically secure random codes (use random_int) and mark them used or expired after verification.
  • Store OTPs securely. Prefer storing a HMAC or salted hash of the OTP rather than the plain code so a DB breach doesn't leak codes.
  • Rate limiting and brute‑force protection: limit OTP requests per number/IP and block after N incorrect attempts.
  • Reuse and concurrency: delete or invalidate older OTPs (example deletes old OTPs before inserting a new one).
  • Logging and monitoring: track failed verifications and unusual request rates.
  • Validate input on server side (mobile number format, lengths) and sanitize all inputs.
  • Handle SMS gateway failures (retry policy, queueing, and reporting to user).
  • Consider user privacy and data regulations in your jurisdiction when storing mobile numbers and logs.

API endpoints (recommended examples)

Example endpoints you will implement (this post prepares the backend code; wiring endpoints and request handling may be in Part 2):

  • POST /register — register a user and send OTP via SMS
  • Request (JSON): {"name":"John Doe","email":"john@example.com","mobile":"9876543210"}
  • Response: 201 Created or error code and message
  • POST /verify — verify OTP and activate user
  • Request (JSON): {"mobile":"9876543210","otp":"123456"}
  • Response: 200 OK and user details or 401 Unauthorized

Always return appropriate HTTP status codes and JSON payloads.

SMS gateway integration (high level)

Use your gateway's HTTP API (example: MSG91). When you call the gateway: handle success and failure, check rate limits, and log gateway responses. The exact request depends on your provider — consult the vendor docs.

Testing and next steps

  • Run the SQL to create tables in phpMyAdmin (screenshots above show the UI flow).
  • Place PHP files under OTP_SMS/include/ and test script flows locally (use Postman/cURL to call endpoints).
  • Implement Part 2 to wire endpoints, add input validation, and include example HTTP requests and Android client code.

References & links

Continued to part -2

Wednesday, January 27, 2016

How to Install WampServer on Windows — Step-by-Step Guide

WAMP (Windows, Apache, MySQL, PHP) is an all-in-one package that installs the basic programs required to run a localhost and build PHP applications. Once installation completes, WampServer provides a tray icon for managing services and settings.

Prerequisites

  • A Windows machine (choose the appropriate 32-bit or 64-bit package depending on your OS).
  • Internet access to download the installer.

Download

Download WampServer from the official site:

Step-by-step installation

  1. Select the correct installer (32-bit or 64-bit) for your Windows installation and download the package. You will see a WampServer installer file at your download location.

  2. Double-click the installation package. Windows may show a security warning — this is expected when running third-party installers. Click Run to proceed.

WampServer installer icon

  1. You will see the standard Windows setup wizard. Proceed through the initial dialogs.

Setup wizard screenshot

  1. Agree to the WampServer license to continue.

License agreement screenshot

  1. Choose the installation location. The author recommends installing WampServer on a drive other than the Windows system drive (for example, D: or E: instead of C:). After selecting the folder, click Next.

Choose installation location

  1. Select additional tasks (optional):
  • Create a Quick Launch icon
  • Create a Desktop icon

Select additional tasks

  1. Click Install to begin the installation.

Installing WampServer progress

  1. The installer copies files and configures bundled services (Apache, MySQL, PHP, phpMyAdmin, SqlBuddy).

Installation progress screenshot

  1. During installation you may be prompted to select a default browser for WampServer (used by some WampServer utilities). If unsure, click Open; Internet Explorer will be the default choice if none is selected.

Choose default browser dialog

  1. After the installer finishes copying files, setup continues with Apache configuration. Windows Firewall may prompt for access. Leave the default options and click "Allow Access" so Apache can accept local connections (this dialog may not appear if Windows Firewall is disabled).

Windows Firewall allow access dialog

  1. You will be prompted for SMTP settings used by PHP's mail() function. The author recommends the following default values during installation:
SMTP: localhost
Email: your-email@example.com

(You can change these later to point to a real SMTP server if required.)

SMTP configuration dialog

  1. Finish the installation and leave "Launch Wamp Server now" checked to start the services immediately.

Installation finished - click Finish

WampServer tray icon states

WampServer adds a tray icon that reflects service status:

  • Red: WampServer is offline; Apache, PHP and MySQL services are not started.
  • Yellow: WampServer is partially offline; one or more services failed to start.
  • Green: All services are running and the development server is ready to use.

WampServer icon states

Yellow state screenshot

Green state screenshot

Testing WampServer

  1. Ensure the WampServer tray icon is green.
  2. Open your web browser and navigate to:
http://127.0.0.1/

or

http://localhost/
  1. If the installation was successful you will see the WampServer welcome screen and server configuration options.

WampServer welcome screen

Final notes

  • After successful installation you will have Apache, MySQL, PHP, phpMyAdmin and SqlBuddy available locally.
  • You are now ready to develop PHP/MySQL applications on your machine.

If you maintain other tutorials on this blog, link from here to:

  • a phpMyAdmin guide,
  • a first PHP page tutorial using localhost,
  • a troubleshooting guide for WampServer service start failures.

These help readers go from installation to practical usage without leaving the site.

Saturday, January 23, 2016

How to Add a Popup Inquiry Form to a Joomla Site (jQuery Ajax Quick Contact)

Greetings of the Day,

TL;DR

Install the free "jQuery Ajax Quick Contact for Joomla with Popup Function" module, configure it as a pop-up module, set the recipient email, assign module positions/pages, publish it — then test the popup on the site.

Prerequisites

  • Administrator access to your Joomla site's backend
  • The module ZIP file downloaded from the vendor
  • Confirm module compatibility with your Joomla version
  • Take a quick backup before installing new extensions

Overview

I was working on a website development for one of my customers. The requirement was: apart from the contact form, they wanted an inquiry form on the home page and side bars — a popup contact form when users click the button.

Instead of developing this from scratch I searched for available extensions and found a suitable free extension: jQuery Ajax Quick Contact for Joomla with Popup Function from JExtentions.

Steps

1. Download the module

First download the extension from the JExtentions Downloads page:

http://jextensions.com/jquery-ajax-quick-contact-module/

2. Login to Joomla administrator

Login to the administrative panel of your Joomla site.

Admin login screenshot

3. Go to Extensions > Manage

Select Extensions in the main menu and click Manage.

Extensions Manage screenshot

4. Install the module

Use the Upload & Install option, choose the downloaded ZIP file and upload.

Upload & Install screenshot

You should get an installation successful message.

Install successful screenshot

5. Open Modules (Extensions > Modules)

Go to Modules in the Extensions menu to find the newly installed JE Quick Contact module.

Modules list screenshot

Open the JE Quick Contact module and configure it.

JE Quick Contact module screenshot

6. Configure the module

  • Select Enable in the jQuery dropdown.
  • Select "Pop Up" as the display type.
  • Enter the pop up button text as desired.
  • Update other configuration values as needed (see the screenshot below for the example configuration).

Module configuration screenshot

Important: Enter the recipient's email address in the module settings. Without a valid recipient email the popup form will not send messages.

Recipient email screenshot

7. Position and publish

  • Select the module position where you want the popup button to appear.
  • Set the module Status to Published.
  • Use the Menu Assignment tab to choose which pages should display the button.

Position & menu assignment screenshot

Save & Close the module.

8. Verify on the frontend

Go to your website and confirm the popup button appears in the chosen position. Click the button to open the popup inquiry form.

Frontend button screenshot

Popup form screenshot

That's it. Happy Coding !

Troubleshooting (short)

  • If installation fails: check file upload limits, folder permissions, and Joomla error logs.
  • If emails are not received: verify the recipient email, check spam folder, and confirm Joomla email settings or SMTP configuration.
  • If the popup button doesn't show: confirm module position, menu assignment, and that the module is published.

Notes and next steps

  • Verify the module is compatible with your Joomla version before installing.
  • Consider compressing or rehosting large images to improve page speed.
  • Add alt text to each image for accessibility and SEO.

References:

Friday, January 22, 2016

Joomla: Fix "Allowed memory size exhausted" PHP error (increase memory_limit safely)

I hosted my website on a Linux server. While I accessed the Contact us page of the site I got the error below:

"Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php"

The error message included the full path to the PHP file, for example: public_html//plugins/system/xyz.php and the line number where the error occurred (in my case it was line 79).

What this error means

PHP enforces a memory limit per process (memory_limit). The message "Allowed memory size of 33554432 bytes exhausted" means a PHP script tried to use more than the configured limit (here 33554432 bytes = 32M).

Common causes:

  • Large data processing (big arrays, large file handling, image processing).
  • A plugin or extension requiring more memory.
  • A bug or infinite loop that consumes memory.
  • A default server-level limit (especially on shared hosting).

Quick, safe fixes (in recommended order)

1) Diagnose first

  • Check the file and the reported line number (e.g., public_html//plugins/system/xyz.php line 79). Look for obvious loops, large allocations or file reads.
  • Temporarily enable error reporting or check logs for fuller stack traces.
  • Use phpinfo() (create a small PHP file with ) to see the configured memory_limit.

2) Increase memory for a single script (temporary)

If you need a quick temporary increase for debugging, you can add an ini_set call near the top of the script that triggers the error. Example (original author snippet):

ini_set('memory_limit', '-1');

Warning: iniset('memorylimit', '-1') removes the limit entirely. This is not recommended on production systems because it can allow runaway processes to consume all server RAM. Prefer setting a specific larger limit, for example:

ini_set('memory_limit', '128M');

Place the iniset line just before the memory-intensive operation or near the top of the plugin file reported in the error (for example, just above line 79 in publichtml//plugins/system/xyz.php). This change affects only the running PHP process executing that file.

3) Make a permanent server-level change (preferred when you control the server)

  • php.ini (global change):

Open your php.ini and change or add:

memory_limit = 128M

Restart the web server (apache/nginx + php-fpm) after changing php.ini.

  • .htaccess (if PHP runs as an Apache module and your host allows it):
php_value memory_limit 128M
  • Joomla configuration (depending on setup):

If you cannot change system files, you can try adding iniset calls in a central place that runs early (but be cautious). On some hosts iniset is disabled.

4) Contact your hosting provider

If you are on shared hosting, the host may enforce a hard limit. Contact support to request a memory increase or upgrade your plan.

Diagnostic steps to avoid simply raising the limit

  • Review the plugin code (here: plugins/system/xyz.php). Try disabling the plugin temporarily to confirm it is the source.
  • Search for large data structures or excessive recursion.
  • Update the extension or check for known bugs.
  • If the operation is intended (e.g., processing very large files), consider reworking the code to use streaming, chunked processing, or temporary files instead of keeping everything in memory.

Example: where to insert ini_set in a plugin file

Open the PHP file referenced in the error (e.g., publichtml//plugins/system/xyz.php) and add an iniset line near the top, before the memory-intensive code runs. For example:

<?php
// plugins/system/xyz.php

// Temporary increase - prefer specific value over -1
ini_set('memory_limit', '128M');

// rest of the plugin code ...

Again: prefer a specific limit (e.g., 128M) over '-1'. Use '-1' only for controlled debugging on a development machine.

Safety and rollback

  • Always make a backup of any file before editing.
  • Test changes on a development or staging site first.
  • If you added ini_set and the page works, use that as a temporary measure while you find the root cause. Remove or reduce the override once you address the memory usage.

Summary checklist

  • Verify file and line number from the error message.
  • Inspect code for loops or big allocations.
  • Try a temporary iniset('memorylimit', '128M') if you control the environment.
  • Prefer changing php.ini or .htaccess for permanent needs.
  • Contact your host if limits are enforced at the server level.
  • Fix the root cause (optimize code, update plugin) rather than permanently removing limits.

That's it. Happy Coding

Thursday, January 21, 2016

How to Enable Google's reCAPTCHA in Joomla — Step‑by‑Step

Introduction

Captcha’s are parts of a website where you sometimes need to type in a word or recognize the images to prove you're a human. Captchas are a great way to prevent spam activity on your website because most "bots" that attempt to post spam cannot read the letters contained in the captcha image.

For years, using Captcha sites prompted users to confirm they aren’t robots by asking them to read distorted text and type it into a box.

Example of a text-based CAPTCHA

But Google released a new API that simplifies the reCAPTCHA experience by just directly asking the users whether or not they are robots. They called it "No CAPTCHA reCAPTCHA". This is how it looks:

No CAPTCHA reCAPTCHA checkbox example

In this article we're going to walk you through the steps for enabling CAPTCHA / reCAPTCHA (Google) in Joomla.

Prerequisites

  • A Joomla administrator account with access to Extensions > Plugin Manager and System > Global Configuration.
  • A Google account to create reCAPTCHA keys (Site key and Secret key).

Obtain your reCAPTCHA keys

  1. Sign in with your Google account at the Google reCAPTCHA admin panel and register your site to obtain Site and Secret keys:

Create a reCAPTCHA key: https://www.google.com/recaptcha/admin#list

  1. When registering, add your website domain and choose the appropriate reCAPTCHA type (the article refers to the No CAPTCHA checkbox flow; Google now offers v2/v3 and Invisible reCAPTCHA — confirm the current choice in Google's admin).

Step-by-step: Enable reCAPTCHA in Joomla

  1. Log in to your Joomla administrator back-end.

  2. Go to Extensions > Plugin Manager (or find Plugin Manager from the Control Panel).

Joomla Plugin Manager screenshot

  1. Edit the "Captcha - ReCaptcha" plugin.

Edit Captcha ReCaptcha plugin screenshot

a) Set Status to "Enabled".

b) Copy and paste the Site Key and Secret Key from the Google reCAPTCHA admin into their appropriate fields in the plugin settings.

  • You will get the Site and Secret keys by signing in with your Google account here: https://www.google.com/recaptcha/admin#list
  • Once you have registered your website domain, Google will provide your reCAPTCHA keys.

c) Click Save & Close.

Configure Global settings (Contact forms and Registration)

  1. To enable reCAPTCHA for Contact forms and Registration:

a) Go to System > Global Configuration and select the "Site" tab.

Global Configuration - Site tab screenshot

b) In the Default Captcha field choose "Captcha - ReCaptcha".

Default Captcha selection screenshot

c) Click Save & Close.

Configure Registration form-specific behavior

  1. To control reCAPTCHA behavior specifically for user registration (if you need different behavior from the Global Configuration):

a) Go to Users > User Manager.

User Manager screenshot

b) Click "Options" and open the Component tab.

User component options screenshot

c) In the Component tab choose one of the Captcha options:

  • Use Default — follows the Default Captcha setting in Global Configuration.
  • None Selected — ignores the Default Captcha; use this if you want reCAPTCHA in Contact forms but not in Registration.
  • Captcha - ReCaptcha — forces reCAPTCHA for registration even if Global Configuration is set to None.

User component captcha choices screenshot

Click Save & Close.

Troubleshooting and verification

  • Verify the Site and Secret keys are correct and correspond to the registered domain in the Google admin panel.
  • Clear Joomla cache and browser cache after saving plugin/global settings.
  • If reCAPTCHA does not appear, confirm the Captcha plugin is "Enabled" in Plugin Manager and that another extension is not conflicting.
  • Test your Contact form and the Registration form to ensure the reCAPTCHA widget displays and submission succeeds.

Notes

  • The article refers to Google's "No CAPTCHA reCAPTCHA" (checkbox flow). Google offers multiple reCAPTCHA variants (v2 checkbox, Invisible reCAPTCHA, and v3). Confirm the reCAPTCHA type you registered in the Google admin panel before copying keys.

  • Official Google reCAPTCHA admin: https://www.google.com/recaptcha/admin#list

That's it!

Wednesday, January 20, 2016

Android Studio Installation — Setup Guide for Windows, macOS & Linux

Earlier I used to develop android applications using Eclipse IDE. Recently Google has released their own android IDE called as Android Studio. This is now the official Android IDE. So I installed Android Studio and thought of recording and sharing the steps. Here we go.

Android Studio welcome image

Table of Contents

Why Android Studio

Code editor screenshot

At the core of Android Studio is an intelligent code editor capable of advanced code completion, refactoring, and code analysis. The powerful code editor helps you be a more productive Android app developer.

  1. Intelligent code editor

Project templates and GitHub integration

  1. Code templates and GitHub integration

New project wizards make it easier than ever to start a new project. Start projects using template code for patterns such as navigation drawer and view pagers, and even import Google code samples from GitHub.

  1. Multi-screen app development

Multi-screen layout editor

Build apps for Android phones, tablets, Android Wear, Android TV, Android Auto and Google Glass. With the new Android Project View and module support in Android Studio, it's easier to manage app projects and resources.

  1. Virtual devices for all shapes and sizes

AVD Manager and emulator screenshot

Android Studio comes pre-configured with an optimized emulator image. The updated and streamlined Virtual Device Manager provides pre-defined device profiles for common Android devices.

  1. Android builds evolved, with Gradle

Gradle build system screenshot

Create multiple APKs for your Android app with different features using the same project. Manage app dependencies with Maven. Build APKs from Android Studio or the command line.

More About the Studio

  • Built on IntelliJ IDEA Community Edition, the popular Java IDE by JetBrains.
  • Flexible Gradle-based build system.
  • Build variants and multiple APK generation.
  • Expanded template support for Google Services and various device types.
  • Rich layout editor with support for theme editing.
  • Lint tools to catch performance, usability, version compatibility, and other problems.
  • ProGuard and app-signing capabilities.
  • Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine.

System Requirements

Windows

  • Microsoft® Windows® 8/7/Vista (32 or 64-bit)
  • 2 GB RAM minimum, 4 GB RAM recommended
  • 400 MB hard disk space
  • At least 1 GB for Android SDK, emulator system images, and caches
  • 1280 x 800 minimum screen resolution
  • Java Development Kit (JDK) 7
  • Optional for accelerated emulator: Intel® processor with support for Intel® VT-x, Intel® EM64T (Intel® 64), and Execute Disable (XD) Bit functionality

Mac OS X

  • Mac® OS X® 10.8.5 or higher, up to 10.9 (Mavericks)
  • 2 GB RAM minimum, 4 GB RAM recommended
  • 400 MB hard disk space
  • At least 1 GB for Android SDK, emulator system images, and caches
  • 1280 x 800 minimum screen resolution
  • Java Runtime Environment (JRE) 6
  • Java Development Kit (JDK) 7
  • Optional for accelerated emulator: Intel® processor with support for Intel® VT-x, Intel® EM64T (Intel® 64), and Execute Disable (XD) Bit functionality

On Mac OS, run Android Studio with Java Runtime Environment (JRE) 6 for optimized font rendering. You can then configure your project to use Java Development Kit (JDK) 6 or JDK 7.

Linux

  • GNOME or KDE desktop
  • GNU C Library (glibc) 2.15 or later
  • 2 GB RAM minimum, 4 GB RAM recommended
  • 400 MB hard disk space
  • At least 1 GB for Android SDK, emulator system images, and caches
  • 1280 x 800 minimum screen resolution
  • Oracle® Java Development Kit (JDK) 7

Installing Android Studio

Android Studio provides everything you need to start developing apps for Android, including the Android Studio IDE and the Android SDK tools. If you didn't download Android Studio, go download Android Studio now, or switch to the stand-alone SDK Tools install.

Before you set up Android Studio, be sure you have installed JDK 6 or higher (the JRE alone is not sufficient)—JDK 7 is required when developing for Android 5.0 and higher. To check if you have JDK installed (and which version), open a terminal and type:

javac -version

If the JDK is not available or the version is lower than version 6, download the Java SE Development Kit 7: http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html

General notes before setup

  • Android Studio provides the IDE and manages SDK packages. Individual tools and other SDK packages are saved outside the Android Studio application directory (for example, \Users\\sdk\ on Windows or /Users//Library/Android/sdk/ on macOS).
  • If your launcher script does not find Java on Windows, set the JAVAHOME environment variable to point to your JDK installation (for example C:\Program Files\Java\jdk1.7.021).

To set up Android Studio on Windows:

  1. Launch the .exe file you just downloaded.
  2. Follow the setup wizard to install Android Studio and any necessary SDK tools. I have installed it on Windows 10. Here are the steps as below:

Android Studio installer step

Once you launched Android Studio, it's time to mention JDK path in android studio installer.

JDK path dialog

Below the image initiating JDK to android SDK:

JDK setup screenshot

On some Windows systems, the launcher script does not find where Java is installed. If you encounter this problem, you need to set an environment variable indicating the correct location.

Select Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and add a new system variable JAVAHOME that points to your JDK folder, for example C:\Program Files\Java\jdk1.7.021.

The individual tools and other SDK packages are saved outside the Android Studio application directory. If you need to access the tools directly, use a terminal to navigate to the location where they are installed. For example:

\Users\<user>\sdk\

Need to check the components, which are required to create applications; below the image has selected Android Studio, Android SDK, Android Virtual Machine and performance (Intel chip).

Component selection

Need to specify the location of local machine path for Android studio and Android SDK, below the image has taken default location.

Paths selection

Specify the RAM for Android emulator (by default it takes 512MB of local machine RAM).

Emulator RAM selection

At final stage, it would extract SDK packages into our local machine; it would take a while to finish the task.

SDK extraction progress

After done all above steps perfectly, you must get finish button and it gonna be open android studio project with Welcome to android studio message as shown below:

Welcome to Android Studio

You can start your application development by calling start a new android studio project. In a new installation frame it will ask Application name, package information and location of the project.

To set up Android Studio on Mac OSX:

  1. Launch the .dmg file you just downloaded.
  2. Drag and drop Android Studio into the Applications folder.
  3. Open Android Studio and follow the setup wizard to install any necessary SDK tools.

If you need to use the Android SDK tools from a command line, you can access them at:

/Users/<user>/Library/Android/sdk/

To set up Android Studio on Linux:

  1. Unpack the downloaded ZIP file into an appropriate location for your applications.
  2. To launch Android Studio, navigate to the android-studio/bin/ directory in a terminal and execute studio.sh.

You may want to add android-studio/bin/ to your PATH environmental variable so that you can start Android Studio from any directory.

  1. If the SDK is not already installed, follow the setup wizard to install the SDK and any necessary SDK tools.

Note: You may also need to install the ia32-libs, lib32ncurses5-dev, and lib32stdc++6 packages. These packages are required to support 32-bit apps on a 64-bit machine.

Troubleshooting and notes

  • If the launcher script does not find Java on Windows: set the system-level JAVA_HOME environment variable pointing to your JDK.
  • Emulator acceleration: to get best performance install Intel HAXM on Intel machines or use the platform hypervisor supported by your OS. (Follow official docs for current steps.)
  • SDK path: the SDK is installed outside Android Studio; note the path when you accept defaults.

Reference

Reference: developer.android.com