Live Username Availability Check in PHP, AJAX & jQuery

On 9/22/2016 Be the first to comment!

Hi! Here I'm going to show you about live username availability check in php and jquery ajax. I don't have to mention how much Signup process means for a website and two main entity required for it is, username and password. Moreover this username should be unique and it's important to check if the username already exists in database or not at the time of registration. Performing this username availability check live would be smart and can be accomplished using php and jquery ajax request.

Live Username Availability Check in PHP & jQuery AJAX:

During user signup, we have to determine if the username entered is already been taken or not. So the idea is to let users type in the username and once they move on to the next field, we send AJAX request to a backend php script where it checks against the database if username is already present or not and returns appropriate result.

Also we have to keep the submit button under disabled state and make it active only when the chosen username is unique and not yet registered. Here goes the implementation for the live username availability check.

Create MySQL Database:

This is the mysql database we'd need for checking username availability.

CREATE DATABASE `db_demo`;
Use `db_demo`;

CREATE TABLE IF NOT EXISTS `tbl_users` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `email` varchar(60) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4;

INSERT INTO `tbl_users` (`id`, `username`, `email`) VALUES
(1, 'foxadmin', 'foxadmin@example.com'),
(2, 'george26', 'georgefoxus@gmail.com'),
(3, 'userjack', 'jack.jil@outlook.com');

HTML & jQuery AJAX Script:

This one is the user interface page. It contains an html form with two input fields for username & email-id and a submit button. The submit button would be kept disabled by default and activated only when the username entered by the user is available to take.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Live Check for Username Availability Using PHP & jQuery AJAX | Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container" style="margin-top: 20px;">
    <div class="row">
        <div class="col-xs-4 col-xs-offset-4">
            <form action="check_username.php" method="post">
                <legend>Check Username Availabilty:</legend>

                <div class="form-group">
                    <input type="text" id="username" placeholder="Enter username" class="form-control" />
                </div>
                <div id="msg" class="form-group"></div>
                <div class="form-group">
                    <input type="text" id="email" placeholder="Email ID" class="form-control" />
                </div>
                <div class="form-group">
                    <input type="submit" id="submit" value="submit" disabled class="btn btn-block btn-primary" />
                </div>
            </form>
        </div>
    </div>
</div>

<script src="js/jquery-1.10.2.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$("#username").blur(function(e) {
    var uname = $(this).val();
    if (uname == "")
    {
        $("#msg").html("");
        $("#submit").attr("disabled", true);
    }
    else
    {
        $("#msg").html("checking...");
        $.ajax({
            url: "check_username.php",
            data: {username: uname},
            type: "POST",
            success: function(data) {
                if(data > '0') {
                    $("#msg").html('<span class="text-danger">Username is already taken!</span>');
                    $("#submit").attr("disabled", true);
                } else {
                    $("#msg").html('<span class="text-success">Username is available!</span>');
                    $("#submit").attr("disabled", false);
                }
            }
        });
    }
});
});
</script>
</body>
</html>

As you can see above, we have used jQuery's ajax() function to send ajax request to backend. The 'url' param of this function is something similar to the form action attribute and contains the php filename where the HTTP request is to be sent. And the param 'data' contains the form data as json string and sent along with the request.

Then there's the 'success' function which gets executed when there is valid response. It gets the response from the php script and notifies user if username is taken or not.

PHP Script:

This script connects to the mysql database and fires a query to determine if there is any matching entry for the username and returns the result to the AJAX function.

check_username.php

<?php
// mysql connection
$host = "localhost";
$user = "username1";
$pass = "password1";
$db = "db_demo";
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_error($con));

if (isset($_POST["username"]))
{
    $username = mysqli_real_escape_string($con, $_POST["username"]);
    $sql = "select username from tbl_users where username='$username'";
    $result = mysqli_query($con, $sql);
    echo mysqli_num_rows($result);
}
?>

That's it. We have everything in place. Now run index.html file and type something for username and shift focus from the field. This will trigger the ajax call and the script informs if username is available or not. If the username you have entered is not yet registered then you will see message like this. And the submit button would be enabled.

live-username-availability-check-in-php-jquery-ajax

On the other hand if username is already taken then error message is shown and the submit button continues to be in disabled state.

check-if-username-already-exists-in-php-ajax

In this demo I have used blur() method to trigger ajax call however you can use change() or keyup() - but please be aware this would increase server load. So your best bet is to set some timer and send ajax request only when certain amount of time elapsed after user stoped typing.

Also Read: Live Search Engine Script using PHP, MySQL & AJAX

Don't Miss: PHP and MySQL User Login and Registration Script

So that explains about live username availability check using php and jquery ajax. You can customize the above code to better suit your requirement.

File Upload, View and Download using PHP and MySQL

On 9/19/2016 Be the first to comment!

Hi! In this tutorial let me show you about upload, view and download file in php and mysql. The file uploading process is similar to what we have discussed here, but this php script not only uploads file to the server but also stores the file path and its created date in mysql database. Apart from uploading file, it also gives you the option to view file on browser and download it from server.

With PHP you can practically upload any type of files and the file uploading script I have shared below will work for all file types like PDF, Document, Images, MP3, Videos, Zip archives etc. Just include those file extensions in the filtering process ($allowed array) and you will be able to upload them.

How to Upload, View & Download File in PHP & MySQL?

Let's move on to the coding part. First you should create mysql database to store file details.

Create MySQL Database:

CREATE DATABASE `demo` ;
Use `demo`;
CREATE TABLE IF NOT EXISTS `tbl_files` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `filename` varchar(255) NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

Next is the database connectivity script that establishes connection to mysql database from php.

dbconnect.php

<?php
//connect mysql database
$host = "localhost";
$user = "username";
$pass = "password";
$db = "demo";
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_error($con));
?>

Then create index.php - this is the main file containing user interface. It has an upload form and a html table to display the list of uploaded files from database along with 'View' & 'Download' links for them.

index.php

<?php
include_once 'dbconnect.php';

// fetch files
$sql = "select filename from tbl_files";
$result = mysqli_query($con, $sql);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Upload View & Download file in PHP and MySQL | Demo</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport" >
    <link rel="stylesheet" href="css/bootstrap.css" type="text/css" />
</head>
<body>
<br/>
<div class="container">
    <div class="row">
        <div class="col-xs-8 col-xs-offset-2 well">
        <form action="upload.php" method="post" enctype="multipart/form-data">
            <legend>Select File to Upload:</legend>
            <div class="form-group">
                <input type="file" name="file1" />
            </div>
            <div class="form-group">
                <input type="submit" name="submit" value="Upload" class="btn btn-info"/>
            </div>
            <?php if(isset($_GET['st'])) { ?>
                <div class="alert alert-danger text-center">
                <?php if ($_GET['st'] == 'success') {
                        echo "File Uploaded Successfully!";
                    }
                    else
                    {
                        echo 'Invalid File Extension!';
                    } ?>
                </div>
            <?php } ?>
        </form>
        </div>
    </div>
    
    <div class="row">
        <div class="col-xs-8 col-xs-offset-2">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>File Name</th>
                        <th>View</th>
                        <th>Download</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                $i = 1;
                while($row = mysqli_fetch_array($result)) { ?>
                <tr>
                    <td><?php echo $i++; ?></td>
                    <td><?php echo $row['filename']; ?></td>
                    <td><a href="uploads/<?php echo $row['filename']; ?>" target="_blank">View</a></td>
                    <td><a href="uploads/<?php echo $row['filename']; ?>" download>Download</td>
                </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

Note: This demo uses twitter bootstrap for css stylesheet.

Running index.php will generate a page with upload form and table with files details similar to this. Users can either click on 'View' link to view the files on browser or on 'Download' to download the files from server.

upload-and-view-file-php-mysql

Finally there is 'uploads.php' file which will be executed when the form is submitted to upload the selected file. Here is where we actually upload the file to the server from the client machine and save its name and uploaded date into the database.

uploads.php

<?php
//check if form is submitted
if (isset($_POST['submit']))
{
    $filename = $_FILES['file1']['name'];

    //upload file
    if($filename != '')
    {
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $allowed = ['pdf', 'txt', 'doc', 'docx', 'png', 'jpg', 'jpeg',  'gif'];
    
        //check if file type is valid
        if (in_array($ext, $allowed))
        {
            // get last record id
            $sql = 'select max(id) as id from tbl_files';
            $result = mysqli_query($con, $sql);
            if (count($result) > 0)
            {
                $row = mysqli_fetch_array($result);
                $filename = ($row['id']+1) . '-' . $filename;
            }
            else
                $filename = '1' . '-' . $filename;

            //set target directory
            $path = 'uploads/';
                
            $created = @date('Y-m-d H:i:s');
            move_uploaded_file($_FILES['file1']['tmp_name'],($path . $filename));
            
            // insert file details into database
            $sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
            mysqli_query($con, $sql);
            header("Location: index.php?st=success");
        }
        else
        {
            header("Location: index.php?st=error");
        }
    }
    else
        header("Location: index.php");
}
?>

This script upload file from local machine to server and stores its details into database and redirects to index.php. If everything goes right you will be able to see success message on completion.

upload-file-in-php-mysql-and-store-in-database

If there's any error you will be notified about it.

file-upload-and-download-in-php-mysql

Also Read: PHP User Login and Signup System using MySQL

So we have seen about file upload and to view and download them using php and mysql database. If you want you can set the file size limit or restrict users to upload only pdf or images etc.

Upload Multiple Images & Files in CodeIgniter (EXAMPLE)

On 9/15/2016 Be the first to comment!

Hi! In this post, we'll see how to upload multiple images and files in codeigniter. Kodingmadesimple has a nice tutorial about codeigniter file upload process. Normal file uploading has a limitation which is you can only upload a single file/image at a time. What if you want to upload multiple files or images in codeigniter in one go? Is it possible to do that? The answer is YES! You can! Here I'll show you an example about multiple file upload in codeigniter.

CodeIgniter Upload Multiple Files/Images:

For this file uploading process you'll need a folder in the server to store all your uploaded files. Just create a folder named 'uploads' inside the application root and make sure to enable 'write' access to it.

Next you need to create user interface to upload files. So create a code igniter view with a form and add file control & submit button to it. Set the name of the file field as array and add 'multiple' attribute to enable multi-select. Without this setting, you'll only be able to select single file at a time to upload.

Also set form type to 'multipart' for the uploading process to work. Here is the view I have created for the demo.

View (multiple_upload_view.php):

<div class="container">
    <div class="row">
        <div class="col-xs-8 col-xs-offset-2 well">
            <?php echo form_open_multipart('multiple_upload/upload');?>
                <legend>Select Files to Upload:</legend>
                <div class="form-group">
                    <input name="usr_files[]" type="file" multiple="" />
                    <span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
                </div>
                <div class="form-group">
                    <input type="submit" value="Upload" class="btn btn-primary btn-block"/>
                </div>
            <?php echo form_close(); ?>
            <?php if (isset($success_msg)) { echo $success_msg; } ?>
        </div>
    </div>
</div>

This view would create a html form similar to this,

upload-multiple-images-files-codeigniter-example

Next you need to create a controller where you receive the files from the file control and loop through the $_FILES array one by one and upload them to server using $this->upload->do_upload() function. By default this function read & uploads the file from the form field with name 'userfile'. If you want to use some other name then you should pass it as function parameter to do_upload().

Controller (multiple_upload.php):

<?php
class multiple_upload extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    function index()
    {
        //load file upload form
        $this->load->view('multiple_upload_view');
    }

    function upload()
    {
        // set upload preferences
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'txt|pdf';
        $config['max_size']    = '150';

        //initialize upload class
        $this->load->library('upload', $config);
        
        $upload_error = array();
        
        for($i=0; $i<count($_FILES['usr_files']['name']); $i++)
        {
            $_FILES['userfile']['name']= $_FILES['usr_files']['name'][$i];
            $_FILES['userfile']['type']= $_FILES['usr_files']['type'][$i];
            $_FILES['userfile']['tmp_name']= $_FILES['usr_files']['tmp_name'][$i];
            $_FILES['userfile']['error']= $_FILES['usr_files']['error'][$i];
            $_FILES['userfile']['size']= $_FILES['usr_files']['size'][$i];
            
            if (!$this->upload->do_upload())
            {
                // fail
                $upload_error = array('error' => $this->upload->display_errors());
                $this->load->view('multiple_upload_view', $upload_error);
                break;
            }
        }
        
        // success
        if ($upload_error == NULL)
        {
            $data['success_msg'] = '<div class="alert alert-success text-center">Finished uploading...</div>';
            $this->load->view('multiple_upload_view', $data);
        }
    }
}
?>

In the above controller I have added a function upload() to loop through the file array, upload files one by one and display a success message once the process is complete.

codeigniter-upload-multiple-files-success

If anything goes wrong at the time of uploading, then error message will be shown to the user.

codeigniter-multiple-image-upload-error

If you want to restrict uploading to images alone, then set the configuration to accept only image file types like this,

$config['allowed_types'] = 'png|gif|jpg|jpeg';

To accept all sorts of file types use '*' instead (default),

$config['allowed_types'] = '*';

Read Also: CodeIgniter Login and Registration System

That explains about uploading multiple images and files in php codeigniter. I have given the logic. Just customize it to suit your needs. Meet you another interesting tutorial :)

Create Database and Table in CodeIgniter (IF NOT EXISTS)

On 9/12/2016 Be the first to comment!

CodeIgniter create database if not exists: To create database & table in code igniter you have to use the Database Forge class. This library helps you to manage all sorts of database activities like create, drop, modify database/tables. You can use this class to migrate database if you prefer to do it manually.

Here we'll see how to create database and tables in codeigniter programmatically using the Forge Class.

Initializing the Forge Class:

First you have to initialize the Forge class and then access its methods using the handle $this->dbforge. The class depends on database driver so make sure it is up and running.

$this->load->dbforge();

Create Database in CodeIgniter:

To create database in codeigniter use the function create_database() like this,

$this->dbforge->create_database('db_name');

// SQL String: CREATE DATABASE db_name;

The function returns TRUE/FALSE based on success or failure. So you can verify if the database is created or not like this,

// check if database is created
if ($this->dbforge->create_database('Library'))
{
 echo 'Database created successfully...';
}

CodeIgniter Create Database If Not Exists:

To include IF NOT EXISTS clause to 'CREATE DATABASE' command, pass the second parameter as 'TRUE' to the method.

$this->dbforge->create_database('Library', TRUE)

// SQL String: CREATE DATABASE IF NOT EXISTS Library;

Create Table in CodeIgniter:

Just like creating databases you can create tables using the function create_table(). Together you have to use the method add_field() to add fields to the table. If you want to add multiple columns/fields to the table then pass it as an associative array to add_field() function. The call to this function should be immediately followed by create_table() method.

Also note that to create table in different database other than the default, first you have to run a query to switch over DB and then create table.

// switch over to Library DB
$this->db->query('use Library');

// define table fields
$fields = array(
  'memid' => array(
    'type' => 'INT',
    'constraint' => 9,
    'unsigned' => TRUE,
    'auto_increment' => TRUE
  ),
  'firstname' => array(
    'type' => 'VARCHAR',
    'constraint' => 30
  ),
  'lastname' => array(
    'type' => 'VARCHAR',
    'constraint' => 30
  ),
  'email' => array(
    'type' => 'VARCHAR',
    'constraint' => 60,
    'unique' => TRUE
  ),
  'password' => array(
    'type' => 'VARCHAR',
    'constraint' => 40
  )
 );

$this->dbforge->add_field($fields);

// define primary key
$this->dbforge->add_key('memid', TRUE);

// create table
$this->dbforge->create_table('Members');

The method add_key('memid', TRUE) adds primary key to the 'memid' field. By passing the second parameter as 'TRUE' will create primary key constraint.

Create Table If Not Exists:

Just like database, you can add IF NOT EXISTS clause while creating table. This will create a table if there is no other table with the same name.

$this->dbforge->create_table('Members', TRUE);

// SQL String: CREATE TABLE IF NOT EXISTS Members (...);

Set MySQL Engine:

If you like to set mysql engines during DB creation, then you have to pass the details in array as third argument to create_database().

$attr = array('ENGINE' => 'InnoDB');
$this->dbforge->create_database('db_name', FALSE, $attr);

That should create database & table in codeigniter. Apart from creating database you can also update, drop and access these database tables.

CodeIgniter Load Multiple Views / View Inside View

On 9/09/2016 Be the first to comment!

This codeigniter tutorial will show you how to load multiple views in controller or load view inside another view in codeigniter. A view can be a complete webpage or just a part of it like header, footer, menu bar, body content etc. They are flexible in nature and can be nested inside one another.

Views should never be called directly in code igniter but loaded via controllers. And the framework allows you to load multiple views simultaneously or load view within view directly. Both the methods deliver same results but their approach is slightly different. We'll see about them here.


Loading Multiple Views in Codeigniter:

In codeignitor, you must load the views using the function $this->load->view() inside controller. When you make multiple calls to this function, codeingiter cleverly appends them together and display it as one. Here is the example of doing it.

<?php
class my_controller extends Controller {

    ...
    ...
    
    function index()
    {
        $this->load->view("header_view");
        $this->load->view("main_content_view");
        $this->load->view("footer_view");
    }
}
?>

Codeigniter Load View Inside Another View:

As for this approach instead of loading the view from the controller you have to load it directly in another view. Just return the inner view (view to be included) as string and pass it to the outer view.


In your controller you have to add this,

<?php
$data['left_menu'] = $this->load->view('left_menu', '', TRUE);
$this->load->view ('user_profile', $data);
?>

The statement $this->load->view('left_menu', '', TRUE); has the third argument as TRUE which makes it to return the view as string rather sending the output to the browser.


Then in the outer view file you must echo the (view) content.

<html>
    <head>
        ...
    </head>
    <body>
        <div id="header">
        </div>
        <div id="main">
            <div><?php echo $left_menu; ?></div>
            <div id="content"></div>
        </div>
        <div id="footer">
        </div>
    </body>
</html>

Like that you can easily load view inside another view in codeigniter.

CodeIgniter Session Tutorial (GET, SET & DESTROY Session Data)

On 9/05/2016 Be the first to comment!

CodeIgniter Session Tutorial: This post will show you how to start and destroy session in codeigniter. Sessions are used to maintain user's state and keep track of their activity on your website. Every user is associated with a unique session ID which will then be stored in a session cookie. But for additional security you can store sessions in database and verify the session id from the cookie against the one from DB.

CodeIgniter's Session class takes care of session related tasks effectively. For each session it stores by default some basic details like session_id, user ip address but also permits to set custom data in sessions.

codeigniter-session-tutorial-set-get-start-destroy-session-data

To Start Session in CodeIgniter:

In order to start session in code igniter first you'll need to initialize the session class and set userdata. You can either do it by auto-loading session class inside application/config/autoload.php or load it individually in your controller.

$this->load->library('session');

Once loaded you get to access it through the handle $this->session.

CodeIgniter: Set Session Data

Using the method set_userdata() you can set session data in codeignitor. Again you can use two different ways to store data in session.

You can set multiple items at once using associative array. For example at the time of user login you may need to store several details about a user which you can set it as an array like this,

$data = array(
    'id' => 'UX102900',
    'name' => 'Kevin',
    'email' => 'kevinbutler@yahoo.com'
);

$this->session->set_userdata($data);

Or set userdata as one variable at a time,

$this->session->set_userdata('name', 'Jackson');

CodeIgniter: Get session data

To get/retrieve data which is already stored in session use,

$this->session->userdata('name');

The function returns FALSE if you try to access a session key that does not exist.

To retrieve all session data at once use the method,

$this->session->all_userdata();

Delete Session Data

Just like setting session data, you can unset them using unset_userdata() function while the session is still alive.

To delete one session variable at a time use,

$this->session->unset_userdata('username');

To delete multiple items at once pass the session keys as an array to unset_userdata() like this,

$data = array(
    'name' => '',
    'email' => ''
);

$this->session->unset_userdata($data);

Destroy Session in CodeIgniter

Use the method sess_destroy() to clear the current session.

$this->session->sess_destroy();

Once you run this, all your userdata will be cleared out and you won't get to access them and not even flashdata. So make sure to call it as the final step like when user logs out of the site.

That explains about handling sessions in codeigniter. Just make sure to set encryption key in config.php file even if you don't intend to use encrypted sessions. This will keep away the hackers from manipulating session data.

How to Find CodeIgniter Version You are Using?

On 8/29/2016 Be the first to comment!

Hi! In this tutorial we'll see how to find codeigniter version you are using. For pros it may sound basic but would be a challenge for someone getting started with code igniter framework.

A while back I was working in an application built on codeigniter. CI looks like an earlier release but I'm not sure about the exact version of codeigniter the application runs. So I started digging out and found the answer - turns out to be simple like I presumed. And I wish to share here the way I used to find codeigniter version for your reference.

how-to-find-codeigniter-version

Finding Codeigniter Version:


Method 1:

CodeIgniter makes the task easy and stores its current version number in a global constant named 'CI_VERSION'. It is defined in a core file which you can open and check out directly.

Just go to 'system' » 'core' » 'CodeIgniter.php' and look for the lines,


/**
 * CodeIgniter Version
 *
 * @var    string
 *
 */
    define('CI_VERSION', '3.0.0');

Here it is CodeIgniter 3 but may vary depending on the version you use.


Method 2:

Just as an alternate method to check codeigniter version, you can echo the constant value 'CI_VERSION' somewhere in codeigniter controller/view file.


<?php
    echo CI_VERSION;
?>

And that should print codeigniter version. Likewise you can easily find codeigniter version you run.

Read Also: How to Submit Form using AJAX in CodeIgniter

Don't Miss: CodeIgniter : Display Query Result in View

Contact Form

Name

Email *

Message *