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: