article

Friday, August 2, 2013

CodeIgniter Form Validation

CodeIgniter Form Validation 

Controller 
application\controllers\welcome.php

<?php
class Welcome extends CI_Controller {
 public function index()
 {
  //Form Validation
  $this->load->helper(array('form', 'url'));
  $this->load->library('form_validation');
  $this->form_validation->set_rules('username', 'Username', 'required');
  $this->form_validation->set_rules('password', 'Password', 'required');
  $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
  $this->form_validation->set_rules('email', 'Email', 'required');
  //Validation Functions
  //$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]');
  //$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
  //$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
  //$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
  if ($this->form_validation->run() == FALSE)
  {
   $this->load->view('welcome_message');
  }
  else
  {
   $this->load->view('formsuccess');
  }
 }
}
application\views\welcome_message.php
<?php echo validation_errors(); ?>

<?php echo form_open('welcome'); ?>

<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />

<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />

<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

<div><input type="submit" value="Submit" /></div>

</form>
Showing Errors Individually
<h5>Username</h5>
<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

<h5>Password</h5>
<?php echo form_error('password'); ?>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />

<h5>Password Confirm</h5>
<?php echo form_error('passconf'); ?>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />

<h5>Email Address</h5>
<?php echo form_error('email'); ?>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

Insert – Edit – Delete Codeigniter


Insert – Edit – Delete Codeigniter 

Create Database

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `username` varchar(15) NOT NULL,
  `password` text NOT NULL,
  `fullname` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
)

Setup Controller

application\controllers\user.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{ 
     /**
     * The __construct function is called so that I don't have to load the model each and every time.
     * And any change while refactoring or something else would mean change in only one place.
     */
    function __construct() {
        parent::__construct();
        $this->load->model('Model_user');
  $this->load->library('form_validation');
        $this->load->helper('form');
    }
 
    function index(){
        $data['query'] = $this->Model_user->getAll();
        $this->load->view('view_user/input',$data);
    }
 function submit(){
        if ($this->input->post('submit')){
                         
            if ($this->input->post('id')){
                $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
                $this->form_validation->set_rules('password', 'Password', 'matches[passconf]');
                $this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]');
                 
                if ($this->form_validation->run() == FALSE){
                    $data['id'] = $this->input->post('id');
                    $data['username'] = set_value('username');
                    $data['fullname'] = set_value('fullname');
                    $this->load->view('view_user/edit',$data);
                }else{
                    $this->Model_user->update();
            redirect('view_user/index');
        }  
            }else{
                $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
                $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
                $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
                $this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]');
             
        if ($this->form_validation->run() == FALSE){
                        $data['query'] = $this->Model_user->getAll();
                        $this->load->view('view_user/input',$data);
                }else{
              $this->Model_user->save();
            redirect('user/index');
        }
      }
        }
    }
     
    function edit(){ 
    $id=$this->uri->segment(3);
    $data['result']=$this->Model_user->getUser($id);
     
    if (empty($id) or count($data['result'])==0 ){
        redirect('user/index');
    }else{   
        $result=$this->Model_user->getUser($id);
        $data['id'] = $result['id'];
        $data['username'] = $result['username'];
            $data['fullname'] = $result['fullname'];
        $this->load->view('view_user', $data);
    }   
  }
   
  function delete($id){
    $this->db->delete('user', array('id' => $id));
        redirect('user/index');
  }
}
Model application\models\Model_user.php
<?php
class Model_user extends CI_Model{
     
 function getAll(){
        $this->db->select('id,username,fullname');
                $this->db->from('users');
                $this->db->limit(10);
                $this->db->order_by('id','ASC');
                $query = $this->db->get();
 
                return $query->result();
    }
     
    function getUser($id){
    $this->db->where('id', $id);
    $query = $this->db->get('users');
     
    return $query->row_array();
    }
     
    function save(){
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $fullname = $this->input->post('fullname');
    $data = array(
      'username'=>$username,
      'password'=>md5($password),
      'fullname'=>$fullname
    );
    $this->db->insert('users',$data);
  }
   
  function update(){
    $id   = $this->input->post('id');
        $username = $this->input->post('username');
        $password = $this->input->post('password');
    $fullname = $this->input->post('fullname');
    if ($password==''){
        $data = array(
      'username'=>$username,
      'fullname'=>$fullname
    );
    }else{
        $data = array(
      'username'=>$username,
      'password'=>md5($password),
      'fullname'=>$fullname
    );
    }
     
    $this->db->where('id',$id);
    $this->db->update('users',$data);   
  }
}
View application\views\view_user\input.php
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Data User</title>
  </head>
  <body>
    <div id="form_input" title="Input / Edit Data">
      <table>
        <?php echo validation_errors(); ?>
        <?php echo form_open('user/submit'); ?>
        <tr >
            <td> <?php echo form_label('User Name : '); ?></td>
            <td> <?php echo form_input('username',set_value('username'),'id="username"'); ?></td>
        </tr>
        <tr>
            <td> <?php echo form_label('Password : ');?> </td>
            <td> <?php echo form_password('password','','id="password"'); ?></td>
        </tr>
         <tr>
            <td> <?php echo form_label('Repeat Password : ');?> </td>
            <td> <?php echo form_password('passconf','','id="passconf"'); ?></td>
        </tr>
        <tr>
            <td> <?php echo form_label('Full Name : ');?> </td>
            <td> <?php echo form_input('fullname', set_value('fullname'),'id="fullname"'); ?></td>
        </tr>
        <tr>
                <td><?php echo form_submit('submit','Save')?>
        </tr>
      </table>
      </div>
      <div id="show">
        <?php $this->load->view('view_user/show'); ?>
    </div>
    </div>
  </body>
</html>
application\views\view_user\show.php
<?php
    if (isset($query) && count($query) > 0){
    ?>
    <h1>Data User</h1>
    <table width="400" border="1">
    <tr >
     <th>No</th>
     <th>Username</th>
     <th>Fullname</th>
     <th>Edit</th>
     <th>Delete</th>
 </tr>
 <?php
 $i=0;
 foreach ($query as $row){
 $i++;
 echo "<tr class=\"record\">";
 echo    "<td>$i</td>";
 echo    "<td>$row->username</td>";
 echo    "<td>$row->fullname</td>";
 echo    "<td><a href=".base_url()."index.php/user/edit/$row->id>Edit</a></td>";
 echo    "<td><a href=".base_url()."index.php/user/delete/$row->id>Delete</a></td>";
 echo  "</tr>";
 }
 ?>
</table>
<?php
    }
?>

Simple Login with CodeIgniter in PHP

Simple Login with CodeIgniter in PHP 

 Create the database

CREATE TABLE `users` (
 `id` tinyint(4) NOT NULL AUTO_INCREMENT,
 `username` varchar(10) NOT NULL,
 `password` varchar(100) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

insert into users (username, password) values ('admin', MD5('password'));
 
Configure CodeIgniter 

application/config/database.php 
 
Default Controller
application/config/routes.php 
call landing controller login
$route['default_controller'] = "login";
 
Default Libraries 
application/config/autoload.php
handle user sessions, and also the URL helper for internal link generation
$autoload['libraries'] = array('database','session');
$autoload['helper'] = array('url'); 

Encryption Key
application/config/config.php
$config['encryption_key'] = 'REALLY_LONG_NUMBER';
 
The Code
 
User Model (application/models/user.php) 

<?php
Class User extends CI_Model
{
 function login($username, $password)
 {
   $this -> db -> select('id, username, password');
   $this -> db -> from('users');
   $this -> db -> where('username', $username);
   $this -> db -> where('password', MD5($password));
   $this -> db -> limit(1);

   $query = $this -> db -> get();

   if($query -> num_rows() == 1)
   {
     return $query->result();
   }
   else
   {
     return false;
   }
 }
}
?>
Login Controller (application/controllers/login.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   $this->load->helper(array('form'));
   $this->load->view('login_view');
 }

}

?>
Login View (application/views/login_view.php)
   <h1>Simple Login with CodeIgniter</h1>
   <?php echo validation_errors(); ?>
   <?php echo form_open('verifylogin'); ?>
     <label for="username">Username:</label>
     <input type="text" size="20" id="username" name="username"/>
     <br/>
     <label for="password">Password:</label>
     <input type="password" size="20" id="passowrd" name="password"/>
     <br/>
     <input type="submit" value="Login"/>
   </form>
VerifyLogin Controller (application/controllers/verifylogin.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
 }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

   $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
   $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.  User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
     //Go to private area
     redirect('home', 'refresh');
   }

 }

 function check_database($password)
 {
   //Field validation succeeded.  Validate against database
   $username = $this->input->post('username');

   //query the database
   $result = $this->user->login($username, $password);

   if($result)
   {
     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'id' => $row->id,
         'username' => $row->username
       );
       $this->session->set_userdata('logged_in', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'Invalid username or password');
     return false;
   }
 }
}
?>
Home Controller (application/controllers/home.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
class Home extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   if($this->session->userdata('logged_in'))
   {
     $session_data = $this->session->userdata('logged_in');
     $data['username'] = $session_data['username'];
     $this->load->view('home_view', $data);
   }
   else
   {
     //If no session, redirect to login page
     redirect('login', 'refresh');
   }
 }

 function logout()
 {
   $this->session->unset_userdata('logged_in');
   session_destroy();
   redirect('home', 'refresh');
 }

}

?>
Home Page View (application/views/home_view.php)
<html>
 <head>
   <title>Simple Login with CodeIgniter - Private Area</title>
 </head>
 <body>
   <h1>Home</h1>
   <h2>Welcome <?php echo $username; ?>!</h2>
   <a href="home/logout">Logout</a>
 </body>
</html>

How to enable or disable an anchor using jQuery

How to enable or disable an anchor using jQuery To prevent an anchor from following the specified href
$(document).ready(function() {
    $('a.something').click(function(e) {
        e.preventDefault();
    });
});

Passing array of checkbox values to php through jQuery

Passing array of checkbox values to php through jQuery 
 
//index.hmtl
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
                function doit() {
                        var p=[];
                        $('input.cb').each( function() {
                                if($(this).attr('checked')) {
                                        p.push($(this).attr('rel'));
                                }
                        } );
                        $.ajax( {
                                url:'process.php',
                                type:'POST',
                                data: {list:p},
                                success: function(res) {
                                        alert(res);
                                }
                        });
                }
        </script>

        <input type="checkbox" class="cb" rel="1"></input>Test 1<br />
        <input type="checkbox" class="cb" rel="2"></input>Test 2<br />
        <input type="checkbox" class="cb" rel="3"></input>Test 3<br />
        <a href="javascript:void(0)" onclick="doit()">Click</a>
//process.php
<?php
print_r(@$_POST['list']);
?>

Tuesday, July 30, 2013

Delete Confirmation using Javascript

Delete Confirmation using Javascript 
 
<script>
function confirmDelete()
{
    return confirm("Are you sure you wish to delete this entry?");
}
</script>
<a href="?action=delete&id=3" onclick="return confirmDelete();"> Delete this entry</a>

PHP Tutorial: Classes and OOP

PHP Tutorial: Classes and OOP 

 
<?php
//PHP Tutorial: Classes and OOP
//The first thing you do is to define the class:
class cow
{
}
//Next, we'll create our first function - this is defined exactly the same as if you were not using classes:
// First we define the class
class cow
{
    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo';
        return $sound;
    }
}
//create the new class object 'in' a variable
// Create new cow object
$daisy = new cow;
//then call the moo() function
echo $daisy->moo();

//If you put this code together then, you will get something like this:
// First we define the class
class cow
{
    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo';
        return $sound;
    }
}
// Create new cow object
$daisy = new cow;
echo $daisy->moo();

//Ex. more functions
// First we define the class
class cow
{
    var $eaten;

    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo<br />';
        return $sound;
    }
    function eat_grass($colour)
    {
        if ($colour == 'green')
        {
            // cow is happy
            $this->eaten = true;
            return $this->moo();
        }
    }

    function make_milk()
    {
        if ($this->eaten)
        {
            return 'Milk produced<br />';
        }
        else
        {
            return 'cow has not eaten yet<br />';
        }
    }
}

//call these functions and try out the new class
// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();
echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced

//final version
// First we define the class
class cow
{
    var $eaten;

    // Define the function moo() - no parameters    
    function moo()
    {
        // Define the variable
        $sound = 'Moooooo<br />';
        return $sound;
    }
    function eat_grass($colour)
    {
        if ($colour == 'green')
        {
            // cow is happy
            $this->eaten = true;
            return $this->moo();
        }
    }

    function make_milk()
    {
        if ($this->eaten)
        {
            return 'Milk produced<br />';
        }
        else
        {
            return 'cow has not eaten yet<br />';
        }
    }
}

// Create the cow object daisy
$daisy = new cow;
echo $daisy->moo();

echo $daisy->make_milk(); // Cow has not eaten yet
$daisy->eat_grass('green');
echo $daisy->make_milk(); // Milk produced
?>

Saturday, July 27, 2013

Style a Select Box Using CSS

Style a Select Box Using CSS
 
<style>
.styled-select select {
   background: transparent;
   width: 268px;
   padding: 5px;
   font-size: 16px;
   line-height: 1;
   border: 0;
   border-radius: 0;
   height: 34px;
   -webkit-appearance: none;
   }
   .styled-select {
   width: 240px;
   height: 34px;
   overflow: hidden;
   background: url(down_arrow_select.jpg) no-repeat right #ddd;
  
   display:block;font-size:16px;outline:0 none;padding:.4em;text-shadow:0 1px 0 #fff;-moz-border-radius:.6em;-webkit-border-radius:.6em;border-radius:.6em;border:1px solid #aaa;color:#333;text-shadow:0 1px 0 #fff;
   }
</style>
<div class="styled-select">
   <select>
      <option>Male</option>
      <option>Female</option>
   </select>
</div>

Friday, July 26, 2013

PHP, jQuery and MySQL Search

PHP, jQuery and MySQL Search
//index.html
<style>
body{ font-family:Arial, Helvetica, sans-serif; }
*{ margin:0;padding:0; }
#container { margin: 0 auto; width: 600px; }
a { color:#DF3D82; text-decoration:none }
a:hover { color:#DF3D82; text-decoration:underline; }
ul.update { list-style:none;font-size:1.1em; margin-top:10px }
ul.update li{ height:30px; border-bottom:#dedede solid 1px; text-align:left;}
ul.update li:first-child{ border-top:#dedede solid 1px; height:30px; text-align:left; }
#flash { margin-top:20px; text-align:left; }
#searchresults { text-align:left; margin-top:20px; display:none; font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#000; }
.word { font-weight:bold; color:#000000; }
#search_box { padding:4px; border:solid 1px #666666; width:300px; height:30px; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; }
.search_button { border:#000000 solid 1px; padding: 6px; color:#000; font-weight:bold; font-size:16px;-moz-border-radius: 6px;-webkit-border-radius: 6px; }
.found { font-weight: bold; font-style: italic; color: #ff0000; }
h2 { margin-right: 70px; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $(".search_button").click(function() {
        // getting the value that user typed
        var searchString    = $("#search_box").val();
        // forming the queryString
        var data            = 'search='+ searchString;
         
        // if searchString is not empty
        if(searchString) {
            // ajax call
            $.ajax({
                type: "POST",
                url: "do_search.php",
                data: data,
                beforeSend: function(html) { // this happens before actual call
                    $("#results").html('');
                    $("#searchresults").show();
                    $(".word").html(searchString);
               },
               success: function(html){ // this happens after we get results
                    $("#results").show();
                    $("#results").append(html);
              }
            });   
        }
        return false;
    });
});
</script>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
    <input type="text" name="search" id="search_box" class='search_box'/>
    <input type="submit" value="Search" class="search_button" /><br />
</form>
</div>     
<div>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>
</div>
</div>
//do_search.php
<?php
//if we got something through $_POST
if (isset($_POST['search'])) {
    // here you would normally include some database connection
    include('db.php');
    $db = new db();
    // never trust what user wrote! We must ALWAYS sanitize user input
    $word = mysql_real_escape_string($_POST['search']);
    $word = htmlentities($word);
    // build your search query to the database
    $sql = "SELECT title, url FROM pages WHERE content LIKE '%" . $word . "%' ORDER BY title LIMIT 10";
    // get results
    $row = $db->select_list($sql);
    if(count($row)) {
        $end_result = '';
        foreach($row as $r) {
            $result         = $r['title'];
            // we will use this to bold the search word in result
            $bold           = '<span class="found">' . $word . '</span>';   
            $end_result     .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';           
        }
        echo $end_result;
    } else {
        echo '<li>No results found</li>';
    }
}
?>

Username availability check using PHP and jQuery

Username availability check using PHP and jQuery
 
<?php

/* CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`username` varchar(150) NOT NULL,
`email` varchar(100) NOT NULL',
`pass` varchar(100)  NOT NULL',
PRIMARY KEY (`id`)
) */
//Username availability check using PHP and jQuery
//if we got something through $_POST
if (isset($_POST['user'])) {
    // here you would normally include some database connection
    include('db.php');
    $db = new db();
    // never trust what user wrote! We must ALWAYS sanitize user input
    $username = mysql_real_escape_string($_POST['user']);
    // build your query to the database
    $sql = "SELECT count(*) as num FROM users WHERE username = " . $username;
    // get results
    $row = $db->select_single($sql);
    if($row['num'] == 0) {
        echo 'Username <em>'.$username.'</em> is available!';
    } else {
        echo 'Username <em>'.$username.'</em> is already taken!';
    }
}
?>
<script>
$(function() {
$("#sub").click(function() {
    // getting the value that user typed
    var checkString    = $("#username_box").val();
    // forming the queryString
    var data            = 'user='+ checkString;
 
    // if checkString is not empty
    if(checkString) {
        // ajax call
        $.ajax({
            type: "POST",
            url: "do_check.php",
            data: data,
            beforeSend: function(html) { // this happen before actual call
                $("#results").html('');
            },
            success: function(html){ // this happen after we get result
                $("#results").show();
                $("#results").append(html);
            }
        });
}
return false;
});
});
</script>
<form action="do_check.php" method="post">
    <input id="username_box" class="search_box" name="username" type="text" />
    <input id="sub" type="submit" value="Check" />
</form>

Thursday, July 25, 2013

Using Sessions in WordPress Plugins

Using Sessions in WordPress Plugins 

In your theme/plugin

Add the next piece of code to your functions.php or plugin file to enable sessions:

/**
 * init_sessions()
 *
 * @uses session_id()
 * @uses session_start()
 */
function init_sessions() {
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'init_sessions');

PHP Multiple Atachment Send

PHP Multiple Atachment Send 


E-mail with Attachment
 <?php
if ($_SERVER['REQUEST_METHOD']=="POST"){

   // we'll begin by assigning the To address and message subject
   $to="somebody@example.com";
   $subject="E-mail with attachment";

   // get the sender's name and email address
   // we'll just plug them a variable to be used later
   $from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";

   // generate a random string to be used as the boundary marker
   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

   // now we'll build the message headers
   $headers = "From: $from\r\n" .
   "MIME-Version: 1.0\r\n" .
      "Content-Type: multipart/mixed;\r\n" .
      " boundary=\"{$mime_boundary}\"";

   // here, we'll start the message body.
   // this is the text that will be displayed
   // in the e-mail
   $message="This is an example";

   // next, we'll build the invisible portion of the message body
   // note that we insert two dashes in front of the MIME boundary 
   // when we use it
   $message = "This is a multi-part message in MIME format.\n\n" .
      "--{$mime_boundary}\n" .
      "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
      "Content-Transfer-Encoding: 7bit\n\n" .
   $message . "\n\n";

   // now we'll process our uploaded files
   foreach($_FILES as $userfile){
      // store the file information to variables for easier access
      $tmp_name = $userfile['tmp_name'];
      $type = $userfile['type'];
      $name = $userfile['name'];
      $size = $userfile['size'];

      // if the upload succeded, the file will exist
      if (file_exists($tmp_name)){

         // check to make sure that it is an uploaded file and not a system file
         if(is_uploaded_file($tmp_name)){
  
            // open the file for a binary read
            $file = fopen($tmp_name,'rb');
  
            // read the file content into a variable
            $data = fread($file,filesize($tmp_name));

            // close the file
            fclose($file);
  
            // now we encode it and split it into acceptable length lines
            $data = chunk_split(base64_encode($data));
         }
  
         // now we'll insert a boundary to indicate we're starting the attachment
         // we have to specify the content type, file name, and disposition as
         // an attachment, then add the file content.
         // NOTE: we don't set another boundary to indicate that the end of the 
         // file has been reached here. we only want one boundary between each file
         // we'll add the final one after the loop finishes.
         $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$type};\n" .
            " name=\"{$name}\"\n" .
            "Content-Disposition: attachment;\n" .
            " filename=\"{$fileatt_name}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n";
      }
   }
   // here's our closing mime boundary that indicates the last of the message
   $message.="--{$mime_boundary}--\n";
   // now we just send the message
   if (@mail($to, $subject, $message, $headers))
      echo "Message Sent";
   else
      echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" 
   enctype="multipart/form-data" name="form1">
   <p>From name: <input type="text" name="fromname"></p>
   <p>From e-mail: <input type="text" name="fromemail"></p>
   <p>File: <input type="file" name="file1"></p>
   <p>File: <input type="file" name="file2"></p>
   <p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>

Sanitize Input Form

Sanitize Input Form

 
<?php
include('connect.php');
$conn = db_connect();
 
 function cleanInput($input) {
  $search = array(
   '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
   '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
   '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
   '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
 );
  $output = preg_replace($search, '', $input);
  return $output;
 }

?>
<?
if(isset($_POST["submit"]))
{
 $_username = cleanInput($_POST["_username"]);
 $_password = md5($_POST["_password"]);  
 $sql_insert = "INSERT INTO tbl_admin(_username, _password) VALUES ('$_username', '$_password')";
 $result = mysql_query($sql_insert);
 echo "records save"; 
 //echo "<script>
 //   window.location='index.php';
 //    </script>";
 //
}
?>
<div style="padding-left:50px; font-weight:bold; font-size:18px; margin-bottom:20px; color:#ffffff">
 ADD NEW Users
</div>
<form name="subjadd" action="" method="post">
 <table width="96%" border="0" cellspacing="3" cellpadding="4">
  <tr>
   <th>User name:</th>
   <td><input name="_username" type="text" size="40"></td>
  </tr>
  <tr>
   <th>Password</th>
   <td><input name="_password" type="text" size="40"></td>
  </tr>
  <tr>
   <th></th>
   <td>
    <input type="submit" name="submit" value="Add New!">
</td>
  </tr>
 </table>
</form>

Public, Private and Protected - PHP OOP

Public, Private and Protected - PHP OOP 

Example 
 
<?php
//Public Visibility in PHP Classes
//Public methods or variables can be accessible from anywhere. It can be accessible from using object(outside the class), or inside the class, or in child class.
class test
{
public $abc;
public $xyz;
public function xyz()
{
}
}

$objA = new test();
echo $objA->abc;//accessible from outside
$objA->xyz();//public method of the class test
?>

<?php
//Private Visibility in PHP Classes
//only be accessible withing the class. Private visibility in php classes is used when you do not want your property or function to be exposed outside the class.
Class test
{
public $abc;
private $xyz;
public function pubDo($a)
{
echo $a;
}
private function privDo($b)
{
echo $b;
}
public function pubPrivDo()
{
$this->xyz = 1;
$this->privDo(1);
}
}
$objT = new test();
$objT->abc = 3;//Works fine
$objT->xyz = 1;//Throw fatal error of visibility
$objT->pubDo("test");//Print "test"
$objT->privDo(1);//Fatal error of visibility
$objT->pubPrivDo();//Within this method private function privDo and variable xyz is called using $this variable.
?>


<?php
//Protected Visibility in PHP Classes
//useful in case of inheritance and interface. Protected method or variable can be accessible either within class or child class.
class parent
{
protected $pr;
public $a
protected function testParent()
{
echo this is test;
}
}
class child extends parent
{
public function testChild()
{
$this->testParent(); //will work because it
}
}
$objParent = new parent();
$objParent->testParent();//Throw error
$objChild = new Child();
$objChild->setChild();//work because test child will call test parent.
?>

Saturday, July 13, 2013

Clearing File Input Values

Clearing File Input Values


 
<script type="text/javascript">
        function clearFileInput( id )
        {
            var elem = document.getElementById( id );
            elem.parentNode.innerHTML = elem.parentNode.innerHTML;
        }
    </script>

    <form method="post" enctype="multipart/form-data">
        <input type="file" name="myFile" id="fileInput1" />
        <input type="submit" name="s" value="Upload" />
    </form>
    <a href="javascript:clearFileInput( 'fileInput1' );">Clear File Input Value</a>

Get URL Parameters Using Javascript

Get URL Parameters Using Javascript

 
function getparamurl( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

var get_param = getparamurl('getid');
alert(get_param);
http://tutorial101.blogspot.com/index.html?getid=123

Tuesday, June 18, 2013

Validate password strength using jQuery

Validate password strength using jQuery

 
<style type="text/css">
#register {
    margin-left:100px;
}
 #register label{
    margin-right:5px;
}
 #register input {
    padding:5px 7px;
    border:1px solid #d5d9da;
    box-shadow: 0 0 5px #e8e9eb inset;
    width:250px;
    font-size:1em;
    outline:0;
}
 #result{
    margin-left:5px;
}
 #register .short{
    color:#FF0000;
}
 #register .weak{
    color:#E66C2C;
}
 #register .good{
    color:#2D98F3;
}
 #register .strong{
    color:#006400;
}
 </style>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function() {
  
    $('#password').keyup(function(){
        $('#result').html(checkStrength($('#password').val()))
    }) 
  
    function checkStrength(password){
  
    //initial strength
    var strength = 0
  
    //if the password length is less than 6, return message.
    if (password.length < 6) {
        $('#result').removeClass()
        $('#result').addClass('short')
        return 'Too short'
    }
  
    //length is ok, lets continue.
  
    //if length is 8 characters or more, increase strength value
    if (password.length > 7) strength += 1
  
    //if password contains both lower and uppercase characters, increase strength value
    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  strength += 1
  
    //if it has numbers and characters, increase strength value
    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))  strength += 1
  
    //if it has one special character, increase strength value
    if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/))  strength += 1
  
    //if it has two special characters, increase strength value
    if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,",%,&,@,#,$,^,*,?,_,~])/)) strength += 1
  
    //now we have calculated strength value, we can return messages
  
    //if value is less than 2
    if (strength < 2 ) {
        $('#result').removeClass()
        $('#result').addClass('weak')
        return 'Weak'
    } else if (strength == 2 ) {
        $('#result').removeClass()
        $('#result').addClass('good')
        return 'Good'
    } else {
        $('#result').removeClass()
        $('#result').addClass('strong')
        return 'Strong'
    }
}
});
</script>
 <form id="register">
    <label for="password">Password:</label>
    <input name="password" id="password" type="password"/>
    <span id="result"></span>
</form>

Form validations with Javascript and HTML5

Form validations with Javascript and HTML5


Javascript Form

<script type="text/javascript">
function send(){
if(document.dataform.tx_name.value=="" || document.dataform.tx_name.value.length < 8)
{
alert( "Insert your name with more than 8 chars!" );
document.dataform.tx_name.focus();
return false;
}
if( document.dataform.tx_email.value=="" || document.dataform.tx_email.value.indexOf('@')==-1 || document.dataform.tx_email.value.indexOf('.')==-1 )
{
alert( "Insert an valid e-mail adress!" );
document.dataform.tx_email.focus();
return false;
}
if (document.dataform.tx_message.value=="")
{
alert( "Insert your message!" );
document.dataform.tx_message.focus();
return false;
}
if (document.dataform.tx_message.value.length < 50 )
{
alert( "Is necessary to use more than 50 chars in the message field!" );
document.dataform.tx_message.focus();
return false;
}
return true;
}
</script>
<form action="#" method="post" name="dataform" onSubmit="return send();" >
  <table width="588" border="0" align="center" >
    <tr>
      <td width="118"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">Name:</font></td>
      <td width="460">
        <input name="tx_name" type="text" class="formbutton" id="tx_name" size="52" maxlength="150">
      </td>
    </tr>
    <tr>
      <td><font size="1" face="Verdana, Arial, Helvetica, sans-serif">E-mail:</font></td>
      <td><font size="2">
        <input name="tx_email" type="text" id="tx_email" size="52" maxlength="150" class="formbutton">
      </font></td>
    </tr>
    <tr>
      <td><font face="Verdana, Arial, Helvetica, sans-serif"><font size="1">Message<strong>:</strong></font></font></td>
      <td rowspan="2"><font size="2">
        <textarea name="tx_message" cols="50" rows="8" class="formbutton" id="tx_message" input ></textarea>
      </font></td>
    </tr>
    <tr>
      <td height="85"><p><strong><font face="Verdana, Arial, Helvetica, sans-serif"><font size="1">
      </font></font></strong></p></td>
    </tr>
    <tr>
      <td height="22"></td>
      <td>
        <input name="Submit" type="submit"  class="formobjects" value="Send">
  
        <input name="Reset" type="reset" class="formobjects" value="Reset">
      </td>
    </tr>
  </table>
</form>   
HTML 5 Form
<form method="post" action="">
    <label for="name">Name: </label>
    <input id="name" type=text required name=name/>
<br />
    <label for="email">Email: </label>
    <input id="email" type=text required name=email/>
<input type=submit value="OK"/>
</form> 

Saturday, June 15, 2013

jQuery and ajax with Codeigniter

jQuery and ajax with Codeigniter

application\controllers\products.php
<?php
class Products extends CI_Controller{
 
 function __construct(){
  parent::__construct();
 }
 
 function index() {
        $this->load->view('products');
    }
 public function get_all_users(){

  $query = $this->db->get('products');
  if($query->num_rows > 0){
   $header = false;
   $output_string = '';
   $output_string .=  "<table border='1'>";
   foreach ($query->result() as $row){
    $name = $row->name;
    $output_string .= '<tr>';
    $output_string .= "<th>$name</th>"; 
    $output_string .= '</tr>';    
   }     
   $output_string .= '</table>';
  }
  else{
   $output_string = 'There are no results';
  }
   
  echo json_encode($output_string);
 }
 }
?>
application\views\products.php
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<button type='button' name='getdata' id='getdata'>Get Data.</button>
<div id='result_table'></div>
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
    $.ajax({
            url: '<?php echo base_url().'products/get_all_users';?>',
            type:'POST',
            dataType: 'json',
            success: function(output_string){
                    $('#result_table').append(output_string);
                } // End of success function of ajax form
            }); // End of ajax call 
 
});
</script>

Friday, June 14, 2013

Create a simple style css table

Create a simple style css table



 
<style>
.simple-style {border-top:1px solid #CFCFCF; border-left:1px solid #CFCFCF; border-right:0; border-bottom:0; width:100%;font-family: Arial, Helvetica, tahoma sans-serif; font-size:12px; line-height:1.6; color:#282828;}
.simple-style td, .simple-style th {border-right:1px solid #CFCFCF; border-bottom:1px solid #CFCFCF; text-align:center; padding:5px 0; width:20%;}
.simple-style th {background-color:#dedede; font-size:120%;text-shadow: 0 1px 0 #fff;}
.simple-style tr:nth-child(even) {background: #fff;}
.simple-style tr:nth-child(odd) {background: #F6F6F6;}
</style>
<div style="width:700px;">
<h3>SIMPLE STYLE TABLE</h3>
<table class="simple-style">
    <thead>
        <tr>
            <th scope="col">Country</th>
            <th scope="col">Area</th>
            <th scope="col">Official languages</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>United States of America</td>
            <td>9,826,630 km2</td>
            <td>English</td>
        </tr>
        <tr>
            <td>United Kingdom</td>
            <td>244,820 km2</td>
            <td>English</td>
        </tr>
        <tr>
            <td>India</td>
            <td>3,287,240 km2</td>
            <td>Hindi, English</td>
        </tr>
        <tr>
            <td>Canada</td>
            <td>9,984,670 km2</td>
            <td>English, French</td>
        </tr>
        <tr>
            <td>Germany</td>
            <td>357,021 km2</td>
            <td>German</td>
        </tr>
    </tbody>
</table>
</div>

Related Post