Pages

Regular expression in PHP (part 1)

Tuesday, September 11, 2012
We deal with at least one form on almost every project. So we need to validate this form. You can do the validation with javascript on the client side. But we also need to validate on the server side because user can turn off the javascript.

To do the form validation on the server side, we need to understand about the regular expression.

Let's start with the simple example.
<?php
$string = "webinone";
echo preg_match("/in/", $string);
?>
The above code will echo 1 because the characters "in" are found in our string.
The below code will echo 0.
<?php
$string = "webinone";
echo preg_match("/ni/", $string); //output: 0

echo preg_match("/IN/", $string); //output: 0
?>

Metacharacters

caret ^

Start of the string
<?php
$string = 'webinone';
echo preg_match("/^we/", $string); //output: 1

echo preg_match("/^eb/", $string); //output: 0
?>
The caret has another usage. I will show you in a moment.

dollor $

End of the string
<?php
$string = 'webinone';
echo preg_match("/one$/", $string); //output: 1

echo preg_match("/noe$/", $string); //output: 0
?>

Character Class []

If you code like [aeiou], it will return 1 when our string has one of the vowel.
<?php
$string = 'big';
echo preg_match("/[aeiou]/", $string); //Output: 1

$string1 = 'baig';
echo preg_match("/[aoiu]/", $string1); //Output: 1

$string2 = 'bag';
echo preg_match("/b[aoiu]g/", $string2); //Output: 1

$string3 = 'beg';
echo preg_match("/b[aoiu]g/", $string3); //Output: 0

$string4 = 'baog';
echo preg_match("/b[aoiu]g/", $string4); //Output: 0
?>
We used the caret ^ for the meaning of the start of the string. But if you use the caret ^ within the [], it means NOT.
<?php
$string = 'webinone';
if(preg_match("/[^a]/",$string))
{
 echo 'String has no a.';
}
?>
By the way if you use the $ withing [], it is not the end of string. It just a simple dollar sign and contains no special meaning within it.

We can use the - for the range of character class. [a-f] is equal to [abcdef].
<?php
$string = 'webinone';
echo preg_match("/[a-z]/", $string); //Output: 1

$string1 = 'WebInOne';
echo preg_match("/[a-z]/", $string1); //Output: 1

$string2 = 'WEBINONE';
echo preg_match("/[a-z]/", $string2); //Output: 0

$string3 = '12345';
echo preg_match("/[a-zA-Z]/", $string3); //Output: 0

$string4 = '12345';
echo preg_match("/[^0-9]/", $string4); //Output: 0
?>

Dot .

Any single character except new line (n).
<?php
$string = 'one';
echo preg_match("/./", $string); //Output: 1

$string1 = 'one';
echo preg_match("/[.]/", $string1); //Output: 0

$string2 = 'one';
echo preg_match("/o.e/", $string2); //Output: 1

$string3 = 'ons';
echo preg_match("/o.e/", $string3); //Output: 0

$string4 = 'onne';
echo preg_match("/o.e/", $string4); //Output: 0

$string5 = "ore";
echo preg_match("/o.e/", $string5); //Output: 1

$string6 = "one";
echo preg_match("/o.e/", $string6); //Output: 0
?>
 

Asterix *

a* means 0 or more of a. We need to see the little complicate example to know its usage.
<?php
$string = "<html>";
echo preg_match("/<[A-Za-z][A-Za-z0-9]*>/", $string); //Output: 1

$string1 = "<b>";
echo preg_match("/<[A-Za-z][A-Za-z0-9]*>/", $string1); //Output: 1

$string2 = "<h3>";
echo preg_match("/<[A-Za-z][A-Za-z0-9]*>/", $string2); //Output: 1

$string3 = "<3>";
echo preg_match("/<[A-Za-z][A-Za-z0-9]*>/", $string3); //Output: 0
?>
In the above example we use <[A-Za-z][A-Za-z0-9]*>. In this regex, < and > are literal characters. The first character class matches a letter. The second character class matches a letter or digit. The star repeats the second character class. Because we used the star, it's OK if the second character class matches nothing. So our regex will match a tag like <B>. When matching <HTML>, the first character class will match H. The star will cause the second character class to be repeated three times, matching T, M and L with each step.

Plus +

a+ mean one or more of a.
<?php
$string = "php";
echo preg_match("/ph+p/", $string); //Output: 1

$string1 = "phhp";
echo preg_match("/ph+p/", $string1); //Output: 1

$string2 = "pp";
echo preg_match("/ph+p/", $string2); //Output: 0

$string3 = "12345";
echo preg_match("/[a-z]+/", $string3); //Output: 0
?>

Question mark ?

a? Zero or one of a.
<?php
$string = "123456";
echo preg_match("/123-?456/", $string); //Output: 1

$string1 = "123-456";
echo preg_match("/123-?456/", $string1); //Output: 1

$string2 = "123--456";
echo preg_match("/123-?456/", $string2); //Output: 0
?>

Curly braces {}

a{3} Exactly 3 of a
a{3,} 3 or more of a
a{,3} Up to 3 of a
a{3,6} 3 to 6 of a

<?php
$string = "google";
echo preg_match("/go{2}gle/", $string); //Output: 1

$string1 = "gooogle";
echo preg_match("/go{2}gle/", $string1); //Output: 0

$string2 = "gooogle";
echo preg_match("/go{2,}gle/", $string2); //Output: 1

$string3 = "google";
echo preg_match("/go{,2}gle/", $string3); //Output: 0

$string4 = "google";
echo preg_match("/go{2,3}gle/", $string4); //Output: 1
?>

Subpattern ()

<?php
$string = "This is PHP.";
echo preg_match("/^(This)/", $string); //Output: 1

$string1 = "That is PHP.";
echo preg_match("/^(This)/", $string1); //Output: 0

$string2 = "That is PHP.";
echo preg_match("/^([0-9])/", $string2); //Output: 0

$string3 = "7 is lucky number.";
echo preg_match("/^([0-9])/", $string3); //Output: 1
?>

Logical Or |


<?php
$string = "This is PHP.";
echo preg_match("/^(This|That)/", $string); //Output: 1

$string1 = "That is PHP.";
echo preg_match("/^(This|That)/", $string1); //Output: 1
?>

Backslash /

Where we use backslash?
If you want to use these eleven metacharacters ^+*.?$()|[ as literal characters in your regex, we need to escape them with a backslash.
<?php
$string = 'webinone.net';
if(preg_match("/./",$string))
{
 echo 'String has dot.';
}
$string1 = 'webinone+net';
if(preg_match("/+/",$string1))
{
 echo 'String has + sign.';
}
?>

Now let's try the real world example. Below example is to test for the email validation. It is not a prefect one, but it will validate most common email address formats correctly.

Crate a blank document in your favourite editor and paste following code in your document. And then save as mail_regex.php in your www (in wamp) folder.
<html>
<head>
 <title>Mail text</title>
</head>
<body>
<?php
 if(isset($_POST['submit']))
 {
  $email = $_POST['email'];
  if(preg_match("/^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/", $email))
  echo "Valid mail";
  else
  echo "Not Valid";
 }
?>
<form method="post" action="mail_regex.php">
 <input type="text" name="email" id="email" size="30" />
 <input name="submit" type="submit" value="Submit"/>
</form>
</body>
</html>

Our regex pattern for the email address is like below:
^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$
As you know, email address are always in a particular format:

username @ domain . extension

For our username part we use

^[a-zA-Z0-9._%-]+

^ means our username must start with this character class [a-zA-Z0-9._%-].
+ follow by the character class so you must enter one or more of the previous character class.

For our domain part we use

[a-zA-Z0-9.-]+

Our domain name must present one or more of that character class.

And then we need to escape with the backslash to use the . as the literal character.

For the extension part we use

[a-zA-Z]{2,4}$

So your extension must present 2 to 4 of the previous character class.

Now you can create some of the regex patterns by yourself I think.

There are many other regex patterns in PHP. I will explain you the rest of other regex patterns in the part 2.

Ref:

phpro.org

regular-expressions.info
Read more ...

Navigation System or Template with PHP and jQuery

Thursday, May 24, 2012
In this tutorial I will explain you how to create a navigation system or dynamic menu system or simple template system by using php include function, $_SESSION and some jQuery function.

Below screenshot is our latest view.

In this tutorial we will create 7 files like below.

You can see demo here.

Demo

1. header.php - It is a header part of our template. It will also include main menu.
2. jquery.js - It is a jquery library file downloaded from jQuery and rename it as jquery.js.
3. style.css - It is a style sheet for our site.
4. index.php - It will load firstly when we run our site or it is our home page.
5. footer.php - It is a footer part of our template.
6. projects.php - It is a other content file.
7. about.php - It is another content file.

Our page source code will be look like this before using php include function.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<script type="text/javascript" src="jquery.js"></script>
<title>Home</title>
</head>

<body>
<div id="wrapper">

<div id="header">
 <h1>Your Site Name</h1>
</div><!-- end of header-->

<ul id="main_nav">
 <li><a id="home" href="index.php">Home</a></li>
 <li><a id="projects" href="projects.php">Projects</a></li>
 <li><a id="about" href="about.php">About Us</a></li>
</ul>

<div id="content">
 <h1>Welcome to our Site.</h1>
 Your content will be here.
</div>

<div id="footer">
 Created by <a href="http://www.webinone.net">WebInOne</a>
</div><!-- end of footer-->

</div><!-- end of wrapper-->
</body>
</html>
When we create a website, we will have many pages like above code. In every page, header part and footer part will be present. So we should create the separate file for this duplicate code as header.php and footer.php. The only thing we need to change is content part. So our index.php file will be look like this.

<?php
 include("header.php");
?>
<div id="content">
 <h1>Welcome to our Site.</h1>
 Your content will be here.
</div>
<?php
 include("footer.php");
?>

I will explain you about the header.php and footer.php in a moment. Now we need to add some code to our index.php to set the title and menu item dynamically by using php $_SESSION.
<?php
 session_start();
 $_SESSION['title']='Home';
 $_SESSION['menu']='home';
 include("header.php");
?>
<div id="content">
 <h1>Welcome to our Site.</h1>
 Your content will be here.
</div>
<?php
 include("footer.php");
?>

Our header.php will look like below. I also add some jquery code to highlight the current location on main menu.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<script type="text/javascript" src="jquery.js"></script>
<title><?php echo $_SESSION['title']; ?></title>
<script type="text/javascript">
 function getMenuVar()
 {
  var route=document.getElementById("for_current").value;
  return route;
 }
 $(document).ready(function() {
  route = getMenuVar();
  if (route == 'home') {
   $('#home').addClass('current');
  } else if (route == 'projects') {
   $('#projects').addClass('current');
  } else if (route == 'about') {
   $('#about').addClass('current'); 
  } else {
   $('#home').addClass('');
  }
 }); 
</script>
</head>
<body>
<div id="wrapper">

<div id="header">
 <h1>Your Site Name</h1>
</div><!-- end of header-->
 <input type="hidden" id="for_current" value="<?php echo $_SESSION['menu']; ?>" name="for_current" />
 <ul id="main_nav">
  <li><a id="home" href="index.php">Home</a></li>
  <li><a id="projects" href="projects.php">Projects</a></li>
  <li><a id="about" href="about.php">About Us</a></li>
 </ul>
As you see in above code, we show our title dynamically by using $_SESSION['title']. And I also add a hidden input field above the main navigation ul coed to echo our $_SESSION['menu']. To grab our menu data from this field, I create a javascript function named getMenuVar(). Because we need to use this data in our jquery code to set the css current class in our main menu dynamically.

Below is our footer.php.
<div id="footer">
 Created by <a href="http://www.webinone.net">WebInOne</a>
</div><!-- end of footer-->
</div><!-- end of wrapper-->
</body>
</html>

Below is our style.css.
*{
 margin:0px;
 padding:0px;
}
#wrapper{
 width: 960px;
 margin: 0 auto;
 background-color: #E9E9E9;
}
#header{
 height: 70px;
    padding-top:20px;
}
#main_nav {
 width: 100%;
 height:37px;
 background: #A0A0A4;
 margin: 0;
 padding: 0;
}
#main_nav li {
 list-style: none;
 float: left;
}
#main_nav li:first-child {
 margin-left: 10px;
}
#main_nav a {
 line-height: 100%;
 font-weight: bold;
 color: #fff;
 display: block;
 padding: 10px 15px;
 text-decoration: none;
 text-shadow: 0 -1px 0 rgba(0,0,0,.5);
}
#main_nav a:hover {
 color: #fff;
 background: #808080;
}
.current{
 color: #fff;
 background:#EC7117;
}
#content{
 min-height:100px;
 background:#FFFBF0;
 margin:0px;
}
#footer {
 clear: both;
 color: #ccc;
 height:50px;
 background:#A0A0A4;
}
#footer a {
 color: #fff;
}

Blow is our projects.php. We need to set our $_SESSION['title'] and $_SESSION['menu'].

<?php
 session_start();
 $_SESSION['title']='Projects';
 $_SESSION['menu']='projects';
 include("header.php");
?>
<div id="content">
 <h1>Our projects list</h1>
 Your projects will be here.
</div>
<?php
 include("footer.php");
?>

The latest file we need crate is about.php.

<?php
 session_start();
 $_SESSION['title']='About';
 $_SESSION['menu']='about';
 include("header.php");
?>
<div id="content">
 <h1>About Us</h1>
 About your company.
</div>
<?php
 include("footer.php");
?>

You can download entire source code here.
Download Source Code
Read more ...

Codeigniter Template Library for Wordpress Fun

Thursday, May 24, 2012
I am not only a Codeigniter fun but also Wordpress fun. So I try to crate a CI template library that look like Wordpress theme.

I have got this library and it will be used with the helper together.

By using this library, you can crate the themes like in Wordpress.

Requirement

Codeigniter 2.0.0 and above

Installing

Copy and paste below code in your new document and save as

./application/libraries/Template.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  /**
  * Template
  * 
  * Wordpress like template for CodeIgniter
  * 
  * @package  Template
  * @version  0.1.0
  * @author  TutsforWeb <http://tutsforweb.blogspot.comt>
  * @link   
  * @copyright  Copyright (c) 2011, TutsforWeb
  * @license  http://opensource.org/licenses/mit-license.php MIT Licensed
  * 
  */

  class Template
  {
   private $ci;
   private $tp_name;
   private $data = array();

   public function __construct() {
    $this->ci = &get_instance();
   }

   public function set($name='') {
    $this->tp_name = $name;
   }

   public function load($name = 'index') {
    $this->load_file($name);
   }

   public function get_header($name) {
    if(isset($name)) {
     $file_name = "header-{$name}.php";
     $this->load_file($file_name);
    }
    else {
     $this->load_file('header');
    }
   }

   public function get_sidebar($name) {
    if(isset($name)) {
     $file_name = "sidebar-{$name}.php";
     $this->load_file($file_name);
    }
    else {
     $this->load_file('sidebar');
    }
   }

   public function get_footer($name) {
    if(isset($name)) {
     $file_name = "footer-{$name}.php";
     $this->load_file($file_name);
    }
    else {
     $this->load_file('footer');
    }
   }

   public function get_template_part($slug, $name) {
    if(isset($name)) {
     $file_name = "{$slug}-{$name}.php";
     $this->load_file($file_name);
    }
    else{
     $this->load_file($slug);
    }
   }

   public function load_file($name)
   {
    if($this->get_data($name))
    {
     $data = $this->get_data($name);
     $this->ci->load->view($this->tp_name.'/'.$name,$data);
    }
    else {
     $this->ci->load->view($this->tp_name.'/'.$name);
    }
   }

   public function set_data($key, $data) {
    $this->data[$key] = $data;
   }

   public function get_data($key) {
    if(isset($this->data[$key])) {
     return $this->data[$key];
    }
    else {
     return false;
    }
   }
  }
?>
(or)
Download from below button and place that file to './application/libraries/' directory.
Download Source Code

Copy and paste below code in your new document and save as

./application/helpers/template_helper.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 /**
  * Template
  *
  * WordPress like template for CodeIgniter
  *
  * @package  Template
  * @subpackage Helpers
  * @version  0.1.0
  * @author  TutsforWeb <http://tutsforweb.blogspot.com>
  * @link   
  * @copyright  Copyright (c) 2011, TutsforWeb
  * @license  http://opensource.org/licenses/mit-license.php MIT Licensed
  *
  */
  
  if ( ! function_exists('get_header'))
  {
   function get_header($name=null)
   {
    $ci =& get_instance();
    return $ci->template->get_header($name);
   }
  }

  if ( ! function_exists('get_sidebar'))
  {
   function get_sidebar($name=null)
   {
    $ci =& get_instance();
    return $ci->template->get_sidebar($name);
   }
  }

  if ( ! function_exists('get_footer'))
  {
   function get_footer($name=null)
   {
    $ci =& get_instance();
    return $ci->template->get_footer($name);
   }
  }

  if ( ! function_exists('get_template_part'))
  {
   function get_template_part($slug, $name=null)
   {
    $ci =& get_instance();
    return $ci->template->get_template_part($slug, $name);
   }
  }
?>
(or)
Download from below button and place that file to './application/helpers/' directory.
Download Source Code

Loading Template

Then open your autoload.php from your './application/config/' directory and set
$autoload['libraries'] = array('template');
and
$autoload['helper'] = array('template');
(or)
You can load Template just like any other library and helper in your controller using the $this->load->library function:
$this->load->library('template');
$this->load->helper('template');

Usage

Creating our theme

Now we can start to write our theme.
Create a folder in your views folder named default.
Let's start with header.php. Copy and paste the following code in you new document and save as header.php in your default theme folder like below.
./application/views/default/header.php
<html>
<head>
<title>Home</title>
</head>
<body>
<div id="pagewrap">
 <div id="header">
  <h1>Your Site Name</h1>
 </div><!-- /#header -->
Next one is footer. Copy and paste the following code in you new document and save as footer.php in your default theme folder like below.
./application/views/default/footer.php

 <div id="footer">
  <p>Design by <a href="http://tutsforweb.blogspot.com">Web In One</a></p>
 </div><!-- /#footer --> 

</div><!-- /#pagewrap -->
</body>
</html>

Next one is sidebar. Copy and paste the following code in you new document and save as footer.php in your default theme folder like below.
./application/views/default/sidebar.php

<div id="sidebar">
 <h2>This is side bar.</h2>
</div><!-- /#sidebar -->

Before we do not write index.php, I want to introduce you some function.
get_header();
get_footer();
get_sidebar();
If you call above function in your view file, it will load your header.php, footer.php and sidebar.php respectively from your theme folder. And then you can also call with the parameter like below.
get_header('primary');
get_footer('primary');
get_sidebar('left');
If you call like above, it will load your header-primary.php, footer-primary.php and sidebar-left.php respectively look like in Wordpress.

Now let's start our index file. Copy and paste the following code in you new document and save as index.php in your default theme folder like below.
./application/views/default/index.php
<?php get_header(); ?>
<div id="content">
 <h2>Content</h2>
  <p>This is content from index.</p>
</div><!--<div id="content">-->
<?php
get_sidebar(); 
get_footer();
?>

The last function for your view file is get_template_part(). It can call any other view file by writing like below.
get_template_part('about');
The above function will load the about.php from your theme folder.

You can also call with two parameter like below.
get_template_part('about','other');
The above function will load the about-other.php from your theme folder.

Controller

$this->template->set()

Firstly you need to set the theme name in your controller.
Assuming that you have tow themes like below.

./application/views/default/index.php
./application/views/default/header.php
./application/views/default/footer.php
./application/views/default/sidebar.php
./application/views/default/about.php
and
./application/views/newtheme/index.php
./application/views/newtheme/header.php
./application/views/newtheme/footer.php
./application/views/newtheme/sidebar.php
./application/views/newtheme/project.php

Now you have two themes named default and newtheme.
In your controller you need to set a theme you want to use like below.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller{
 public function __construct() {
  parent::__construct();
 }
 
    public function index() {
  $this->template->set('default');
 }
}
?>

$this->template->load()

Now you can load your theme.
If you load with no parameter, it will load index.php like below.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller{
 public function __construct() {
  parent::__construct();
 }
 
    public function index() {
  $this->template->set('default');
         $this->template->load();
 }
}
?>

If you load with the parameter, it will load the view file that you set as parameter as below.

$this->template->set('default');
$this->template->load('about');

$this->template->set_data()


If you want to pass your data from controller to view, you must use this function. Let's discuss how to use this function in your controller and in your view file.

Now we want to pass our title from our controller to view file. Below is controller syntax:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller{
 public function __construct(){
  parent::__construct();
 }

 public function index() {
  $this->template->set('default');
  $header_data['title'] = "TutsforWeb: Web design and developmetn tutorials";
  $this->template->set_data('header',$header_data);
  $this->template->load();
 }
}
?>
First parameter is your view file name.
You can you in your header.php view file as you used in CI view file like below.

<html>
<head>
 <title><?php echo $title; ?></title>
</head>
<body>
<div id="pagewrap">
 <div id="header">
  <h1>Your Site Name</h1>
 </div><!-- /#header -->

If you have any other tips, techniques or requirement, let us know in the comments.
Read more ...

Registration system with email verifying in PHP

Wednesday, May 23, 2012
In this tutorial I will show how to write a sign up form with email verification or confirmation in php. If your website use a registration form, you need to use email verification to reduce the spam and to make sure the email supplied belongs to that member.

In this tutorial I create a 7 file like below.

1. index.php - I write a registration form in this file.
2. configdb.php - to connect the database.
3. register.php - In this file, we will do form validation, saving user data to database and sending email to user for confirmation.
4. confirm.php - In this file, we will set the confirmation code to null if the user click the link from his email.
5. login.php - In this file, we will test whether the email and password is correct and confirmation code is null.
6. member.php - In this file, we will test whether the member is or not.
7. logout.php - In this file, we will unset the user session data.

Creating database table

We need to create a user table before writing our script. Import following SQL statement via phpMyAdmin or any other MySQL tool.
CREATE TABLE `user` (
`id` INT( 50 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 100 ) NOT NULL ,
`password` VARCHAR( 20 ) NOT NULL ,
`com_code` VARCHAR( 255 ) default NULL,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sing Up</title>
<style>
 label{
  width:100px;
  float:left;
 }
</style>
</head>
<body>
<?php 
 session_start();
 if(isset($_SESSION['error']))
 {
  echo '<p>'.$_SESSION['error']['username'].'</p>';
  echo '<p>'.$_SESSION['error']['email'].'</p>';
  echo '<p>'.$_SESSION['error']['password'].'</p>';
  unset($_SESSION['error']);
 }
?>
<div class="signup_form">
<form action="register.php" method="post" >
 <p>
  <label for="username">User Name:</label>
  <input name="username" type="text" id="username" size="30"/>
 </p>
 <p>
  <label for="email">E-mail:</label>
  <input name="email" type="text" id="email" size="30"/>
 </p>
 <p>
  <label for="password">Password:</label>
  <input name="password" type="password" id="password" size="30 "/>
 </p>
 <p>
  <input name="submit" type="submit" value="Submit"/>
 </p>
</form>
</div>
<p><a href="login.php">Login</a></p>
</body>
</html>
We use the PHP $_SESSIONvariable to show the form validation error that set in the register.php.

configdb.php

<?php
 $mysqli=mysqli_connect('localhost','dbusername','dbpassword','databasename') or die("Database Error");
?>

register.php

I divide this file into two parts to be clear when we discuss. In the first part, you will see the form validation.
<?php
session_start();
include('configdb.php');
if(isset($_POST['submit']))
{
 //whether the username is blank
 if($_POST['username'] == '')
 {
  $_SESSION['error']['username'] = "User Name is required.";
 }
 //whether the email is blank
 if($_POST['email'] == '')
 {
  $_SESSION['error']['email'] = "E-mail is required.";
 }
 else
 {
  //whether the email format is correct
  if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
  {
   //if it has the correct format whether the email has already exist
   $email= $_POST['email'];
   $sql1 = "SELECT * FROM user WHERE email = '$email'";
   $result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
   if (mysqli_num_rows($result1) > 0)
            {
    $_SESSION['error']['email'] = "This Email is already used.";
   }
  }
  else
  {
   //this error will set if the email format is not correct
   $_SESSION['error']['email'] = "Your email is not valid.";
  }
 }
 //whether the password is blank
 if($_POST['password'] == '')
 {
  $_SESSION['error']['password'] = "Password is required.";
 }
Firstly, we test whether the user is blank. And then whether the email is blank; if not, we also test whether the email format is correct. If the email format is correct, we will test whether this email has already exist. And then we will test whether the password is blank.
 //if the error exist, we will go to registration form
 if(isset($_SESSION['error']))
 {
  header("Location: index.php");
  exit;
 }
 else
 {
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = $_POST['password'];
  $com_code = md5(uniqid(rand()));

  $sql2 = "INSERT INTO user (username, email, password, com_code) VALUES ('$username', '$email', '$password', '$com_code')";
  $result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());

  if($result2)
  {
   $to = $email;
   $subject = "Confirmation from TutsforWeb to $username";
   $header = "TutsforWeb: Confirmation from TutsforWeb";
   $message = "Please click the link below to verify and activate your account. rn";
   $message .= "http://www.yourname.com/confirm.php?passkey=$com_code";

   $sentmail = mail($to,$subject,$message,$header);

   if($sentmail)
            {
   echo "Your Confirmation link Has Been Sent To Your Email Address.";
   }
   else
         {
    echo "Cannot send Confirmation link to your e-mail address";
   }
  }
 }
}
?>
In this part, we will test whether the error exit; if not, we will add the user data to our database table and will send a mail for email verifying.

confirm.php

<?php
 include('configdb.php');
 $passkey = $_GET['passkey'];
 $sql = "UPDATE user SET com_code=NULL WHERE com_code='$passkey'";
 $result = mysqli_query($mysqli,$sql) or die(mysqli_error());
 if($result)
 {
  echo '<div>Your account is now active. You may now <a href="login.php">Log in</a></div>';
}
 else
 {
  echo "Some error occur.";
 }
?>
This file will active when your click the confirmation link from his/her email. It will update the com_code field from our database table by setting to null. Because when we write our login page, we will also test whether the com_code field is null.

login.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<style>
 label{
  width:100px;
  float:left;
 }
</style>
</head>
<body>
<?php
 session_start();
 include('configdb.php');
 if(isset($_POST['submit']))
 {
  $email = trim($_POST['email']);
  $password = trim($_POST['password']);
  $query = "SELECT * FROM user WHERE email='$email' AND password='$password' AND com_code IS NULL";
  $result = mysqli_query($mysqli,$query)or die(mysqli_error());
  $num_row = mysqli_num_rows($result);
  $row=mysqli_fetch_array($result);
  if( $num_row ==1 )
         {
   $_SESSION['user_name']=$row['username'];
   header("Location: member.php");
   exit;
  }
  else
         {
   echo 'false';
  }
 }
?>
<div class="login_form">
<form action="login.php" method="post" >
 <p>
  <label for="email">E-mail:</label>
  <input name="email" type="text" id="email" size="30"/>
 </p>
 <p>
  <label for="password">Password:</label>
  <input name="password" type="password" id="password" size="30"/>
 </p>
 <p>
  <input name="submit" type="submit" value="Submit"/>
 </p>
</form>
</div>
</body>
</html>
If the form have been submitted, we will retrieve the data that is equal to the data supplied by user and com_code must also be null. If it is true, we will set the session variable.

member.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Member page</title>
</head>
<body>
<?php
 session_start();
 if($_SESSION['user_name'] == '')
 {
  header("Location: index.php");
  exit;
 }
 echo "Hi ".$_SESSION['user_name'];
?>
<a href="logout.php">Logout</a>
</body>
</html>
If the user has already logged in, our session variable will not be blank. If it is blank we will go back to index.php or registration form.

logout.php

<?php
 session_start();
 unset($_SESSION['user_name']);
 header('Location: index.php');
?>
Download Source Code
Read more ...

Date validation for Codeigniter 2

Wednesday, May 23, 2012
I wrote a tutorial here about the CI date. At that post I used the HTML <select> for the input of date. Sometime our client can want to use text box for the date input. We need the validation for this date. I have found this code from here. It is for CI 1.7.* and PHP 5.2.*. So I change some code for the CI 2.0.* and PHP 5.3.*.

To use, copy the class below into your application/libraries folder named MY_Form_validation.php, then in your controller use it like any other rule.

Form

This validation rule validates an input text box only right now.

<input type="text" name="date" value="<?php echo set_value('date'); ?>" size="10" />

Controller Usage


UK

$this->form_validation->set_rules('date', 'date', 'trim|required|valid_date[d/m/y,/]');

US

$this->form_validation->set_rules('date', 'date', 'trim|required|valid_date[m/d/y,/]');

Database

$this->form_validation->set_rules('date', 'date', 'trim|required|valid_date[y-m-d,-]');

Code


<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

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

 /**
 * @desc Validates a date format
 * @params format,delimiter
 * e.g. d/m/y,/ or y-m-d,-
 */
 function valid_date($str, $params)
 {
  // setup
  $CI =&get_instance();
  $params = explode(',', $params);
  $delimiter = $params[1];
  $date_parts = explode($delimiter, $params[0]);

  // get the index (0, 1 or 2) for each part
  $di = $this->valid_date_part_index($date_parts, 'd');
  $mi = $this->valid_date_part_index($date_parts, 'm');
  $yi = $this->valid_date_part_index($date_parts, 'y');

  // regex setup
  $dre =   "(0?1|0?2|0?3|0?4|0?5|0?6|0?7|0?8|0?9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)";
  $mre = "(0?1|0?2|0?3|0?4|0?5|0?6|0?7|0?8|0?9|10|11|12)";
  $yre = "([0-9]{4})";
  $red = ''.$delimiter; // escape delimiter for regex
  $rex = "/^[0]{$red}[1]{$red}[2]/";

  // do replacements at correct positions
  $rex = str_replace("[{$di}]", $dre, $rex);
  $rex = str_replace("[{$mi}]", $mre, $rex);
  $rex = str_replace("[{$yi}]", $yre, $rex);

  if (preg_match($rex, $str, $matches))
  {
   // skip 0 as it contains full match, check the date is logically valid
   if (checkdate($matches[$mi + 1], $matches[$di + 1], $matches[$yi + 1]))
   {
    return true;
   }
   else
   {
    // match but logically invalid
    $CI->form_validation->set_message('valid_date', "The date is invalid.");
    return false;
   }
  }

  // no match
  $CI->form_validation->set_message('valid_date', "The date format is invalid. Use {$params[0]}");
  return false;
 }

 function valid_date_part_index($parts, $search)
 {
  for ($i = 0; $i <= count($parts); $i++)
  {
   if ($parts[$i] == $search)
   {
    return $i;
   }
  }
 }
}
?>
`
Read more ...

jQuery Ajax form validation in Codeigniter

Sunday, May 20, 2012
This tutorial is part 2 of User Registration with Codeigniter. In the previous tutorial, we do the form validation in the sever side. In this tutorial, we will do the form validation by using the ajax technology. So user can know whether his/her form valid or not before submitting.

Requirement

CodeIgniter
jQuery

Our last screen shot


Create a folder named js in your root directory and then download the jQuery file below your js folder. Rename it as jquery.js. And then link this file in our header_view.php like following.
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.js"></script>

Editing registration_view file for ajax validation

Firstly I add the span class to the user_name input field to show our yes or no picture like following.
<p>
 <label for="user_name">User Name:</label>
<input type="text" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" /><span id="usr_verify" class="verify"></span>
</p>
And then add the following script to our registration_view.php.
<script type="text/javascript">
$(document).ready(function(){
 $("#user_name").keyup(function(){
  if($("#user_name").val().length >= 4)
  {
  $.ajax({
   type: "POST",
   url: "<?php echo base_url();?>index.php/user/check_user",
   data: "name="+$("#user_name").val(),
   success: function(msg){
    if(msg=="true")
    {
     $("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/yes.png')" });
    }
    else
    {
     $("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/no.png')" });
    }
   }
  });
  }
  else 
  {
   $("#usr_verify").css({ "background-image": "none" });
  }
 });
});
</script>
We use the jQuery keyup function to test whether the user already exit or not. Before we use the jQuey ajax, we need to test whether the user_name field val().length is greater than or equal 4. If the length is greater than or equal 4, we use the jQuery ajax function. In the url I give the function check_user. So in our controller, we must add that controller. Following is our check_user function. Add that function to our user controller.
public function check_user()
{
 $usr=$this->input->post('name');
 $result=$this->user_model->check_user_exist($usr);
 if($result)
 {
  echo "false";
  }
 else{
  echo "true";
  }
}
In the check_user() function, we set the $usr variable from our ajax data parameter. And then we call the model function check_user_exist. This function will return true if the user name already exits. It will return false if the user name does not exist. How do we echo for our ajax success function? So I echo the false if the user name already exits and true if the user name does not exit. We get this echoed data as a msg in the ajax success function. So we add the css background image as the yes.png if the msg is equal to true. Else we will add no.png.

Now we need to create the check_user_exist() model function. Add following function to our user_model model.
public function check_user_exist($usr)
{
 $this->db->where("username",$usr);
 $query=$this->db->get("user");
 if($query->num_rows()>0)
 {
  return true;
 }
 else
 {
  return false;
 }
}
The last thing we need to do is to add css class .verify for our image.
.verify
{
    margin-top: 4px;
    margin-left: 9px;
    position: absolute;
    width: 16px;
    height: 16px;
}
In my source code, I also add password and email validation. Download the source code and you can learn more.
Download Source Code
Read more ...

User Registration with Codeigniter

Sunday, May 20, 2012
In this tutorial, I will explain you user registration with CI. If you are a very newbies in CI, you can start by reading How to start with CI? or read this excellent article Everything You Need to Get Started With CodeIgniter.

If you have finished our previous tutorial, we can start this tutorial now. The CI classes we have to learn in this tutorial are session and form validation. I believe that you would be familiar with PHP session.

Requirement

Download the latest CI version from the following link.

CodeIgniter

Step 1:Configuration

Open application/config/database.php, and change the following database configuration to fit your mysql configuration.

$config['hostname'] = "localhost";

$config['username'] = "myusername";

$config['password'] = "mypassword";

$config['database'] = "mydatabase";

$config['dbdriver'] = "mysql";

 

Then open application/config/config.php

$config['base_url'] = 'http://localhost/ci_user';

$config['encryption_key'] = '1234';

 

Open application/config/autoload.php

$autoload['libraries'] = array('session','database');

and

$autoload['helper'] = array('url','form');

 

Open application/config/routes.php, change default controller to user controller as we’ll create later on this tutorial.

$route['default_controller'] = 'user';

Step 2:Creating User table

We need to create a table in our database. Import following SQL statement via phpMyAdmin or any other MySQL tool.
CREATE TABLE `user` (
`id` INT( 50 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 100 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB

Step 3:Creating our Controller

Create a blank document in the controller file (application -> controller) and name it user.php, in the document add all the following code.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
 public function __construct()
 {
  parent::__construct();
  $this->load->model('user_model');
 }
 public function index()
 {
  if(($this->session->userdata('user_name')!=""))
  {
   $this->welcome();
  }
  else{
   $data['title']= 'Home';
   $this->load->view('header_view',$data);
   $this->load->view("registration_view.php", $data);
   $this->load->view('footer_view',$data);
  }
 }
 public function welcome()
 {
  $data['title']= 'Welcome';
  $this->load->view('header_view',$data);
  $this->load->view('welcome_view.php', $data);
  $this->load->view('footer_view',$data);
 }
 public function login()
 {
  $email=$this->input->post('email');
  $password=md5($this->input->post('pass'));

  $result=$this->user_model->login($email,$password);
  if($result) $this->welcome();
  else        $this->index();
 }
 public function thank()
 {
  $data['title']= 'Thank';
  $this->load->view('header_view',$data);
  $this->load->view('thank_view.php', $data);
  $this->load->view('footer_view',$data);
 }
 public function registration()
 {
  $this->load->library('form_validation');
  // field name, error message, validation rules
  $this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[4]|xss_clean');
  $this->form_validation->set_rules('email_address', 'Your Email', 'trim|required|valid_email');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
  $this->form_validation->set_rules('con_password', 'Password Confirmation', 'trim|required|matches[password]');

  if($this->form_validation->run() == FALSE)
  {
   $this->index();
  }
  else
  {
   $this->user_model->add_user();
   $this->thank();
  }
 }
 public function logout()
 {
  $newdata = array(
  'user_id'   =>'',
  'user_name'  =>'',
  'user_email'     => '',
  'logged_in' => FALSE,
  );
  $this->session->unset_userdata($newdata );
  $this->session->sess_destroy();
  $this->index();
 }
}
?>
In the index() function,

if(($this->session->userdata('user_name')!=""))

the above code is equal to the following code in php.

if($_SESSION['user_name']!="")

It means that if the user_name is not equal to the null, this user have already logged in. So we will go to welcome() function. Else we will show registration from view.

You will understand next login() and thank() functions I think.

In the registration() function, firstly we load the form_validation library. And then we set the rules for our form field. The trim rule is equal to the php trim() function and you will understand the others I think. And then we run the form validation. If the result is false, we will go to index() function. Else we will add user data and will go to thank() function.

In the logout() function, we will unset and destroy the session data and will go to the index() function.

Step 4:Creating Model

Create a blank document in the model file (application -> model) and name it user_model.php, in the document add all the following code.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
 public function __construct()
 {
  parent::__construct();
 }
 function login($email,$password)
 {
  $this->db->where("email",$email);
  $this->db->where("password",$password);

  $query=$this->db->get("user");
  if($query->num_rows()>0)
  {
   foreach($query->result() as $rows)
   {
    //add all data to session
    $newdata = array(
      'user_id'  => $rows->id,
      'user_name'  => $rows->username,
      'user_email'    => $rows->email,
      'logged_in'  => TRUE,
    );
   }
   $this->session->set_userdata($newdata);
   return true;
  }
  return false;
 }
 public function add_user()
 {
  $data=array(
    'username'=>$this->input->post('user_name'),
    'email'=>$this->input->post('email_address'),
    'password'=>md5($this->input->post('password'))
  );
  $this->db->insert('user',$data);
 }
}
?>
In the login() function,

$this->db->where("email",$email);

$this->db->where("password",$password);

the above two line will produce the following query in MySQL:

WHERE email='$email' AND password='$password'

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

This above code will set our user data to the session variable.

Step 5:Designing our view files

Create a blank document in the views file (application -> views) and name it header_view.php, in the document add all the following code.
<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title><?php echo (isset($title)) ? $title : "My CI Site" ?> </title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/css/style.css" />
</head>
<body>
 <div id="wrapper">
Create a blank document in the views file (application -> views) and name it footer_view.php, in the document add all the following code.
<div id="footer">
  &copy; 2011 <a href="http://tutsforweb.blogspot.com/">TutforWeb</a> All Rights Reserved.
 </div><!-- <div class="footer">-->
 </div><!--<div id="wrapper">-->
</body>
</html>
Now let's create our registration view file.

I will use the tableless form design. It has some benefits:

1.Faster loading of pages

2.Efficiency

3.Consistency

4.SEO advantage

5.Layouts and design sophistication

6.Bandwidth efficiency

Create a blank document in the views file (application -> views) and name it registration_view.php, in the document add all the following code.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
 <?php echo form_open("user/login"); ?>
  <label for="email">Email:</label>
  <input type="text" id="email" name="email" value="" />
  <label for="password">Password:</label>
  <input type="password" id="pass" name="pass" value="" />
  <input type="submit" class="" value="Sign in" />
 <?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<div class="reg_form">
<div class="form_title">Sign Up</div>
<div class="form_sub_title">It's free and anyone can join</div>
 <?php echo validation_errors('<p class="error">'); ?>
 <?php echo form_open("user/registration"); ?>
  <p>
  <label for="user_name">User Name:</label>
  <input type="text" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" />
  </p>
  <p>
  <label for="email_address">Your Email:</label>
  <input type="text" id="email_address" name="email_address" value="<?php echo set_value('email_address'); ?>" />
  </p>
  <p>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" value="<?php echo set_value('password'); ?>" />
  </p>
  <p>
  <label for="con_password">Confirm Password:</label>
  <input type="password" id="con_password" name="con_password" value="<?php echo set_value('con_password'); ?>" />
  </p>
  <p>
  <input type="submit" class="greenButton" value="Submit" />
  </p>
 <?php echo form_close(); ?>
</div><!--<div class="reg_form">-->
</div><!--<div id="content">-->
In this view we echo our validation errors like below.

<?php echo validation_errors('<p>'); ?>

In our input fields, we use the below function.

<?php echo set_value('user_name'); ?>

Because of above function the original data will be show in the form, if there is an error after the validation rules. So we have only been dealing with errors.

Below code is thank_view.php and welcome_view.php.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
 <?php echo form_open("user/login"); ?>
  <label for="email">Email:</label>
  <input type="text" id="email" name="email" value="" />
  <label for="pass">Password:</label>
  <input type="password" id="pass" name="pass" value="" />
  <input type="submit" class="" value="Sign in" />
 <?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<h1>Thank!</h1>
</div><!--<div id="content">-->
<div class="content">
  <h2>Welcome Back, <?php echo $this->session->userdata('username'); ?>!</h2>
  <p>This section represents the area that only logged in members can access.</p>
  <h4><?php echo anchor('user/logout', 'Logout'); ?></h4>
</div><!--<div class="content">-->
We need some css code to design our registration form. Copy following code and paste your css>style.css.
@charset "utf-8";
/* CSS Document */
body{
background-color:#FFF;
font-family:Monaco,Consolas,'Lucida Grande','Lucida Console';
font-size:16px;
text-shadow:rgba(0,0,0,0.01) 0 0 0;
}
#wrapper{
width:960px;
margin:0 auto;
}
#content{
width:960px;
margin:5px;
float:left;
}
/************************************************/
.signup_wrap{
height:25px;
width:100%;
padding:5px;
background-color:#2A1FFF;
}
.signin_form{
float:right;
}
.signin_form input{
width:80px;
}
.reg_form{
width:460px;
padding:20px;
margin:0 auto;
border:3px solid #DFDFDF;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbd4e5));
background: -moz-linear-gradient(top,  #fff,  #cbd4e5);
filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff', endColorstr='#cbd4e5');
}
.form_title,
.form_sub_title{
font-size:20px;

font-family:"Lucida Grande",Tahoma,Verdana,Arial,sans-serif;
font-size:20px;
font-weight:bold;
}
.form_sub_title{
font-weight:normal;
padding:6px 0 15px 0;
}
.reg_form p{
width: 300px;
clear: left;
margin: 0;
padding: 5px 0 8px 0;
padding-left: 155px; /*width of left column containing the label elements*/
border-top: 1px dashed gray;
height: 1%;
}
.reg_form label{
font-weight: bold;
float: left;
margin-left: -155px; /*width of left column*/
width: 150px; /*width of labels. Should be smaller than left column (155px) to create some right margin*/
}
input{
padding:3px;
color:#333333;
border:1px solid #96A6C5;
margin-top:2px;
width:180px;
font-size:11px;
}
.greenButton{
width:auto;
margin:10px 0 0 2px;
padding:3px 4px 3px 4px;
color:white;
background-color:#589d39;
outline:none;
border:1px solid #006600;
font-weight:bold;
}
.greenButton:active{
background-color:#006600;
padding:4px 3px 2px 5px;
}
.error{
color:#F00;
}
#footer{
color:#fff;
padding-top:20px;
text-align:center;
background: #454546; 
height: 20px;
clear:both;
}
Now our form is finished. Don’t hesitate to ask me, if something goes wrong on your side.
In the next tutorial we will discuss jQuery Ajax with CI.
Download Source Code
Read more ...