Archives 2023

Razorpay payment gateway custom checkout

Sample codes to help you integrate the payment methods of your choice on Razorpay Checkout.

If you want to list all the payment methods offered by Axis bank, allow card payments for ICICI bank only and hide upi payment method from the Checkout, you can do so as follows:

<html>
<button id="rzp-button1" class="btn btn-outline-dark btn-lg"><i class="fas fa-money-bill"></i> Own Checkout</button>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
  var options = {
    "key": "[YOUR_KEY_ID]", // Enter the Key ID generated from the Dashboard
    "amount": "1000",
    "currency": "INR",
    "description": "Acme Corp",
    "image": "https://s3.amazonaws.com/rzp-mobile/images/rzp.jpg",
    "prefill":
    {
      "email": "gaurav.kumar@example.com",
      "contact": +919900000000,
    },
    config: {
      display: {
        blocks: {
          utib: { //name for Axis block
            name: "Pay using Axis Bank",
            instruments: [
              {
                method: "card",
                issuers: ["UTIB"]
              },
              {
                method: "netbanking",
                banks: ["UTIB"]
              },
            ]
          },
          other: { //  name for other block
            name: "Other Payment modes",
            instruments: [
              {
                method: "card",
                issuers: ["ICIC"]
              },
              {
                method: 'netbanking',
              }
            ]
          }
        },
        hide: [
          {
          method: "upi"
          }
        ],
        sequence: ["block.utib", "block.other"],
        preferences: {
          show_default_blocks: false // Should Checkout show its default blocks?
        }
      }
    },
    "handler": function (response) {
      alert(response.razorpay_payment_id);
    },
    "modal": {
      "ondismiss": function () {
        if (confirm("Are you sure, you want to close the form?")) {
          txt = "You pressed OK!";
          console.log("Checkout form closed by the user");
        } else {
          txt = "You pressed Cancel!";
          console.log("Complete the Payment")
        }
      }
    }
  };
  var rzp1 = new Razorpay(options);
  document.getElementById('rzp-button1').onclick = function (e) {
    rzp1.open();
    e.preventDefault();
  }
</script>
</html>

Show Ola Money Separately on Checkout

Use the code given below to show Ola Money separately on Checkout:

config: {
    display: {
      blocks: {
        banks: {
          name: 'Methods with Offers',
          instruments: [
            {
              method: 'wallet',
              wallets: ['olamoney']
            }]
        },
      },
      sequence: ['block.banks'],
      preferences: {
        show_default_blocks: true,
      },
    },
  },
};

Show Freecharge Separately on Checkout

Use the code given below to show Freecharge separately on Checkout:

config: {
    display: {
      blocks: {
        banks: {
          name: 'Methods with Offers',
          instruments: [
            {
              method: 'wallet',
              wallets: ['freecharge']
            }]
        },
      },
      sequence: ['block.banks'],
      preferences: {
        show_default_blocks: true,
      },
    },
  },
};

Show Most Used Methods

Use the code given below to show methods with offers:

config: {
    display: {
      blocks: {
        banks: {
          name: 'Most Used Methods',
          instruments: [
            {
              method: 'wallet',
              wallets: ['freecharge']
            },
            {
                method: 'upi'
            },
            ],
        },
      },
      sequence: ['block.banks'],
      preferences: {
        show_default_blocks: true,
      },
    },
  },
};

Show Instruments of a Certain Bank Only

Use the code given below to show the instruments of a certain bank only on Checkout:

config: {
    display: {
      blocks: {
        banks: {
          name: 'Pay using Axis bank',
          instruments: [
            {
              method: 'netbanking',
              banks: ['UTIB'],
            },
            {
              method: 'card',
              issuers: ['UTIB'],
            },
            {
                method: 'wallet',
                wallets:['payzapp']
            }
          ],
        },
      },
      sequence: ['block.banks'],
      preferences: {
        show_default_blocks: false,
      },
    },
  },
};

Highlight Instruments of a Certain Bank

Use the code given below to highlight the instruments of a certain bank only on Checkout:

config: {
    display: {
      blocks: {
        banks: {
          name: 'Pay using Axis banks',
          instruments: [
            {
              method: 'netbanking',
              banks: ['UTIB'],
            },
            {
              method: 'card',
              issuers: ['UTIB'],
            },
            {
                method: 'wallet',
                wallets:['payzapp']
            }
          ],
        },
      },
      sequence: ['block.banks'],
      preferences: {
        show_default_blocks: true,
      },
    },
  },
};

Reorder Payment Methods

Use the code given below to reorder payment methods on Checkout:

config: {
    display: {
      blocks: {
        banks: {
          name: 'All payment methods',
          instruments: [
            {
              method: 'upi'
            },
            {
              method: 'card'
            },
            {
                method: 'wallet'
            },
            {
                method: 'netbanking'
            }
          ],
        },
      },
      sequence: ['block.banks'],
      preferences: {
        show_default_blocks: false,
      },
    },
  },
};

Remove a Method from Checkout

Use the code given below to remove a method from Checkout:

config: {
    display: {
      hide: [
        {
          method: 'upi'
        }
      ],
      preferences: {
        show_default_blocks: true,
      },
    },
  },
};

Show Only a Certain Payment Method on Checkout

Use the code given below to show only a certain payment method on Checkout:

config: {
    display: {
      blocks: {
        banks: {
          name: 'Pay via UPI',
          instruments: [
            {
              method: 'upi'
            }
          ],
        },
      },
      sequence: ['block.banks'],
      preferences: {
        show_default_blocks: false,
      },
    },
  },
};

Card

config: {
    display: {
      blocks: {
        banks: {
          name: 'Pay via Card',
          instruments: [
            {
              method: 'card'
            }
          ],
        },
      },
      sequence: ['block.banks'],
      preferences: {
        show_default_blocks: false,
      },
    },
  },
};

Paytm Payment Gateway Integration in PHP

In this tutorial, we have explained Paytm Payment Gateway Integration in PHP programming language. In today scenario Paytm is the most popular and trusted mobile wallet system. As per the Economic time’s survey Paytm reached approx 200 million registered users. Yes, that is a huge number.

After demonetization in India, Paytm become more popular. Now, most of the users pay Bills and transfer money via the Paytm service. It’s very easy to use and of course very fast.

Today many eCommerce or other service websites start using Paytm payment gateway. Its also reduce the risk to exposing credit card details or banking password. Just send or receive payment via your Mobile Phone. So, no doubt Paytm is a better service for online payment for your Website or Mobile App.

Steps to Integrate Paytm Payment Gateway in PHP

Let’s start the process of Paytm Payment Gateway Integration. It’s very easy to integrate in your application as compared to other payment gateways. Follow the below steps:

Step 1 : Register for Paytm Account

Sign Up for a Paytm business account from here: https://paytm.com/business/payments/online

During Sign up process, you need to choose the option that Paytm Payment Gateway requires for a Website or APP. Also submit a valid Redirect URL, where you want to redirect the user after successful payment received.

In the registration process, they ask for some official information like Business Types, addresses, Verification proof, Bank Details, etc. Although you can get Paytm sandbox credential without complete this process. But for production, you have to provide all required information.

After this, you will get Paytm Staging Credentials, which included Staging MID, Merchant Key, Industry Type, Website Name, and Channel ID. Paytm also send testing wallet details, which you can use for test transaction flow.

Note: All users must use Paytm with only an Indian registered number because the company hasn’t gone overseas except for Canada.

Step 2 : Download Official Paytm PHP Kit

Paytm official announced library source code in all languages. Just download Paytm Payment Gateway kit in PHP from GitHub. Extract the Zip file, there is the ‘PaytmKit’ folder which has all required files.

Step 3: Configure Paytm Credential

Open ‘config_paytm.php’ file in PaytmKit -> lib folder and update with the access credential you got from Paytm.

define('PAYTM_ENVIRONMENT', 'TEST'); // change value PROD for production
define('PAYTM_MERCHANT_KEY', 'vsbi51****uKL0#3 ');
define('PAYTM_MERCHANT_MID', 'codefi*****858443');
define('PAYTM_MERCHANT_WEBSITE', 'WEBS***ING');

By default source code ready for staging site. When you want to move to Production update the ‘PAYTM_ENVIRONMENT’ value by ‘PROD’.

Step 4: Create HTML Payment Form

After configuring the credential, your code is ready to process. Now create an HTML form to make the online transactions.

Form action should be to this file ‘pgRedirect.php’ inside PaytmKit folder. This file handle checksum and other require details and redirect to you Paytm payment page. After click on checkout button user can process the payment via the paytm wallet.

<!doctype html>
<html>
<head>
<title>Patym Payment Gateway Integration in PHP</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container" style="padding-top:100px;">
    <div class="col-xs-6 col-xs-offset-3">
        <div class="panel panel-default">
            <div style="background-color: #000000; color:#fff" class="panel-heading">
                <h3 class="text-center">Paytm Payment Gateway Demo</h3>
            </div>
            <div class="panel-body">
            <form action="pgRedirect.php" method="post">
				<input type="hidden" id="CUST_ID" name="CUST_ID" value="CUST001">
					<input type="hidden" id="INDUSTRY_TYPE_ID" name="INDUSTRY_TYPE_ID" value="Retail">
					<input type="hidden"  id="CHANNEL_ID" name="CHANNEL_ID" value="WEB">
                <div class="form-group">
					
					<label>Order ID:</label>
                    <input type="text" class="form-control" id="ORDER_ID" name="ORDER_ID" size="20" maxlength="20" autocomplete="off" 

tabindex="1" value="<?php echo  "ORDER" . rand(10000,99999999)?>">
                </div>
               
                <div class="form-group">
					<label>Amount to Pay:</label>
                    <input type="text" class="form-control" id="TXN_AMOUNT" name="TXN_AMOUNT" autocomplete="off" tabindex="5" 

value="20">
                </div>
                <div class="form-group">
                    <input type="submit" name="submit" value="CheckOut" class="btn btn-success btn-lg" style="background-

color:#0000FF; margin-left: 37%;">
                </div>
            </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>

In this form we are sending some required parameter as hidden variable like Channel ID, Industry Type and Customer ID. You have to pass these parameters along with form submit.

Razorpay payment gateway integration in PHP

create a folder inside the root directory of your local server.

create a file (index.php) inside that folder along with some inputs such as payee name, amount, and item description as shown below

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Razorpay</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
 
<div class="container mt-3" style="width: 50%;">
  <h2>Razorpay Payment Integration in PHP</h2>
  <form action="#">
    <div class="mb-3 mt-3">
      <label for="email">Payee Name:</label>
      <input type="email" class="form-control" id="name" placeholder="Enter Payee Name" name="payee_name">
    </div>
    <div class="mb-3">
      <label for="pwd">Amount:</label>
      <input type="number" class="form-control" id="amount" placeholder="Enter Amount" name="amount">
    </div>
    <div class="mb-3">
      <label for="pwd">Item Description:</label>
      <input type="text" class="form-control" id="description" placeholder="Enter Description" name="description">
    </div>
    <button type="button" class="btn btn-primary" id="rzp-button1" onclick="pay_now()">Pay</button>
  </form>
</div>
</body>
</html>

Paste the javascript code inside the index.php file as shown below

<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script type="text/javascript">
    function pay_now(){
          //get the input from the form
          var name = $("#payee_name").val();
          var amount = $("#amount").val();
          var actual_amount = amount*100;
          var description = $('#description').val();
          //var actual_amount = amount;
          var options = {
            "key": "rzp_test_xx28KfXBaypeQW", // Enter the Key ID generated from the Dashboard
            "amount": actual_amount, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
            "currency": "INR",
            "name": name,
            "description": description,
            "image": "razorpay.png",
            //"order_id": "order_IluGWxBm9U8zJ8", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
            "handler": function (response){
                console.log(response);
                $.ajax({
 
                    url: 'process_payment.php',
                    'type': 'POST',
                    'data': {'payment_id':response.razorpay_payment_id,'amount':actual_amount,'name':name},
                    success:function(data){
                        console.log(data);
                      window.location.href = 'thank_you.php';
                    }
 
                });
                // alert(response.razorpay_payment_id);
                // alert(response.razorpay_order_id);
                // alert(response.razorpay_signature)
            },
             
        };
        var rzp1 = new Razorpay(options);
        rzp1.on('payment.failed', function (response){
                alert(response.error.code);
                alert(response.error.description);
                alert(response.error.source);
                alert(response.error.step);
                alert(response.error.reason);
                alert(response.error.metadata.order_id);
                alert(response.error.metadata.payment_id);
        });
        document.getElementById('rzp-button1').onclick = function(e){
            rzp1.open();
            e.preventDefault();
        }
    }
</script>

Establish the database connection in PHP so that you can insert the data with the Razorpay payment id.

Create a table in your database as shown below

DDL information of the table

CREATE TABLE razorpay_payment (
id int(10) NOT NULL AUTO_INCREMENT,
name varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
amount int(10) NOT NULL,
payment_status varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
payment_id varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
paid_on datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Create a file process_payment.php to submit the payment details inside the database after successful payment.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Razorpay</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
 
<div class="container mt-3" style="width: 50%;">
  <h2>Razorpay Payment Integration in PHP</h2>
  <form action="#">
    <div class="mb-3 mt-3">
      <label for="email">Payee Name:</label>
      <input type="email" class="form-control" id="name" placeholder="Enter Payee Name" name="payee_name">
    </div>
    <div class="mb-3">
      <label for="pwd">Amount:</label>
      <input type="number" class="form-control" id="amount" placeholder="Enter Amount" name="amount">
    </div>
    <div class="mb-3">
      <label for="pwd">Item Description:</label>
      <input type="text" class="form-control" id="description" placeholder="Enter Description" name="description">
    </div>
    <button type="button" class="btn btn-primary" id="rzp-button1" onclick="pay_now()">Pay</button>
  </form>
</div>
 
</body>
</html>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script type="text/javascript">
    function pay_now(){
          //get the input from the form
          var name = $("#payee_name").val();
          var amount = $("#amount").val();
          var actual_amount = amount*100;
          var description = $('#description').val();
          //var actual_amount = amount;
          var options = {
            "key": "rzp_test_xx28KfXBaypeQW", // Enter the Key ID generated from the Dashboard
            "amount": actual_amount, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
            "currency": "INR",
            "name": name,
            "description": description,
            "image": "razorpay.png",
            //"order_id": "order_IluGWxBm9U8zJ8", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
            "handler": function (response){
                console.log(response);
                $.ajax({
 
                    url: 'process_payment.php',
                    'type': 'POST',
                    'data': {'payment_id':response.razorpay_payment_id,'amount':actual_amount,'name':name},
                    success:function(data){
                        console.log(data);
                      window.location.href = 'thank_you.php';
                    }
 
                });
                // alert(response.razorpay_payment_id);
                // alert(response.razorpay_order_id);
                // alert(response.razorpay_signature)
            },
             
        };
        var rzp1 = new Razorpay(options);
        rzp1.on('payment.failed', function (response){
                alert(response.error.code);
                alert(response.error.description);
                alert(response.error.source);
                alert(response.error.step);
                alert(response.error.reason);
                alert(response.error.metadata.order_id);
                alert(response.error.metadata.payment_id);
        });
        document.getElementById('rzp-button1').onclick = function(e){
            rzp1.open();
            e.preventDefault();
        }
    }
</script>

Explanation of the above code:-

  • As soon as the form is submitted, we will get the input values using jquery and pass them to the options variable along with the key ID generated from the Razorpay dashboard.
  • When you pass the input values using jquery then do not forget to multiply the amount by 100 because the currency is INR which means you are putting the amount as paisa which is why you need to multiply by 100.
  • Now, you will see a Razorpay interface after giving the phone number and email as shown below. Here you can view various options for payments.

Now, inside the handler function, if you console the response then you will see the response values as shown below. Note that when you console then comment on the ajax request otherwise you can not see the response on the console.

Now we will use the razorpay_payment_id shown on the console and send it with the amount and payee name in the ajax request to the URL: process_payment.php.

Now, in the process_payment.php file, include your database connection file (dbconnect.php) as shown below

<?php
$servername='localhost';
$username="root";
$password="";
try
{
    $con=new PDO("mysql:host=$servername;dbname=myproject_db",$username,$password);
    $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    //echo 'connected';
}
catch(PDOException $e)
{
    echo '<br>'.$e->getMessage();
}
?>

Now, inside the process_payment.php, get the razorpay_payment_id and other data sent from the ajax request and save them in the MySQL database as shown below

<?php
//connect the database
include 'dbconnect.php';
 
//get the payment details from payment page
 
if(isset($_POST['payment_id']) && isset($_POST['amount']) && isset($_POST['name']))
{
    $paymentId = $_POST['payment_id'];
    $amount = $_POST['amount'];
    $name = $_POST['name'];
 
    //insert data into database
    $sql="INSERT INTO razorpay_payment(name,amount,payment_status,payment_id)VALUES('$name','$amount','paid','$paymentId')";
    $stmt=$con->prepare($sql);
    $stmt->execute();
}
?>

Now, inside the success function, you can redirect to a thank you page after successful payment as shown below.

window.location.href = 'thank_you.php';

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
 
<div class="container mt-3">
  <div class="alert alert-success alert-dismissible">
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    <strong>Success!</strong> Payment Paid Successfully.
  </div>
</div>
 
</body>
</html>
HTML meta Tag

HTML <meta> Tag

The <meta> tag in HTML is used to provide metadata or additional information about an HTML document. It is placed within the <head> section of an HTML document and does not require a closing tag.

Here’s an example of how the <meta> tag can be used:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="This is a sample webpage.">
  <meta name="keywords" content="HTML, metadata, example">
  <title>Example Page</title>
</head>
<body>
  <!-- Page content goes here -->
</body>
</html>

In the example above, several <meta> tags are used to provide different types of metadata:

  • The charset attribute specifies the character encoding for the document. In this case, it is set to UTF-8, which is a widely used character encoding for handling various languages.
  • The viewport attribute sets the viewport properties for responsive web design. The example above sets the width to the device width and scales the content to fit the device.
  • The description attribute provides a brief description of the webpage’s content. This description may be used by search engines or other applications that process the webpage.
  • The keywords attribute specifies a comma-separated list of keywords relevant to the webpage’s content. These keywords can help search engines understand the page’s topic or content.

There are various other attributes and values that can be used with the <meta> tag to provide different types of metadata. Some examples include setting the author, specifying the document’s language, indicating the expiration date, and more. The choice of which metadata to include depends on the specific requirements and purpose of the webpage.

Table contains:

Example

Describe metadata within an HTML document:

<head>
  <meta charset="UTF-8">
  <meta name="description" content="Free Web tutorials">
  <meta name="keywords" content="HTML, CSS, JavaScript">
  <meta name="author" content="John Doe">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

Definition and Usage

The <meta> tag defines metadata about an HTML document. Metadata is data (information) about data.

<meta> tags always go inside the <head> element, and are typically used to specify character set, page description, keywords, author of the document, and viewport settings.

Metadata will not be displayed on the page, but is machine parsable.

Metadata is used by browsers (how to display content or reload page), search engines (keywords), and other web services.

There is a method to let web designers take control over the viewport (the user’s visible area of a web page), through the <meta> tag (See “Setting The Viewport” example below).

More Examples

Define keywords for search engines:

<meta name="keywords" content="HTML, CSS, JavaScript">

Define a description of your web page:

<meta name="description" content="HTML and CSS">

Define the author of a page:

<meta name="author" content="Mahabul Alam">

Refresh document every 30 seconds:

<meta http-equiv="refresh" content="30">

Setting the viewport to make your website look good on all devices:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Setting the Viewport

The viewport is the user’s visible area of a web page. It varies with the device – it will be smaller on a mobile phone than on a computer screen.

You should include the following <meta> element in all your web pages:

<meta name="viewport" content="width=device-width, initial-scale=1.0">
HTML header Tag

HTML header Tag defines a head section of the web page or head section of another section of the web page. HTML header tag is semantic part of HTML5. HTML header tag usually contain introductory part.

Syntax of HTML header Tag

The Syntax of HTML header Tag is shown below, It has both starting and ending tags.

<header>
</header>

Usage of HTML header Tag

HTML header Tag is used in HTML5 to specify the opening section. HTML header section mostly contain the headings, logo, navigation menu, slider, banner, video etc.

One web page can contain more than one HTML header tags, mostly header tag is the first section of a web page but you can use it later as well.

HTML header tag cannot be used inside footer tag, address tag or inside any other header tag.

HTML header tag is a block level element.

Example of HTML header Tag

Simple example of HTML header Tag is shown below.

<header>
  <nav>
  <ul>
    <li><a>Home</a></li>
    <li><a>About</a></li>
    <li><a>Contact Us</a></li>
  </ul>
  </nav>
  <h1>HowToCodeSchool.com</h1>
  <p>Learn HTML online!</p>
</header>

Contain Table:

The <header> tag in HTML is used to define a container for introductory content or a group of navigational links at the top of a document or a section. It represents the header section of a webpage or a specific section within the document.

Here’s an example of how to use the <header> tag in HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Example Page</title>
</head>
<body>
  <header>
    <h1>Welcome to Example Page</h1>
    <nav>
      <a href="#">Home</a>
      <a href="#">About</a>
      <a href="#">Contact</a>
    </nav>
  </header>
  
  <!-- Rest of the content -->
  
</body>
</html>

In the example above, the <header> tag is used to contain the introductory content of the webpage. It includes an <h1> heading element for the page title and a <nav> element for navigation links. The <header> tag is placed within the <body> section of the HTML document.

By using the <header> tag, you can semantically structure your webpage and separate the introductory content or navigation from the main content. It helps in organizing the different sections of your webpage and enhances accessibility and SEO (Search Engine Optimization).

Dropdown Menu in Navbar
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.navbar {
  overflow: hidden;
  background-color: #333;
  font-family: Arial, Helvetica, sans-serif;
}

.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  cursor: pointer;
  font-size: 16px;  
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navbar a:hover, .dropdown:hover .dropbtn, .dropbtn:focus {
  background-color: red;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
</style>
</head>
<body>

<div class="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <div class="dropdown">
  <button class="dropbtn" onclick="myFunction()">Dropdown
    <i class="fa fa-caret-down"></i>
  </button>
  <div class="dropdown-content" id="myDropdown">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
  </div> 
</div>

<h3>Dropdown Menu inside a Navigation Bar</h3>
<p>Click on the "Dropdown" link to see the dropdown menu.</p>

<script>
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn')) {
  var myDropdown = document.getElementById("myDropdown");
    if (myDropdown.classList.contains('show')) {
      myDropdown.classList.remove('show');
    }
  }
}
</script>
</body>
</html>

Example

Dropdown Menu inside a Navigation Bar

Click on the “Dropdown” link to see the dropdown menu.

To create a dropdown menu in a navbar using HTML, you can use the <ul> and <li> elements along with CSS for styling. Here’s an example:

<!DOCTYPE html>
<html>
<head>
  <style>
    /* CSS for the dropdown menu */
    .dropdown {
      position: relative;
      display: inline-block;
    }
    
    .dropdown-content {
      display: none;
      position: absolute;
      background-color: #f9f9f9;
      min-width: 160px;
      box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
      z-index: 1;
    }
    
    .dropdown:hover .dropdown-content {
      display: block;
    }
  </style>
</head>
<body>
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li class="dropdown">
        <a href="#">Services</a>
        <ul class="dropdown-content">
          <li><a href="#">Service 1</a></li>
          <li><a href="#">Service 2</a></li>
          <li><a href="#">Service 3</a></li>
        </ul>
      </li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</body>
</html>

In this example, the “Services” menu item has a dropdown menu with three sub-items: “Service 1,” “Service 2,” and “Service 3.” When the user hovers over the “Services” menu item, the dropdown menu appears.

The CSS part of the code defines the styles for the dropdown menu. The .dropdown class is applied to the parent <li> element of the dropdown menu, and the .dropdown-content class is applied to the <ul> element that contains the sub-items.

Feel free to customize the CSS styles as per your requirements to match your website’s design.

How to remove .html extension

All the pages on the website have a structure which is given by HTML. HTML provides the structure to content, text, tables, headings, and lists on the webpage that makes the page easy to read. While saving an HTML document it has an extension as .html. Therefore, the URL of the website have a .html extension. The .html extension can be easily removed by editing the .htaccess file.

.htaccess file: The .htaccess file is created with a Text Editor like Notepad. It is a simple ASCII file that lets the server know what configuration changes are to be made on a per-directory basis.

Note: The .htaccess is the full name of the file. It is not file.htaccess, it is simply .htaccess.

Removing .html Extension: To remove the .html extension from a URL. For example: 

example.com/latestpost.html

To

example.com/latestpost

You have to follow these steps: 

  • Log in to cPanel account.
  • In the Files section, click on the File Manager icon.
  • Click on the Settings Button in the top right corner.
  • If you want to make changes in the Primary Domain then Click on the radio button next to the Web Root. If changes are to be made on Other Domains, then Click the dropdown menu and find the domain in which changes are to be made.
  • Remember to check the checkbox next to Show Hidden Files. Now click the Save Button to return to the File Manager window.
  • Now you are in the Root Folder of the domain which you have selected to make changes. Search for the .htaccess file and right-click on it. Click on the Edit option in the menu. You can now add code to the .htaccess file.
  • Add the following code inside the .htaccess file
#remove html file extension https://example.com/page.html
# to https://example.com/page
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC, L]
  • Click on the Save Changes Button and then on Close Button.

You can now link any page inside the HTML document without needing to add the extension of the page as no extension will be visible now in the URL of the website.

Example:  

<a href="http://example.com/image" title="image">image</a>

The search engine may index these pages as duplicate content, to overcome this add a <canonical> meta tag in the HTML file. 

Example:  

<link rel="canonical" href="https://example.com/blog/first-blog" />

To remove the “.html” extension from URLs, you can use URL rewriting techniques, specifically by configuring your web server to handle such requests.

Here’s an example using Apache’s mod_rewrite module, assuming you’re using an Apache web server:

  1. Enable mod_rewrite: Ensure that the mod_rewrite module is enabled on your server. You can typically do this by uncommenting the relevant line in the Apache configuration file (httpd.conf) or by using the appropriate command for your server setup.
  2. Create or modify the .htaccess file: In the root directory of your website or the directory where the HTML files reside, create or modify the .htaccess file.
  3. Add the rewrite rules: Add the following code to the .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [L]

These rules check if the requested URL (without the “.html” extension) matches an existing HTML file. If it does, the server internally maps the URL to the corresponding HTML file with the extension. However, the client sees and accesses the URL without the extension.

  1. Test the configuration: Save the .htaccess file and test the configuration by accessing a URL without the “.html” extension. For example, if your file is “about.html,” you should be able to access it as “https://www.example.com/about.”

Please note that the above instructions are specific to Apache web servers using mod_rewrite. If you’re using a different web server, such as Nginx or Microsoft IIS, the configuration steps may differ. Additionally, ensure that you have appropriate file permissions and consult your server’s documentation for specific instructions.

It’s also worth mentioning that removing file extensions from URLs can have implications for search engine optimization (SEO) and may require updating internal links and references within your website.

How to redirect HTTP to HTTPS

How to redirect HTTP to HTTPS Using .htaccess

Chrome and Firefox have started showing insecure warnings on sites without SSL certificates. Without SSL, your website will show insecure to the visitors. Therefore, using an SSL-encrypted connection for safety, accessibility or PCI compliance reasons is necessary. It becomes very important to redirect from HTTP to HTTPS.

What is SSL?

SSL stands for Secure Sockets Layer. It was one of the early protocols developed for secure communication over the internet. SSL provides a secure and encrypted connection between a client and a server, ensuring that data transmitted between them remains confidential and cannot be intercepted or tampered with by unauthorized parties.

SSL uses a combination of cryptographic algorithms to establish an encrypted connection. When a client (such as a web browser) initiates a connection with a server that supports SSL, they go through a process called the SSL handshake. During the handshake, the client and server exchange information and negotiate the encryption parameters for the session.

Once the SSL handshake is complete, a secure connection is established, and data exchanged between the client and server is encrypted using symmetric encryption. This means that even if someone manages to intercept the data, they cannot understand its contents without the encryption key.

SSL has been widely used for securing sensitive information, such as credit card details, login credentials, and personal information, transmitted over the internet. However, it has been succeeded by the newer Transport Layer Security (TLS) protocol, which is an enhanced version of SSL. TLS is backward-compatible with SSL, and the terms “SSL” and “TLS” are often used interchangeably in practice.

It’s worth noting that SSL/TLS is primarily used for securing the connection between a client (e.g., a web browser) and a server. It does not guarantee the security of the server or the application running on it. Additional security measures and best practices need to be implemented to ensure the overall security of the server and the data it holds.

Why SSL is Critical?

SSL (Secure Sockets Layer) or its successor TLS (Transport Layer Security) is critical for several reasons:

  1. Confidentiality: SSL ensures the confidentiality of data transmitted over the internet. By encrypting the communication between a client and a server, SSL prevents unauthorized parties from intercepting and understanding the content of the data. This is crucial when transmitting sensitive information such as credit card details, login credentials, or personal data.
  2. Data Integrity: SSL provides data integrity, ensuring that the information exchanged between the client and server remains intact and unaltered during transmission. Through the use of cryptographic algorithms, SSL verifies that the data received at the destination is the same as the data sent by the source. This helps to prevent data tampering or modification by malicious entities.
  3. Authentication: SSL supports server authentication, which allows clients to verify the identity of the server they are communicating with. When a server presents an SSL certificate signed by a trusted certificate authority (CA), the client can be confident that they are connecting to the legitimate server and not an impostor. This helps prevent man-in-the-middle attacks where an attacker intercepts the communication and poses as the server.
  4. Trust and Confidence: SSL helps establish trust and confidence between users and websites or online services. When users see the padlock icon or the “https://” prefix in their browser’s address bar, it indicates that the connection is secured with SSL/TLS. This visual indicator reassures users that their interactions are protected, which is particularly important for e-commerce websites, online banking, or any site that deals with sensitive information.
  5. Regulatory Compliance: SSL/TLS is often a requirement for compliance with various industry standards and regulations. For example, the Payment Card Industry Data Security Standard (PCI DSS) mandates the use of SSL/TLS to protect credit card data during transmission. Compliance with such standards is crucial for businesses that handle sensitive customer information to avoid penalties and maintain customer trust.

Overall, SSL is critical because it provides encryption, data integrity, authentication, and establishes trust in online communications. By implementing SSL/TLS, organizations can enhance the security of their online services and protect sensitive data, fostering a safer environment for users.

In order to force your web traffic to use HTTPS, edit the codes in the .htaccess file.

Before we move onto redirecting HTTP to HTTPS, here’s how you can edit .htaccess file. If you already know skip to Redirection steps.

Editing .htaccess File

There are instructions/directives in the .htaccess file that tell the server how to act in certain scenarios and directly affects how your website functions. Common directives in .htaccess file:

  • Redirects
  • Rewriting URLs

Ways to edit an .htaccess file:

  • Edit the file on your computer and upload it to the server using FTP.
  • Use “Edit” mode in FTP program that allows you to edit a file remotely.
  • Use a text editor and SSH to edit the file.
  • Use the File Manager in cPanel to edit the file.

Editing .htaccess in cPanel File Manager

  • Login to cPanel
  • Files > File Manager > Document Root for:
  • Now select the domain name you want to access
  • Check “Show Hidden Files (dotfiles)”
  • Click “Go”
  • After a new tab or window opens, look for the .htaccess file.
  • Right click on the .htaccess file and click on “Code Edit” on the menu.
  • A dialogue box may pop up asking about encoding. Click “Edit” button to continue.
  • Edit the file
  • “Save Changes” when done.
  • Test your website to make sure it is done correctly. In case, there is an error, restore to the previous version and try again.
  • Once you are done, click “Close” to close the window.

Redirecting HTTP to HTTPS

  • Redirect All Web Traffic

If you have existing code in your .htaccess, add the following:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
  • Redirect Only a Specific Domain

For redirecting a specific domain to use HTTPS, add the following:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
  • Redirect Only a Specific Folder

Redirecting to HTTPS on a specific folder, add the following:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$ https://www.yourdomain.com/folder/$1 [R,L]

Note: Replace “yourdomain” with your actual domain name wherever required. Also, in case of the folder, replace /folder with the actual folder name.

HTTP to HTTPS redirect refers to the process of automatically redirecting a user’s request from an insecure HTTP connection to a secure HTTPS connection. This redirection is important for several reasons:

  1. Security: HTTPS utilizes SSL/TLS encryption to secure the communication between the client and the server. By redirecting from HTTP to HTTPS, you ensure that sensitive information, such as login credentials or financial data, is transmitted securely, reducing the risk of eavesdropping, tampering, or data interception.
  2. Data Integrity: HTTPS ensures the integrity of data during transmission. By redirecting to HTTPS, you prevent attackers from modifying the content of the communication, as SSL/TLS verifies the integrity of the data exchanged between the client and server.
  3. Trust and User Confidence: Users have come to associate HTTPS with secure and trustworthy websites. When a user sees the padlock icon and “https://” in the browser’s address bar, it instills confidence that their connection is encrypted and their data is protected. By redirecting to HTTPS, you provide a positive user experience and build trust with your visitors.

To implement an HTTP to HTTPS redirect, you typically need to configure your web server or website to automatically redirect incoming HTTP requests to the corresponding HTTPS URL. This can usually be achieved through server-side configurations or using code directives.

For example, if you’re using the Apache HTTP Server, you can add the following code to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This code checks if the incoming request is not using HTTPS and redirects it to the HTTPS version of the URL.

Similarly, other web servers like Nginx or IIS have their own configuration mechanisms for performing the redirect.

It’s important to note that implementing the redirect requires an SSL/TLS certificate to be installed on the server to enable HTTPS. Without a valid certificate, the redirect will not work, and users may encounter warnings or errors when attempting to access your website.

Think it was helpful? Share this article to help others come on HTTPS.

Diwali Dhamaka Offer


Coupon code: DIWALI2024 Discount: 7000/-
Coupon expiry date: 2024-11-05

This will close in 20 seconds

X