Best Kali Linux Compatible Wireless Adapters/Dongles 2017

On 5/22/2017 Be the first to comment!

Here are the best kali linux compatible wireless adapters and usb dongles for 2017. Kali Linux is a Linux distribution mainly used for Penetration Testing, accessing N/W Security & Ethical Hacking. The process of choosing a wireless adapter or usb dongle to work with Kali Linux is not an easy task. It's just because the Operating system doesn't support all kinds of wifi adapters.

For example Pentesting requires a card to go into monitor mode and do packet injection which all cards can't do it. The Card's chipset and drivers is what determines if an adapter is compatible with kali or not.

Below I have listed out the most popular chipsets for Kali linux and Wireless adapters compatible with them. They work well for Penetration testing too.

Popular Kali Linux Compatible Chipsets:

  • Atheros AR9271
  • Ralink RT3070
  • Ralink RT3572

Best Kali Linux Compatible Wireless Adapters:

1. Alfa AWUS036NHA (Atheros AR9271 Chipset Compatible)

Check Price

Alfa-AWUS036NHA

Alfa AWUS036NHA is a best wifi adapter for pentesting. For wireless penetration testing, Atheros AR9271 is a good chipset and you can go for Alfa AWUS036NHA card if you plan to run Kali as VM. Just get the job done without hassle.

  • Compatible with any 802.11b, 802.11g or 802.11n routers using 2.4Ghz band
  • Supports multiple input multiple output
  • High speed transfer TX data rate of up to 150 mbps
  • Includes 4" detachable antenna of 5 dbi which can be upgraded up to 9 dbi.
  • Works with 64/128-bit wep, wpa, wpa2, tkip, aes security protocols.
  • Supports Windows 2000, XP 32/64, vista 32/64 & Windows 7 Platform. So compatible with Kali Linux running as VM on these hosts.

Get It Now From Amazon »

2. TP-Link TL-WN722N (AR9271 Chipset Compatible)

Check Price

best wifi card for kali linux

Another great wireless adapter for cheapest price. TP-Link TL-WN722N uses AR9271 Chipset and has great range of up to 150Mbps. The card is easy to set up and works perfectly with Kali Linux.

  • Supports Wireless speed of up to 150Mbps
  • Works both on Infrastructure and Ad-Hoc Mode
  • Includes a detachable 4dbi omni directional antenna
  • Supports WPS & USB 2.0
  • Compatible with Windows XP, Windows Vista, Windows 7, 8, 8.1 platforms

Get It Now From Amazon »

3. Alfa AWUSO36NH (RT3070 Chipset Compatible)

Check Price

best alfa wifi adapter for kali

One of the best compatible usb wireless adapter for kali linux. This 2 Watt 802.11n compatible Wifi adapter is quite powerful and supports Ralink RT3070 Chipset. The dongle has very good range and perfect for packet monitoring.

  • Compatible with any 2.4GHz routers of 802.11n, 802.11b/g/n wireless standards
  • Includes removable 4" - 5 dBi antenna and can be be upgraded up to 9dBi
  • Supports 64/128-bit WEP, WPA, WPA2, TKIP, AES Protocols
  • Compatible with Windows 2000, XP 32/64, Vista 32/64, Windows 7, Linux (2.4.x/2.6.x),and Mac (10.4.x/10.5.x)

Get It Now From Amazon »

4. Alfa AWUS036NEH (RT3070 Chipset)

Check Price

Alfa-AWUS036NEH

This is Wi-Fi Dongle is similar to Alfa AWUSO36NH in specs and covers long range. Alfa AWUS036NEH is exceptional for penetration testing and is good at packet injection and monitoring.

  • Works well with any 802.11b/g and 'N' routers
  • Includes removable 4" 5dBi antenna (upgradable up to 9dBi)
  • Supports packet injection & monitor mode
  • Protocols supported - 64/128-bit WEP, WPA, WPA2, TKIP, AES
  • Compatible with Windows 2000, 32/64 bit XP, Vista, Windows 7, Linux (2.4.x/2.6.x), Mac (10.4.x/10.5.x) Power PC& PC.

Get It Now From Amazon »

5. Panda PAU05 (RT3070 Chipset)

Check Price

Panda-PAU05

Panda 300mbps wireless n usb adapter is very reasonably priced and works with 802.11g/n standard and offers a data speed of up to 300 Mbps. It is exceptionally good considering the price but make sure to download and install the latest driver (alone) for Windows 7 and leave the rest of the setup to Windows itself.

  • Compatible with any 802.11g or 802.11n 2.4Ghz wireless routers
  • Wireless speed of up to 300Mbps
  • Works with both infrastructure and ad-hoc modes
  • Security protocol compliant: 64/128bit WEP, WPA, WPA2, 802.1x and 802.11i, Cisco CCS V1.0, 2.0 and 3.0
  • Supports 32/64-bit Windows 8/7/Vista, Mac OS 10.4/10.5/10.6/10.7/10.8/10.9 and latest version of 32/64-bit Mint, Ubuntu, Fedora, openSUSE, etc.

Get It Now From Amazon »

6. Alfa AWUS051NH (Ralink RT3572 Chipset)

Check Price

Alfa-AWUS051NH

Alfa AWUS051NH is little expensive but has amazing signal reception and works well on Kali and in 5Ghz Monitor mode.

  • It is compatible with 802.11n draft 3.0, 802.11a/b/g wireless standards
  • Work with 2.4GHz and 5.8GHz band and MIMO (Multiple Input Multiple Output)
  • Supports wireless transfer RX data rate of up to to 300 Mbps
  • Allows wireless data encryption with 64/128-bit WEP, WPA, WPA2, TKIP, AES Protocols
  • Compatible with Windows 2000, 32/64 bit XP & Vista, Linux (2.4.x/2.6.x), Mac (10.4.x/10.5.x) Power PC& PC.

Get It Now From Amazon »

Over To You:

So these are the best wireless adapters and usb dongles for kali linux. Though all these adapters works well with Kali, just make sure if it is the right one for your environment. For example if you wish to run Kali on Virtual box in Windows 7 host then make sure the card is compatible with Windows 7 OS. Also you must be cautious about the coverage range. Antenna with bigger dBi would be better for longer range. This helps you avoid future trouble. If you find this useful please share it with others to give them good suggestion.

Also Read:

Delete ALL Files and Subfolders from Folder in PHP

On 5/16/2017 Be the first to comment!

Hi! Today let's see how to delete all files and sub-folders from a folder using php. If your website allows user uploaded contents then I bet you might want to do regular clean ups to free up more space in web server. Like deleting all files of a user without activity for long time, deleting files older than 3 months etc. Whatever the reason, doing such clean-up manually is a tedious task. You can accomplish it with the help of an automated php script. And I'm going to show you here exactly how to delete directory and all files and sub directories from it with php.

php-delete-all-files-and-subfolders-from-folder

Delete All Files from Folder in PHP:

As for deleting all files from a folder the process is pretty straight forward. You only need two native php functions glob() and unlink() to achieve this.

  • Function glob() returns an array of filenames/directories matching the given pattern.
  • Function unlink() deletes a given file.

Our process goes like this - you have to loop through the files one by one from a given folder, check if it is a file and delete file with the help of unlink() function. Here is the simple php function I have written to delete all files from a directory.

PHP Function to Delete All Files from Folder:

<?php
// delete all files from folder
function deleteFiles($dir)
{
    // loop through the files one by one
    foreach(glob($dir . '/*') as $file){
        // check if is a file and not sub-directory
        if(is_file($file)){
            // delete file
            unlink($file);
        }
    }
}
?>

Usage:

<?php deleteFiles("test"); ?>

As you can see in function deleteFiles() we have used the pattern '/*' to instruct glob() to get all the files names from the folder.

Next we loop through the files one by one and check if the item is a file and not a sub folder itself using is_file() function.

Once we confirm it as a file we delete it with unlink() method. The process will be repeated until no file is left in the specific folder.

Delete Only Particular File Type from Folder:

Say you don't want to remove all files, just the pdf files alone from a folder. Then here's the script for the task.

<?php
// delete all pdf files from folder
function deleteFiles($dir)
{
    // loop through the files one by one
    foreach(glob($dir . '/*.pdf') as $file){
        // check if is a file and not sub-directory
        if(is_file($file)){
            // delete file
            unlink($file);
        }
    }
}
?>

Delete Files Older than X Days from Folder:

This is another useful variation of the script. Suppose you want to delete older files say of at least 90 days old. You have to simply check if the last modified date and time of the file is greater than 90 days and delete if it is.

<?php
// delete all files older than 90 days
function deleteFiles($dir)
{
    // loop through the files one by one
    foreach(glob($dir . '/*') as $file){
        if(is_file($file)){
            // check if file older than 90 days
            if((time() - filemtime($file)) > (60 * 60 * 24 * 90))
                unlink($file);
        }
    }
}
?>

To check if files are older than 90 days, we have used filemtime() to get last modified timestamp of a given file, took its difference from current timestamp and checked it against 90 days count.

Delete All Files and Sub Folders from a Folder in PHP:

So far we have seen about deleting just files present in a directory. What if you have sub directories with files inside the folder. In such case the above script won't work. You'll need to create recursive function to delete all files, sub-directories and parent directory altogether.

Simply deleting a folder with rmdir() won't work. It will throw exception if you attempt to remove folder with files in it. So first you have to delete files one by one from each sub folder plus the rest of the files and then delete folders by removing parent folder.

Here is the php recursive function to delete files and sub folders from the folder.

<?php
// delete all files and sub-folders from a folder
function deleteAll($dir) {
    foreach(glob($dir . '/*') as $file) {
        if(is_dir($file))
            deleteAll($file);
        else
            unlink($file);
    }
    rmdir($dir);
}
?>

Function Usage:

<?php deleteAll("test"); ?>

It will take care of deleting all files, sub folders from a folder automatically.

You can use the above php script to delete files and sub-directories in a given folder programmatically. The script is relatively fast but it depends on the amount of files and folders to be deleted. I hope you find this tutorial useful. Meet you in another interesting one :)

CodeIgniter MODAL Contact Form w/ jQuery AJAX Validation Example

On 5/10/2017 16 Comments so far

Hi, a while back I have written a tutorial about building contact form in codeigniter. It got great feedbacks and some of the readers asked about implementing the same feature in modal popup form. I thought it would be beneficial to kodingmadesimple.com readers if I provide it as a separate tutorial and in this article I’m going to show you How to Build a Proper Modal Contact Form in CodeIgniter with AJAX Field Validations.

Though the features of the modal form we are going to build would be similar to regular contact form, it become little bit tricky in the way we do form field validations. Since we can’t afford to refresh the page by submitting the form, we should go by AJAX technique to avoid page refreshing.

One thing to mention here is I wish to validate the form input on server side for security reasons even though you can do it on client side. Let’s see how to implement this in codeigniter.

Recommended Read: How to Get User IP Address in CodeIgniter

Creating Modal Form using Twitter Bootstrap CSS

To build our modal form, we are going to use Twitter Bootstrap CSS since it provides easy-to-use modal component and it fits our purpose. In order to use bootstrap in codeigniter you have to properly integrate the two frameworks. It’s very simple to do it and if you don’t know how, read this article to setup bootstrap css in codeigniter framework.

CodeIgniter Modal Contact Form Workflow

Modal Form is just like any other web forms but it opens up as a popover, so it should be invoked by clicking a button or a link. For better understanding I’ll show this with an example page, consisting a top navigation menu with ‘Contact’ menu link and upon clicking the contact menu the modal contact form should pop up.

Then using the ajax technique we should post the form data, run validation check and display if there are any validation errors at the bottom of the form. If it passes validation check, we should configure and send email to the site owner’s email address and provide proper message alerts to the user.

Implementing Modal Contact Form in CodeIgniter

To implement the modal form we should create a controller and a view file (for interface) in codeigniter. Since we are going to process the form data and send it as email there is no need for model file.

The Controller File (‘modal_contact.php’)

First create a file named ‘modal_contact.php’ inside ‘application/controllers’ folder and copy paste the below code to it.

<?php
class modal_contact extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library(array('form_validation', 'email'));
    }

    function index()
    {
        $this->load->view('modal_contact_view');
    }

    function submit()
    {
        //set validation rules
        $this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean|callback_alpha_space_only');
        $this->form_validation->set_rules('email', 'Emaid ID', 'trim|required|valid_email');
        $this->form_validation->set_rules('subject', 'Subject', 'trim|required|xss_clean');
        $this->form_validation->set_rules('message', 'Message', 'trim|required|xss_clean');
        
        //run validation check
        if ($this->form_validation->run() == FALSE)
        {   //validation fails
            echo validation_errors();
        }
        else
        {
            //get the form data
            $name = $this->input->post('name');
            $from_email = $this->input->post('email');
            $subject = $this->input->post('subject');
            $message = $this->input->post('message');
            
            //set to_email id to which you want to receive mails
            $to_email = 'user@gmail.com';
            
            //configure email settings
            $config['protocol'] = 'smtp';
            $config['smtp_host'] = 'ssl://smtp.gmail.com'; // change this to yours
            $config['smtp_port'] = '465';
            $config['smtp_user'] = 'user@gmail.com'; // change this to yours
            $config['smtp_pass'] = 'mypassword'; // change this to yours
            $config['mailtype'] = 'html';
            $config['charset'] = 'iso-8859-1';
            $config['wordwrap'] = TRUE;
            $config['newline'] = "\r\n"; //use double quotes
            $this->email->initialize($config);
            
            //send mail
            $this->email->from($from_email, $name);
            $this->email->to($to_email);
            $this->email->subject($subject);
            $this->email->message($message);
            if ($this->email->send())
            {
                // mail sent
                echo "YES";
            }
            else
            {
                //error
                echo "NO";
            }
        }
    }
    
    //custom validation function to accept alphabets and space
    function alpha_space_only($str)
    {
        if (!preg_match("/^[a-zA-Z ]+$/",$str))
        {
            $this->form_validation->set_message('alpha_space_only', 'The %s field must contain only alphabets and space');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
}
?>

The constructor function loads the essential helper & libraries including the ‘email’ class for sending mail.

The index() function is the default one to be called when we invoke the controller and it loads the view file (this we will create next) to show the form interface.

The submit() function is where the form data is posted through ajax call, run validation check and send email.

Here we set the validation rules for all the form fields and run validation check. If there is any validation error then we display it at the bottom of the form. The statement echo validation_errors(); will return back all the validation error messages. This in turn will be received by the jquery ajax function and displayed at the bottom of the modal form interface like this.

codeigniter-ajax-form-validation-example
CodeIgniter AJAX Form Validation Errors

If there is no such validation errors, then we configure the email settings and send the mail using $this->email->send(); statement. We also notify the user if their message is properly sent or not.

The View File (‘modal_contact_view.php’)

Now it’s time to create the modal interface. Create a file named ‘modal_contact_view.php’ inside ‘application/views’ folder and copy paste the below code and save.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter Modal Contact Form Example</title>
    <!--load bootstrap css-->
    <link href="<?php echo base_url("assets/bootstrap/css/bootstrap.css"); ?>" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- Navigation Menu -->
<nav class="navbar navbar-inverse" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">ShopMania</a>
        </div>
        <div class="collapse navbar-collapse" id="navbar1">
            <ul class="nav navbar-nav">
                <li><a href="#">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Deals & Offers</a></li>
                <li><a href="#">Blog</a></li>
                <li class="active"><a href="#" data-toggle="modal" data-target="#myModal">Contact</a></li>
            </ul>
        </div>
    </div>
</nav>

<!-- modal form -->
<div id="myModal" class="modal fade" aria-labelledby="myModalLabel" aria-hidden="true" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <?php $attributes = array("name" => "contact_form", "id" => "contact_form");
            echo form_open("modal_contact/submit", $attributes);?>

            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Contact Form</h4>
            </div>
            <div class="modal-body" id="myModalBody">
                <div class="form-group">
                    <label for="name">Name</label>
                    <input class="form-control" id="name" name="name" placeholder="Your Full Name" type="text" value="<?php echo set_value('name'); ?>" />
                </div>
                
                <div class="form-group">
                    <label for="email">Email ID</label>
                    <input class="form-control" id="email" name="email" placeholder="Email-ID" type="text" value="<?php echo set_value('email'); ?>" />
                </div>

                <div class="form-group">
                    <label for="subject">Subject</label>
                    <input class="form-control" id="subject" name="subject" placeholder="Subject" type="text" value="<?php echo set_value('subject'); ?>" />
                </div>

                <div class="form-group">
                    <label for="message">Message</label>
                    <textarea class="form-control" id="message" name="message" rows="4" placeholder="Message"><?php echo set_value('message'); ?></textarea>
                </div>

                <div id="alert-msg"></div>
            </div>
            <div class="modal-footer">
                <input class="btn btn-default" id="submit" name="submit" type="button" value="Send Mail" />
                <input class="btn btn-default" type="button" data-dismiss="modal" value="Close" />
            </div>
            <?php echo form_close(); ?>            
        </div>
    </div>
</div>
<!--load jquery & bootstrap js files-->
<script type="text/javascript" src="<?php echo base_url("assets/js/jquery-1.10.2.js"); ?>"></script>
<script src="<?php echo base_url("assets/bootstrap/js/bootstrap.min.js"); ?>"></script>
<script type="text/javascript">
$('#submit').click(function() {
    var form_data = {
        name: $('#name').val(),
        email: $('#email').val(),
        subject: $('#subject').val(),
        message: $('#message').val()
    };
    $.ajax({
        url: "<?php echo site_url('modal_contact/submit'); ?>",
        type: 'POST',
        data: form_data,
        success: function(msg) {
            if (msg == 'YES')
                $('#alert-msg').html('<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
            else if (msg == 'NO')
                $('#alert-msg').html('<div class="alert alert-danger text-center">Error in sending your message! Please try again later.</div>');
            else
                $('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>');
        }
    });
    return false;
});
</script>
</body>
</html>

The <nav> element creates responsive navigation menu using bootstrap’s navbar component. Next we have created the modal form with id #myModal and invoke it using the data attribute data-target="#myModal" when the user clicks on the ‘contact’ menu.

At the bottom of the markup we have created a jQuery script to run when the user clicks on the ‘Send Mail’ button and it collects the form data and post it to the controller’s submit() function. The return value is received and the appropriate message alerts are displayed on the div block with id #alert-msg.

That’s it. We have completed the coding part. Now run the controller in the browser and you can see a page with navigation menu like this.

twitter-bootstrap-navigation-menu-example

Next click on the ‘Contact’ menu link and the modal form pops up like this.

codeigniter-modal-contact-form-ajax-validation-example
CodeIgniter Modal Contact Form

When you feed the form data and click on the ‘Send Mail’ button, the form data is submitted and processed via AJAX call and appropriate success or failure alerts will be displayed like this.

codeigniter-send-email-success-message
codeigniter-send-email-failure-message

Now we have created a working modal contact form in php codeigniter framework. If you want to store the contact form data into database rather than sending mail, then read this codeigniter contact form tutorial with database storage option.

Also Read:

Select All Div Text On Mouse Click using JavaScript

On 5/01/2017 Be the first to comment!

Hi! Let's see how to select all div text on single mouse click using javascript. At times you may let site users to copy block of text or code snippets. In such case users has to click on and drag the mouse to select the entire text. But you can make users to copy complete text with just a single mouse click. Say for example you have a div container with some code snippet. When user clicks anywhere inside div the whole content of the element will be selected. This will drastically improve user experience. And you can achieve it with good old javascript. Here's how to do it.

select all div text on click javascript

Selecting All Div Text on Mouse Click in JavaScript

The method I'm going to show you will not only select text inside div but works with any html element. It can be a paragraph element, textbox or text area.

Read Also

Here's the javascript function to select complete text of a given container.

Create JavaScript Function

<script type="text/javascript">
function selectAllText(id)
{
    if (document.selection)
    {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(id));
        range.select();
    }
    else if (window.getSelection)
    {
        var range = document.createRange();
        range.selectNode(document.getElementById(id));
        window.getSelection().addRange(range);
    }
}
</script>

Here's how the above javascript function works.

  • The method document.body.createTextRange() will create a text range for the entire document.
  • Next selectNode() will mark the start and end of the text inside the given container.
  • Finally select() method will select the text between the given text range

Function Usage

Create a <div> element and call the function selectAllText() on click event.

<div id="mydiv" onclick="selectAllText(this.id)">Lorem ipsum dolem</div>

Clicking anywhere inside the div will select it's entire text content. This will be very useful to copy paste code snippets or other texts with just a single mouse click.

As I already said you can replace the div container with any other html element. The same function will work for them as well.

If you want to implement something similar with jquery you have to use select() function.

$("#mydiv").focus(function() {
    var $this = $(this);
    $this.select();
});

Likewise you can select all div text with single mouse click in javascript. I hope you find this script useful. Meet you in another interesting tutorial :)

Easy PHP Form Validation with Parsley.js Library

On 4/25/2017 Be the first to comment!

Hey! Let's see about easy php form validation using parsley.js jquery library. Form Validation should be done at both client and server side. For client validation you can use javascript or jquery and for server-side any backend script like PHP, Ruby etc. If your app consists of several web forms then validation process could be repetitive and boring. Here's where Parsley comes to the rescue.

Parsley is a light-weight javascript form validation library. With Parsley everything becomes easy. You can validate user input without writing lines and lines of code. Parsley uses special DOM API and includes all sorts of common validators you need to validate HTML forms. It's feature-rich and can be easily extended to accommodate custom validations.

How to Use Parsley to Validate HTML Forms?

For validating forms, you can configure all your validation rules right from DOM by using Parsley's data-parsley- DOM attribute.

Please note that the library relies on jquery so you must load jquery before loading Parsley.js.

Read Also:

Just download Parsley.js from here and move it to your application root. Load jquery & parsley in html form.

<html>
    <body>

        <form id="myform">
            ...
            ...
        </form>

        <script src="jquery.js"></script>
        <script src="parsley.min.js"></script>
    </body>
</html>

Then you must set validation rules to each one of the input fields. To make a field mandatory just use HTML5 required attribute or parsley's data-parsley-required.

<input id="myfield" type="text" required />

To validate an email field add Parsley DOM validator like this.

<input id="email" data-parsley-type="email" type="text" />

Validation error will be displayed below form input like this,

form validation parsley error

To match the input with specific pattern, say you need the field to contain only alphabets use data-parsley-pattern attribute like this.

<input id="name" type="text" data-parsley-pattern="^[a-zA-Z]+$" />

Finally you have to bind Parsley to the form. You can do this in two ways. First one is by simply adding data-parsley-validate attribute to html form tag.

<form id="myform" data-parsley-validate>
    ...
    ...
</form>

And the second one is to bind via java script function.

<form id="myform">
    ...
    ...
</form>

<script type="text/javascript">
    $('#myform').parsley();
</script>

PHP Form Validation with Parsley.js:

Now let's see a real world demo. For this I'm going to create user sign up form, validate fields with parsley.js and if everything went ok use php script to insert user details into mysql database. I'm using php here but it can be any other server-side script.

Create user registration form.

index.html

<!doctype html>
<html>
<head>
<title>User Registration Form</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">
        <div class="col-xs-6 col-xs-offset-3 well">
            <form action="register.php" method="post" class="form-horizontal">
                <div class="form-group">
                    <div class="col-xs-6">
                        <label for="fname">First Name</label>
                        <input type="text" id="fname" name="fname" placeholder="Enter First Name" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                    <div class="col-xs-6">
                        <label for="lname">Last Name</label>
                        <input type="text" id="lname" name="lname" placeholder="Last Name" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="col-xs-12">
                        <label for="email">Email</label>
                        <input type="text" id="email" name="email" placeholder="Email" required data-parsley-type="email" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-12">
                        <label for="password">Password</label>
                        <input type="password" id="password" name="password" placeholder="Password" required data-parsley-length="[8, 16]" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-12">
                        <label for="cpassword">Confirm Password</label>
                        <input type="password" id="cpassword" name="cpassword" placeholder="Confirm Password"data-parsley-equalto="#password" data-parsley-trigger="keyup" required class="form-control" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-12">
                        <label for="cpassword">Website</label>
                        <input type="text" id="website" name="website" placeholder="Website URL" data-parsley-type="url" data-parsley-trigger="keyup" class="form-control" />
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-12">
                        <label>
                        <input type="checkbox" id="chkrules" name="chkrules" required /> I Accept the Terms & Conditions
                        </label>
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="col-xs-12">
                        <input type="submit" id="submit" name="submit" value="Register" class="btn btn-primary" />
                    </div>
                </div>
            </form>
        </div>
    </div>
    <script src="js/jquery-1.10.2.js"></script>
    <script src="js/parsley.min.js"></script>
    <script>
    $(document).ready(function(){
        $('form').parsley();
    });
    </script>
</body>
</html>

Then add php script to grab submitted form details and store it in database.

register.php

<?php
$con = mysqli_connect("localhost", "root", "", "mydemo") or die("Error " . mysqli_error($con));

if (isset($_POST['submit'])) {
    $firstname = mysqli_real_escape_string($con, $_POST['fname']);
    $lastname = mysqli_real_escape_string($con, $_POST['lname']);
    $emailid = mysqli_real_escape_string($con, $_POST['email']);
    $password = mysqli_real_escape_string($con, $_POST['password']);
    $website = mysqli_real_escape_string($con, $_POST['website']);
    $sql = "INSERT INTO tbl_users(fname, lname, email, password, website) VALUES('$firstname', '$lastname', '$emailid', 'md5($password)', '$website')";
    
    if(mysqli_query($con, $sql))
        echo "Successfully Registered!";
    else
        echo "Error! Please try again later!!!";
}
mysqli_close($con);
?>

And finally some css overriding. Parsley has its own css styling but since I have used bootstrap for form design I'm going to stick with it and override some bootstrap styles to color up the validation process.

CSS

.container {
    margin-top: 30px;
}

.well {
    background: none;
}

input.parsley-error,
select.parsley-error,
textarea.parsley-error {    
    border-color:#D43F3A;
    box-shadow: none;
}

input.parsley-error:focus,
select.parsley-error:focus,
textarea.parsley-error:focus {    
    border-color:#D43F3A;
    box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #FF8F8A;
}

input.parsley-success,
select.parsley-success,
textarea.parsley-success {    
    border-color:#398439;
    box-shadow: none;
}

input.parsley-success:focus,
select.parsley-success:focus,
textarea.parsley-success:focus {    
    border-color:#398439;
    box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #89D489
}

.parsley-errors-list {
    list-style-type: none;
    padding-left: 0;
    margin-top: 5px;
    margin-bottom: 0;
}

.parsley-errors-list.filled {
    color: #D43F3A;
    opacity: 1;
}

Done! We have everything in place. Now run the form and you will see something like this,

php form validation parsley jquery

Since form fields are set as required you will get validation error if you submit the form without providing input for mandatory fields.

php form validation error parsley

And the data-parsley-trigger="keyup" attribute will trigger field validation as soon as you key-in input fields.

php parsley form validation error

If a particular field validation is met then the input box will turn into green.

parsley form validation success

Once you input all the details and the parsley validation is successful, form will be submitted and the backend register.php script will take care of the rest of the registration process.

Well! I've shown really a gist of what parsley can do. We have only used a handful of built-in validators but the library supports lot more than that and also let you craft custom validators of your own. Here are some of the most common parsley validators you'll need for form validation.

API Validators Details
data-parsley-required Makes input field mandatory. Similar to HTML5 'required' attribute.
data-parsley-type="alphanum" Validates if input is a valid alpha-numeric string.
data-parsley-type="integer" Validates if input is a valid integer
data-parsley-pattern="^[a-zA-Z]+$" It validates if the input contains only alphabets. You can use any sort of regular expressions with '-pattern' attribute.
data-parsley-type="email" It validates if a form input is a valid email address
data-parsley-type="url" It validates if the input is a valid url.
data-parsley-length="[6, 12]" Validates if the length of the input is between minimum and maximum number of characters.
data-parsley-range="[6, 10]" Validates if the input is between the minimum and maximum range.
data-parsley-equalto="#somefield" It validates if value of the field matches with another field. This is quite useful in password confirmation type validation.
data-parsley-trigger="keyup" It triggers the validation process on key up event.

Parsley.js official site contains well-documented manual which you can use for learning more challenging functionalities. Once you get started it's quite easy to go with the flow. I hope you find this simple php form validation with parsley.js tutorial useful. Please don't forget to share it in social media. Meet you in another interesting tutorial.

Permanent 301 Redirect with PHP

On 4/17/2017 Be the first to comment!

Hey! In today's post let's see how to do permanent 301 redirect with php. Redirection is a very common practice in websites and can be done at page or domain level. There are two types of redirect, one is temporary and other is permanent. The temporary redirect sends 302 http code with headers and indicates browsers and search engines that the page is moved temporarily. And permanent redirection sends 301 code and tells browsers and search engines that the page is moved permanently to different location.

You can do page redirects via htaccess file or within code. PHP has this header() function which lets you redirect users from one page to another. No doubt most of you have used it countless times. But do you know the redirect you do is just temporary? Because unless stated explicitly the headers are sent for 302 redirect. So let's see how to perform 301 redirect in php here.

301 redirect in php

Permanent 301 Redirect with PHP:

Sometimes you might have moved a resource to another place and want to redirect the page permanently. It's also good for SEO and 301 redirect will pass link juice to the new url.

Also Read:

In php you have to redirect to another url like this,

header("Location: example/page.php");

Just pass the destination page to header() and it will attach 302 code and do temporary redirect. But you can also make the function to perform 301. For that you must state the response code with headers like this.

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://example.com/sample/page/");
?>

The above code will redirect users to the new url attaching a 301 http response code to headers. That's instructs browsers and bots to take it as permanent redirect. (Learn how to get http status code from Headers in PHP.)

If you think two lines of code is too much then refine it into a single line like this.

<?php header("Location: http://example.com/sample/page/", true, 301); ?>

The above line will permanently redirects to the provided page.

Most of us use only one param with in header() but the function takes up to three parameters.

  • First parameter is obviously the page location.
  • Second param is a boolean value and is useful if you send multiple headers of same type. True will replace same type header and False will force to send multiple headers of similar type.
  • Third param is the 'http_response_code' and attach the headers with redirection code.

Permanent 301 Redirect via HTACCESS:

Redirecting page via htaccess is even easier and practiced by so many webmasters. To redirect a page permanently add this line to the htaccess file in server.

redirect 301 /old-file.php /new-file.php

The above code will permanently redirect old-file.php to new-file.php with in the same domain.

If you have to redirect a file to another domain then specify the entire url.
redirect 301 /old-file.php http://another-domain.com/another-file.php

Likewise you can perform permanent 301 redirect in php. Make sure to place headers before actual output starts in php file. Else you will get error. I hope you find this useful. Meet you in next tutorial:D

Add/Remove Key Value Pairs (Attributes) from JSON Data using JavaScript

On 4/10/2017 Be the first to comment!

Hi! Let's see how to add and remove key value pairs from json data using javascript. JSON is the string representation of java script object and cross-platform compatible. Using AJAX you can communicate with numerous web services and grab API data in JSON format. Considering the increased popularity of API's, it goes without saying that the ability to read, process and manipulate JSON is a must have skill for developers. In JSON, data is stored as key - value pairs and wrapped within quotes since it's a string. Sometimes the key-value pairs are also referred to as attributes, items or elements. Here I'm going to show you how to append or remove key value pairs from existing json data.

add remove key value pair from json javascript

JSON Attributes - Key Value Pairs:

JSON attributes are represented as key value pairs something similar to associative arrays. The key-value pairs look something like this,

{ "name": "Barbie" }

Here "name" is the key and "Barbie" is the value of that key.

Also Read:

Plus JSON comes in all sorts of representation - simple, nested or arrays. The simple format contains a set of attributes like this.

{
    "fruit": "apple",
    "color": "red"
}

And as for array of items it will look like this,

[
    {
        "name": "Fredie",
        "department": "Finance"
    },
    {
        "name": "Rolland",
        "department": "Sales"
    },
    {
        "name": "Gina",
        "department": "Customer Service"
    }
]

At times json data can be complicated with nested attributes.

{
    "empid": "ABC001X",
    "personal": {
        "name": "Paula Thompson",
        "gender": "Female",
        "age": "34",
        "address": {
            "streetaddress": "12 117th Street",
            "city": "New York",
            "state": "NY",
            "zipcode": "10038"
        }
    },
    "official": {
        "designation": "Vice President",
        "department": "Operations"
    }
}

However it is you can manipulate json easily with native java script. The same can be handled with jquery but unless necessary just the plain old javascript will do. By this way you can reduce server load.

Add Key Value Pair to JSON with JavaScript:

Adding key value pair to json will append the new attribute to the end of the json string. Following is the simplest way to add attributes to existing json data.

var data = {
    "id": "XYZ123",
    "name": "Greg",
    "gender": "Male"
};

data.country = "United States";
console.log(JSON.stringify(data));

// Produce Output
{
    "id":"XYZ123",
    "name":"Greg",
    "gender":"Male",
    "country":"United States"
}

If json has array of items, then you can add key value pairs to each subset like this,

var data = [
    {
        "name": "John Smith",
        "age": "45"
    },
    {
        "name": "Peter Jason",
        "age": "26"
    },
    {
        "name": "Alice Ray",
        "age": "34"
    }
];

for (var i=0; i<data.length; i++) {
    data[i].department = "Administration";
    data[i].company = "ABC Corp";
}
console.log(JSON.stringify(data));

// Produce Output
var data = [
    {
        "name":"John Smith",
        "age":"45",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Peter Jason",
        "age":"26",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Alice Ray",
        "age":"34",
        "department":"Administration",
        "company":"ABC Corp"
    }
];

You have to loop through the array of items and add attributes to each one of it.

Remove Key Value Pair from JSON:

Let's say you have the following JSON data,

var data = {
    "id":"XYZ123",
    "name":"Greg",
    "gender":"Male",
    "country":"United States"
};

In order to remove an attribute from json you have to use JS delete method. This will delete the json attribute with the specific key.

delete data.gender;
console.log(JSON.stringify(data));

// Produce Output
{
    "id":"XYZ123",
    "name":"Greg",
    "country":"United States"
}

Likewise you can remove the occurrence of particular attribute from json array.

var data = [
    {
        "name":"John Smith",
        "age":"45",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Peter Jason",
        "age":"26",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Alice Ray",
        "age":"34",
        "department":"Administration",
        "company":"ABC Corp"
    }
];

for (var i=0; i<data.length; i++) {
    delete data[i].age;
}
console.log(JSON.stringify(data));

// Produce Output
[
    {
        "name":"John Smith",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Peter Jason",
        "department":"Administration",
        "company":"ABC Corp"
    },
    {
        "name":"Alice Ray",
        "department":"Administration",
        "company":"ABC Corp"
    }
]

That explains about add and remove key value pairs in json using javascript. Please note that the json you use should be of valid one for the above methods to work. I hope you find this tutorial useful. Meet you in another interesting one.

Contact Form

Name

Email *

Message *