Show or hide input field password – HTML and Javascript

In this blog post, we will discuss, how you can show or hide an input field for password using plain HTML and Javascript. This is useful because sometimes users wants to see what password they are setting. This feature is very helpful in:

  • Signup, because user will be entering his password for the first time.
  • Reset, because user wants to know what new password he is setting-up.

No library has been used in this tutorial.

First, we will create an input field for password.

<!-- input field for password -->
<input type="password" id="password" />

Then, we will create a button that will show or hide the password.

<!-- button to toggle show/hide -->
<button type="button" onclick="togglePassword()">Show/hide</button>

Finally, we will create a Javascript function that will change the type of password input field.

// function to toggle password
function togglePassword() {

    // get password input field
    const password = document.getElementById("password")

    // change input type to password if currently is text, and change to text if currently is password
    password.type = (password.type == "password") ? "text" : "password"
}

This function will first get the DOM of input field for password. Then it will execute a ternary operator to check if the current type is “password”, meaning the password is hidden, then it will set it’s type to “text” and the password will be visible to the user.

And if currently the type is “text”, it means that user is currently viewing the password, then it will set it’s type to “password” and hence hide the password.

Complete source code:

<!-- input field for password -->
<input type="password" id="password" />

<!-- button to toggle show/hide -->
<button type="button" onclick="togglePassword()">Show/hide</button>

<script>
    // function to toggle password
    function togglePassword() {

        // get password input field
        const password = document.getElementById("password")

        // change input type to password if currently is text, and change to text if currently is password
        password.type = (password.type == "password") ? "text" : "password"
    }
</script>

Above code will create an input field and a button. By default, what you enter in the input field will not be visible to you. But once you press the button, the password will be visible. And on again pressing the button, it will be hidden. That’s how you can show or hide an input field for password using simple HTML and Javascript.

Redirect to previous page – Javascript

Let’s say you have a webpage where you want to show an anchor link to the user that will redirect the user to his previous page. So we will first create an anchor link to the first page.

<!-- create an anchor tag to page 2 and attach an onclick event listener to it -->
<a href="page2.php" onclick="gotoPage()">Page 2</a>

When it is clicked, we will call a Javascript function instead of directly redirecting to new page.

function gotoPage() {
    // prevent the page from redirecting
    event.preventDefault()

    // get current page location and save it in local storage
    localStorage.setItem("referrer", window.location.href)

    // redirect to the href attribute
    window.location.href = event.target.getAttribute("href") || ""
}

This function will first prevent the page from redirecting to anchor href attribute. Then it will get the current page URL, along with all its query parameters, and save it in local storage. Finally, it will get the anchor tag’s href attribute and redirect the user to it.

In order to redirect the user back to previous page, we need to create a file named “page2.php” and create another anchor link in it. By default, the anchor link will be hidden. It will only be visible if local storage has some referrer value.

<!-- create back button, hidden by default -->
<a id="referrer" style="display: none;">Go back</a>

After that, we run a Javascript code that will get the local storage value and set in to that anchor tag.

// check if value exists in referrer local storage
const referrerValue = localStorage.getItem("referrer")
if (referrerValue) {
    // if yes, then set it to the href attribute of back button
    const referrerNode = document.getElementById("referrer")
    referrerNode.setAttribute("href", referrerValue)

    // and display the button
    referrerNode.style.display = ""
}

It will first get the referrer value from local storage. If there is any value, then it will get the back button node and referrer value. It will set the href attribute of back button to the referrer value. And finally, it will display the back button. If there is no referrer, then the back button will stay hidden.

Assign shirt number to new cricketer – PHP PDO MySQL

Suppose you have a database where data of all players of any sports team is stored. Every player has a name and a shirt number. We will create a program that will generate a new number for new player. We will make sure the new number is not already assigned to any player. We will keep generating new numbers until a unique number is found.

First, create a table “players” in your database by running the following SQL query.

CREATE TABLE IF NOT EXISTS players2 (
    id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    shirt_number INTEGER(11) NOT NULL
);

Then, create a file named “assign-shirt-number-to-new-player.php” and write the following code in it:

// connect with database
$pdo = new PDO("mysql:host=localhost; dbname=test;", "root", "", [
    PDO::ATTR_PERSISTENT => true
]);

This will make a persistent connection with the database. We are using PHP PDO because it has built-in support for SQL injection. After that, you need to fetch all the players already saved in the database.

// fetch all the players from the database
$statement = $pdo->prepare("SELECT * FROM players");
$statement->execute([]);
$rows = $statement->fetchAll(PDO::FETCH_OBJ);

Then we will set the range of numbers in which we want to generate a new number.

// set number of range for shirt numbers
$number_range = 10;

This will generate numbers between 0 and 10. After that, we will create a recursive function that will keep generating a new number unitl a unique shirt number is found.

// recursive function to return the new shirt number
function get_code()
{
    // define global variables to access them inside function
    global $rows, $number_range;

    // if all the numbers are taken, then return -1
    if (count($rows) >= $number_range)
        return -1;

    // generate a random number
    $code = rand(0, $number_range);

    // check if it already exists in the database
    foreach ($rows as $row)
    {
        if ($row->shirt_number == $code) // if number already exists, then start recursion i.e. generate another number
        return get_code();
    }

    // if number not already exists, then return it
    return $code;
}

We need to call this function once to start checking for new unique shirt number.

// initial call to recursive function
$code = get_code();

There is a possibility that all the numbers from 0 to 10 are already taken, in this case, we will display an error message.

// if all numbers are taken, display an error
if ($code == -1)
{
    echo "<p>All numbers are taken.</p>";
    exit;
}

If everything worked fine, we will have a new unique shirt number in our $code variable. We can simply insert it in our database.

// name of new player
$name = "Adnan";

// if shirt number not taken, then insert in database
$statement = $pdo->prepare("INSERT INTO players (name, shirt_number) VALUES (:name, :code)");
$statement->execute([
    ":name" => $name,
    ":code" => $code
]);

// display the new shirt number
echo "<p>New code: " . $code . "</p>";

Complete code

<?php

// connect with database
$pdo = new PDO("mysql:host=localhost; dbname=test;", "root", "root", [
    PDO::ATTR_PERSISTENT => true
]);

// fetch all the players from the database
$statement = $pdo->prepare("SELECT * FROM players");
$statement->execute([]);
$rows = $statement->fetchAll(PDO::FETCH_OBJ);

// set number of range for shirt numbers
$number_range = 10;

// recursive function to return the new shirt number
function get_code()
{
    // define global variables to access them inside function
    global $rows, $number_range;

    // if all the numbers are taken, then return -1
    if (count($rows) >= $number_range)
        return -1;

    // generate a random number
    $code = rand(0, $number_range);

    // check if it already exists in the database
    foreach ($rows as $row)
    {
        if ($row->shirt_number == $code) // if number already exists, then start recursion i.e. generate another number
        return get_code();
    }

    // if number not already exists, then return it
    return $code;
}

// initial call to recursive function
$code = get_code();

// if all numbers are taken, display an error
if ($code == -1)
{
    echo "<p>All numbers are taken.</p>";
    exit;
}

// name of new player
$name = "Adnan";

// if shirt number not taken, then insert in database
$statement = $pdo->prepare("INSERT INTO players (name, shirt_number) VALUES (:name, :code)");
$statement->execute([
    ":name" => $name,
    ":code" => $code
]);

// display the new shirt number
echo "<p>New code: " . $code . "</p>";

Check if URL is valid – PHP

In order to check if a URL is valid in PHP, we are going to use the cURL. You can get the complete reference on cURL from php.net. First, we are going to create a variable that will hold the value of URL that needs to be checked.

<?php

// URL to check
$url = "https://adnan-tech.com/";

Then, we are going to initialize the cURL.

// Initialize cURL
$curl = curl_init();

After that, we need to set the URL of cURL and make sure to return the response from server. For this, we will use cURL options.

// Set cURL options
curl_setopt_array($curl, [
    // Set URL
    CURLOPT_URL => $url,

    // Make sure to return the response
    CURLOPT_RETURNTRANSFER => 1
]);

Finally, we can execute this cURL request.

// Execute the CURL request
$response = curl_exec($curl);

Then, we will get the error from response (if there is any). If there is no error in response, it means that the URL is valid and the curl_error will return an empty string.

// Get error from CURL, it will be empty if there is no error.
$error = curl_error($curl);

We can put a condition on this variable to check if this variable has some value, it means there is an error in the request. In that case, we will display the error and stop the script. Otherwise, we will display a message that the URL is valid.

// If not empty, display the error and stop the script.
if ($error)
    die($error);

// Else, the URL is valid
echo "Valid";

Here is the complete code.

<?php

// URL to check
$url = "https://adnan-tech.com/";

// Initialize CURL
$curl = curl_init();

// Set CURL options
curl_setopt_array($curl, [
    // Set URL
    CURLOPT_URL => $url,

    // Make sure to return the response
    CURLOPT_RETURNTRANSFER => 1
]);

// Execute the CURL request
$response = curl_exec($curl);

// Get error from CURL, it will be empty if there is no error.
$error = curl_error($curl);

// If not empty, display the error and stop the script.
if ($error)
    die($error);

// Else, the URL is valid
echo "Valid";

That’s how you can check if a URL is valid or not in PHP.

Sort custom post type by ID ascending – WordPress

Suppose you have custom post type in WordPress that you want to sort such that it displays the first created post on top. By default, WordPress sort the posts by ID in descending. That means that the latest uploaded post will be displayed on top, which is good in many cases. But there might be a scenario where you want the first post to be displayed first. In this post, we will teach you how to do it using our Social Network API custom post type.

First, you need to go to your WordPress admin panel and navigate to Appearance -> Theme File Editor. In that page, select your current theme and find it’s “index.php” file and open it. In this file, search for a code:

<?php if ( have_posts() ) : ?>

Inside this “if” condition, and before the while loop:

<?php while ( have_posts() ) : the_post(); ?>

Write the following code, make sure to replace “social-network-api” with your own custom post type where you want to apply this sort.

<?php if ( have_posts() ) : ?>
                        
    <?php
        $post_type = $_GET["post_type"] ?? "";
        if ($post_type == "social-network-api"):
            query_posts([
                "post_type" => $post_type,
                "posts_per_page" => 10,
                "orderby" => "ID",
                "order" => "ASC"
            ]);
        endif;
    ?>

    <?php while ( have_posts() ) : the_post(); ?>

    <?php endwhile; ?>

<?php endif; ?>

If you refresh the page now, you will see your first post be displayed first.

How to send money from remitly.com to NayaPay (Pakistan)

In order to send money from remitly.com to NayaPay (Pakistan), you need to follow the following steps.

Step 1: Create an account

First, you need to create an account on remitly.com.

step_1-create-account-remitly.com
create-account-remitly.com

Step 2: Select country

After registration is done, you need to select country as “Pakistan” and click on “Send Money” button. You will also see the exchange rate you will get from your currency to PKR.

1-select-country-remitly.com
select-country-remitly.com

Step 3: Add recipient

On next screen, if you are sending the money for the first time to that recipient, you need to select “New Recipient”. Once you pay, your all recipients will be displayed here and you do not have to enter their information again.

2-new-recipient-remitly.com
new-recipient-remitly.com

Step 4: Enter amount

Enter the amount you want to send. You will see the exchange rate on this screen as well.

3-enter-amount-remitly.com
enter-amount-remitly.com

Step 5: Delivery method

Right now, Remitly provides 3 delivery methods. In order to send money to NayaPay account, you need to select “Mobile Money” as delivery method.

4-delivery-method-remitly.com
delivery-method-remitly.com

Step 6: NayaPay

After selecting delivery method as “Mobile Money”, you will see a list of all payment methods. In this list, you will find “NayaPay”. You can also perform a search if you do not find it.

5-nayapay-remitly.com
nayapay-remitly.com

Step 7: Recipient’s details

Next, you need to enter the recipient’s details. Typically, it is just the complete name and the account number of recipient. Recipient can see his account number from his NayaPay mobile app.

6-recipient-details-remitly.com
recipient-details-remitly.com

Step 8: Recipient’s phone

After that, you need to enter the recipient’s phone number.

7-recipient-phone-remitly.com
recipient-phone-remitly.com

Step 9: Recipient notification

If you want the recipient to receive an SMS notification from remitly.com, then you can press “Yes, please”.

8-recipient-notification-remitly.com
recipient-notification-remitly.com

Step 10: Enter sender details

Once the recipient’s details are done, then you need to enter your own details. This typically involves your complete name and date of birth. You also need to confirm these details on next screen.

9-sender-details-remitly.com
sender-details-remitly.com

Step 11: Confirm your information

Double-check your name and date of birth. If everything is right, then press “Confirm”.

10-confirm-information-remitly.com
confirm-information-remitly.com

Step 12: Sender’s address

Enter your address including street, city, state and zip code.

11-sender-address-remitly.com
sender-address-remitly.com

Step 13: Sender’s phone

You also need to enter your own phone number as well.

12-sender-phone-remitly.com
sender-phone-remitly.com

Step 14: Last step

If everything goes well, you will see a screen that says that your money is on its way. remitly.com will also provide you a tracking link that you can send to recipient so he can check the payment status as well.

step_5-money-on-way-remitly.com
money-on-way-remitly.com

How to generate random string in PHP

In this article, I will show you, how you can generate a random string in PHP. You can set the length of random string. Also, you can define all the possible characters you want in your random string.

In order to generate random string in PHP, we will first create a string of all the possible characters we want in our random string.

$str = "qwertyuiopasdfghjklzxcvbnm";

Then we are going to get the length of that string.

$str_length = strlen($str);

After that, we will create a variable that will hold the output value i.e. random string.

$output = "";

Loop through the number of characters you want in your random string.

$length = 6;

for ($a = 1; $a <= $length; $a++)
{
    // [section-1]
}

On the place of [section-1], we will get the random index from string of possible characters.

$random = rand(0, $str_length - 1);

And we will pick the random character from that string.

$ch = $str[$random];

Finally, we will append that character in our output string.

$output .= $ch;

If you echo $output; you will see a random string every time that code is executed. Here is the full code:

$str = "qwertyuiopasdfghjklzxcvbnm";
$str_length = strlen($str);
$output = "";
$length = 6;
for ($a = 1; $a <= $length; $a++)
{
    $random = rand(0, $str_length - 1);
    $ch = $str[$random];
    $output .= $ch;
}
echo $output;