Add, Update, Delete and Read JSON Data/File in PHP

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

Hi! Today let's see about JSON CRUD with PHP. Yep! Manipulating json data - add, update (edit), delete and read json file using php script. JSON is everywhere these days. With increasing popularity of APIs it's a must for a developer to know how to read, parse and manipulate json data. If you wonder what the connection between API and JSON is, almost all modern APIs lean towards REST and they provide response as JSON. (In KodingMadeSimple.com I have covered json topics a lot earlier and you can visit our JSON Tutorials section to learn more about working with JSON format.)

php add edit delete read json file

JSON is the string notation of JavaScript object. It takes up simple to complex forms and stores data as (key, value) pairs.

This is the example of a json file.

Read Also:

results.json

[
    {
        "Code": "1",
        "Name": "June Zupers",
        "Sports": "Base Ball"
    },
    {
        "Code": "2",
        "Name": "Fred Cortez",
        "Sports": "Soccer"
    },
    {
        "Code": "3",
        "Name": "Kevin Burks",
        "Sports": "Tennis"
    }
]

Now let me show you how to read and parse through above json file using php.

Read JSON File in PHP:

To read json file with php, you must first get the json data stored in the file, decode json and finally parse through the array or object.

For that you'll need two php functions - one is file_get_contents() and the other is json_decode().

<?php
// load file
$data = file_get_contents('results.json');

// decode json to associative array
$json_arr = json_decode($data, true);

foreach ($json_arr as $key => $value) {
    echo  $json_arr[$key] . " - " .  $json_arr[$value] . "<br/>";
}
?>

If you know the specific key name, then you can simply access it like this,

echo $json_arr[0]['Code'];

Note: The function json_decode() decodes the given json string into an array or object. For example the statement json_decode($data, true); in above code will return associative array. You can ignore the second parameter 'true' to make it return as an object.

Add to JSON File in PHP:

To add additional records to json file you have to simply append it to the end of file. Here let's see an example for adding new data. The following php snippet takes up a json file, decode it, add extra records and again encode to json and save it into a new file.

<?php
// read json file
$data = file_get_contents('results.json');

// decode json
$json_arr = json_decode($data, true);

// add data
$json_arr[] = array('Code'=>4, 'Name'=>'Jeff Darwin', 'Sports'=>'Cricket');

// encode json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
?>

results_new.json

[
    {
        "Code":"1",
        "Name":"June Zupers",
        "Sports":"Base Ball"
    },
    {
        "Code":"2",
        "Name":"Fred Cortez",
        "Sports":"Soccer"
    },
    {
        "Code":"3",
        "Name":"Kevin Burks",
        "Sports":"Tennis"
    },
    {
        "Code":4,
        "Name":"Jeff Darwin",
        "Sports":"Cricket"
    }
]

Update JSON File PHP:

As for updating json file you can either modify single value or in bulk. Here's an example for modifying value for a specific json attribute.

<?php
// read file
$data = file_get_contents('results.json');

// decode json to array
$json_arr = json_decode($data, true);

foreach ($json_arr as $key => $value) {
    if ($value['Code'] == '2') {
        $json_arr[$key]['Sports'] = "Foot Ball";
    }
}

// encode array to json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
?>

Here's what the script does.

  • Load results.json file to a variable
  • Decode json data to array
  • Loop through the array and check if key 'Code' is '2'
  • And edit the corresponding 'Sports' value to 'Foot Ball'

results_new.json

[
    {
        "Code":"1",
        "Name":"June Zupers",
        "Sports":"Base Ball"
    },
    {
        "Code":"2",
        "Name":"Fred Cortez",
        "Sports":"Foot Ball"
    },
    {
        "Code":"3",
        "Name":"Kevin Burks",
        "Sports":"Tennis"
    }
]

Delete JSON Data from File:

JSON deletion is little complex since it is easy to mess up doing the process. You must be clear what you need to delete first, a specific key pair from all rows or a complete row.

For example this php script will delete entire record from json containing key 'Code' as '2'.

<?php
// read json file
$data = file_get_contents('results.json');

// decode json to associative array
$json_arr = json_decode($data, true);

// get array index to delete
$arr_index = array();
foreach ($json_arr as $key => $value)
{
    if ($value['Code'] == "2")
    {
        $arr_index[] = $key;
    }
}

// delete data
foreach ($arr_index as $i)
{
    unset($json_arr[$i]);
}

// rebase array
$json_arr = array_values($json_arr);

// encode array to json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
?>

And this is the file we get after deletion.

[
    {
        "Code":"1",
        "Name":"June Zupers",
        "Sports":"Base Ball"
    },
    {
        "Code":"3",
        "Name":"Kevin Burks",
        "Sports":"Tennis"
    }
]

The deletion script uses two foreach loops. The first one is for determining the array index we need to delete from json.

And the second is what actually deletes from array using unset() function.

Finally it rebases the array, encode it to json and store it in a new file.

Read Also:

Likewise you can add, edit, delete and read json file in php. It's easy to mess up with json and so many newbies confuses json and actual javascript object. JSON can get complex if it uses nested structure and you'll have real trouble manipulating it. Only constant practice will get you there and it's easy to master it in my opinion.

I hope you like this tutorial. Please don't forget to share it with your friends.

Best 7 jQuery File Upload Plugins (Drag and Drop, Progress Bar)

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

Hi! Here's some of the best jquery file upload plugins for your next project. Implementing file uploading is one big headache as you have to take care of things like security; handling multiple uploads, dealing with too large files etc. And then there's this user experience sort of things like drag and drop, progress bar and providing file preview. Overall you have to sort out so many things during uploading process. If you don't want to go through all these hassle then use any one of the readily available jquery file upload plug in.

Below we have handpicked some of the best file upload plugins in jquery to make your life easier. They come with so many customizing options and let you integrate beautiful file uploader to your websites quickly and serve rich user experience.

best jquery file upload plugins with progress bar

7 Best jQuery File Upload Plugins:

1. Uploadify

Read: Drag and Drop Multiple File Upload in jQuery & AJAX

Uploadify plug-in let you integrate multiple file upload functionality to your website easily. This file upload plugin offers extreme customization and available as both HTML5 and Flash versions for you to choose from. What we like most is the ability to upload multiple files without clustering the page with numerous browse buttons, real-time progress bar and drag-drop support with HTML5 version.

Key Features:

  • Multiple file upload without multiple browse buttons
  • Drag and drop files to upload queue
  • Real time progress bar to show uploading status
  • Highly Customizable to suit your need
  • Restrict uploads based on file size, type, quantity etc

Visit Website

2. Droply JS

Droply is a light-weight responsive jQuery based plug-in to setup single or multi-file upload feature to websites. As a developer your time is precious, so using droply.js will give you the leverage to add beautiful and professional file uploader to websites without going through the hassle of implementing everything from scratch. The highly configurable settings and ease-of-use makes it a remarkable file uploader plug in.

With Droply users can easily upload extremely large files of several giga-bytes with ease as it employs the latest chunk upload technique. And the best part is its minimal size without comprising rich features it offers. It is written in pure jquery so compatible with all platforms.

Key Features:

  • Responsive multi-file uploader
  • Drag and drop Files support
  • Delete files from upload queue
  • Employs smooth CSS3 effects
  • Progress indicator & file preview options
  • Compatible with Android and iOS

Visit Website

3. Plupload

Plupload is another great choice if you need a file uploader with ready to build User Interface. It is based on HTML5 APIs and offers limited customizations. But Flash and Silverlight fallbacks, numerous readily available themes and multi-lingual packs makes it worth trying. Plus it uploads files in chunks and let you bypass any server limitation on uploading bigger files.

Read: jQuery Drop Down List with Search Example

Key Features:

  • Multi-uploader using HTML5 APIs
  • Drag-and-Drop file support
  • Instant thumbnail preview
  • Shrink Images on Client-Side to save bandwidth
  • Upload in Chunks to support large files
  • Support for 30+ languages

Visit Website

4. FineUploader

FineUploader is a flexible library written in pure JavaScript but available as jquery plugin too. It includes all sorts of basic functionalities you require in a file uploader plugin like single/multiple file uploads, drag and drop files, real-time progress indicator and file preview options. What if you have uploaded a wrong file? Well! With fineuploader you get a nice option to delete uploaded files.

Besides the plug-in offers so many interesting features like pause & resume uploads, file partitioning, entire folder uploading, image scaling, uploading directly to cloud like Amazon S3 or Microsoft Blob Storage service etc.

Key Features:

  • Pause, Resume & Retry Uploads
  • Cancel uploads in the middle
  • Support for Cloud uploading
  • Delete already uploaded files
  • File Chunking / Partitioning
  • ES6 modules & CommonJS Support
  • Upload from mobile camera

Visit Website

5. jQuery File Upload

jQuery File Upload is another good jquery plugin for simplified file uploading and saving. It offers versatile range of options supporting multiple file upload, drag and drop feature, status bar indicator, file preview and much more. Plus you can cancel and resume upload at any time. It also supports uploading large file in chunks and let you edit and resize images after uploading.

jQuery File Upload Plug in is cross-domain compatible which is another good reason to go for. It works with all sorts of server platforms like PHP, Python, Java, Node.js, Ruby on Rails etc that supports standard HTML file uploads.

Key Features:

  • Multiple file uploads
  • Drag & Drop files
  • Progress bar Support
  • Cancel/Resume uploads
  • Image resizing via JS APIs
  • Preview images/audio/video
  • Highly configurable & extendable

Visit Website

6. DropzoneJS

Dropzone is an open source library that turns out any HTML element into a potential dropzone area. It employs AJAX technology and let user drag and drop files onto it for uploading. The library is extremely light-weight and written on pure java script. Includes so many nice features like multiple uploads, progress bar, image preview & resize, configure file limits, rename file during uploads etc.

Dropzone is compatible with browsers like Chrome, Firefox, IE, Safari, Opera but not work in older versions which doesn't support drag’n’drop. So make sure to check for browser compatibility.

Key Features:

  • Multiple files & synchronous uploads
  • Progress bar indicator
  • Support for big files
  • Drag-and-drop
  • Image Preview
  • Enabled Retina

Visit Website

7. Bootstrap File Input

If you need something to work with Bootstrap then this is for you. Bootstrap File Input Plugin works with Bootstrap 3.x and an enhanced version of standard HTML5 file element with multiple file selection, preview support for various types of files such as html, image, audio, video, flash and objects. Further you can simply drag and drop files for uploading, preview, add and delete uploaded files. It is based on AJAX and relies on Bootstrap CSS3 styles.

Key Features:

  • Multiple File uploads
  • Drag and drop
  • Multi-file preview
  • Multi language widgets
  • Image Resizing
  • Configurable layout & style

Visit Website

Also Read:

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.

Contact Form

Name

Email *

Message *