Smtp email using CodeIgniter's Email library

Email_with_ci
We will be using email library  in the CodeIgniter  to send smtp email from GMAIL. Email library supports Mail, Sendmail and SMTP.

Email library makes sending smtp emails a piece of cake with various features like cc,bcc,multiple recipients ,html, attachments and many more.

So , here is what we are going to do in this post

a)     a)  Create a form where user will fill his name,email and message

b)      b) Send this email to admin just like contact us or feedback form using GMAIL

Email_codeigniter
In this post I will not go through all the initial process of configuring CodeIgniter , because I have already mentioned this in my previous posts .

Let’s start this tutorial with view. Create “email_view.php” in view folder , here will take name,email address and message from user .This is a very simple form

<html>

<head>

<title><?php echo $title ; ?></title>

<link href="<?php echo base_url()?>css/style.css" rel="stylesheet" type="text/css">

</head>

<body>

<div id="main_wrap">

<?php echo form_open('email/send'); ?>

<h1>Feedback Form</h1>

<p>

                                <label for="name">Name :</label>

                                <input type="text" name="name" id="name">

</p>

<p>

                                <label for="email">Email</label>

                                <input type="text" name="email" id="email">

</p>

<p>

                                <label for="message">Message </label>

                                <textarea name="message"></textarea>

</p>

<p>                        <?php echo form_submit('Submit','Submit'); ?>  </p>

<?php echo form_close(); ?>

</div> <!-- main_wrap -->

</body>

</html>

Here we are using form and url helper to create this page. You can find more on these helpers in Codeigniter user guide.

A little style to add with this page

#main_wrap

{

                width:500px;

                height:350px;

                margin:0 auto;

                background-color:#d6d6d6;

                border:1px solid #3e3e3e;

                padding-left:10px;

}

label

{           display:block;  }

As you can notice in the form_open , I have mentioned ‘email/send’  this means will call email controller .

Before coming to controller par we will create a configuration file in config folder. Create a file email.php in this folder

<?php

$config['protocol']='smtp';

$config['smtp_host']='ssl://smtp.googlemail.com';

$config['smtp_port']='465';

$config['smtp_user']='Your gmail user name ';

$config['smtp_pass']='your password'; 

?>

We can mention this config array in controller also .If we can’t mention this in the controller Ci will automatically search for the configuration file in the config folder with the name same as our controller here we are saving this file as “email.php” and our controller name is also the same.

We are ready with our view and configuration file.It’s time to start with our controller which will send the email. Create a file “email.php”

<?php

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

class Email extends CI_Controller

{

                function __construct()

                {

                                parent::__construct();

                }

                public function index()

                {

                                $this->load->helper(array('url','form'));

                                $data  = array(

                                                                'title' => 'SMTP email with Codeigniter' 

                                                );

                                $this->load->view('email_view',$data);

                }

                public function send()

                {

                                // load form validation library

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

                                //setting the rules

                                $this->form_validation->set_rules('name','Name','required');

                                $this->form_validation->set_rules('email','Email','trim|required|valid_email');

                                $this->form_validation->set_rules('message','Message','trim|required');

                                if($this->form_validation->run() == FALSE)

                                {

                                                 echo validation_errors();

                                }

                                else

                                {

                                                date_default_timezone_set('Asia/Calcutta');

                                                $name                  = $this->input->post('name');

                                                $email                   = $this->input->post('email');

                                                $message            = $this->input->post('message');

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

                                                $this->email->set_newline("\r\n");

                                                $this->email->from($name,$email);

                                                $this->email->to('deven.mycode@gmail.com');

                                                $this->email->subject('Feedback from website');

                                                $this->email->message($message);

                                                if($this->email->send())

                                                {

                                                                echo "Thanks for your feedback";

                                                }

                                                else

                                                {

                                                                show_error($this->email->print_debugger());

                                                }

                                }

                }

}

?>

Code is pretty simple and straight forward.

In the index function we are loading two helpers “url” and “form”.In the view section you must have seen the use of base_url() function provided by url helper .

form_open() and form_close() function provided by form helper.

Now here comes the main part of this tutorial the send function.

In the initial lines we are loading “form_validation” library which is very useful for validation purpose and makes life easy.

If  form_validation->run() return FALSE then will display the error message and if  TRUE is the retun value then will proceed to further to send the email.

In the first line we are setting default time zone for me its “Asia/Calcutta”

$name                  = $this->input->post('name');

$email                  = $this->input->post('email');

$message            = $this->input->post('message');

In this block of code we are accepting the value entered by the visitor.

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

$this->email->set_newline("\r\n");

$this->email->from($name,$email);

$this->email->to('deven.mycode@gmail.com');

$this->email->subject('Feedback from website');

$this->email->message($message);

if($this->email->send())

{

                echo "Thanks for your feedback";

}

else

{

                show_error($this->email->print_debugger());

}

In the first line we are loading email library and setting newline.

From , to ,subject and message will be set via these available methods

Finally if the email sent successfully , message will come on the screen else the debugger will print detail error report.

So, we have learnt how to send smtp email with Codeigniter using Gmail smtp settings. Because of email library provided by Codeigniter makes life easy and  time saving library to avoids using other classes to send an email.

Pagination with CodeIgniter

Till now we have tried our hands on from writing our first  Hello World program to database connection. Now in this tutorial we are going to create pagination using “pagination” library of CodeIgniter.

First of all this is what we are going to create.

Pagination_codeigniter
So, let’s start with database creation

Go to application\config\database.php and change following lines as per your setting

$db['default']['hostname'] = 'localhost';

$db['default']['username'] = 'root';       

$db['default']['password'] = '';            

$db['default']['database'] = 'ci';          

$db['default']['dbdriver'] = 'mysql'; 

Will create a table called “contacts”. Table structure for table contacts

Field

Type

Null

Default

id

int(3)

No

 

name

varchar(50)

No

 

mobile

bigint(10)

No

 

email

varchar(50)

No

 

 Now open  config.php and go to line number 17

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

Again change it as per your setting.

Now the final configuration left is setting default controller, open routes.php go to line number 41 you will find something like this

$route['default_controller'] = "contacts";

Here we are declaring “contacts” as our default controller, which is to be loaded when this application is initiated.

We are done with configuration , Lets starts with our controller, create a file “contacts.php” , open it in your favorite editor

First will create a class Contacts

class Contacts_model extends CI_Model{

           public function __construct()

            {

                        parent::__construct();

                        $this->load->database();

            }

          public function contacts_count()

            {

                        return $this->db->count_all('contacts');

            }

public function get_all($per_page,$offset)

            {

                        $query = $this->db->get('contacts',$per_page,$offset);

                        return $query->result();

            }

}

In these lines of code you can observe that I am loading database in the constructor.

In contacts_count function we are retrieving the number of records present in the contacts table. If you are new to CI and don’t have any idea about active record of CI then you can find detailed information about this <a href=” http://codeigniter.com/user_guide/database/active_record.html

”>here   </a>

 The contacts_count and get_all function we will be using in our controller soon.

Go back to “contacts.php” our controller

Now will start with pagination , we are starting with declaring number of records per page.

//number of records per page

$per_page = 5;  

$offset   = $this->uri->segment(3);  // setting uri segment

To understand this we have to look at how our url will look like

http://localhost/ci/pagination/index.php/contacts/index/10

 we can clearly see that there are 3 segments in this uri

  1. contacts
  2. index
  3. 10

$this->uri->segment(n)

This permits you to get specific segment Where n is the segment number you wish to retrieve. Segments are numbered from left to right.

$offset   = $this->uri->segment(3);

// loading pagination library

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

$config['base_url'] = $data['base'].'/index.php/contacts/index/';

$config['total_rows'] = $total;

$config['per_page']   = $per_page;

$config['full_tag_open'] = '<div id="pagination">';

$config['full_tag_close'] = '</div>';

The $config array contains your configuration variables. It is passed to the $this->pagination->initialize function as shown above. Although there are some twenty items you can configure, at minimum you need the three shown. Here is a description of what those items represent:

  • base_url This is the full URL to the controller class/function containing your pagination. In the example above, it is pointing to a controller called "Test" and a function called "page". Keep in mind that you can re-route your URI if you need a different structure.
  • total_rows This number represents the total rows in the result set you are creating pagination for. Typically this number will be the total rows that your database query returned.
  • per_page The number of items you intend to show per page. In the above example, you would be showing 20 items per page. (from codeigniter manual)

If you would like to surround the entire pagination with some markup you can do it with these two prefs:

$config['full_tag_open'] = '<p>';

The opening tag placed on the left side of the entire result.

$config['full_tag_close'] = '</p>';

The closing tag placed on the right side of the entire result.

$this->pagination->initialize($config);

$data['pagination'] =$this->pagination->create_links();

The create_links() function returns an empty string when there is no pagination to show.

Finally we are ready to send this data to our view contacts_view

$data['query'] = $this->contacts_model->get_all($per_page,$offset);

$this->load->view('contacts_view',$data);

Before going to create view here is our final controller file “contacts.php”

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

class Contacts extends CI_Controller{

            public function __construct()

            {

                        parent::__construct();

            }           

            public function index()

            {          $data['base'] = $this->config->item('base_url');

                        $data['title']= "Contacts";      

                        $this->load->Model("contacts_model");

                       

                        $total     = $this->contacts_model->contacts_count();

                        $per_page = 5;

                        $offset   = $this->uri->segment(3);                       

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

                        $config['base_url'] = $data['base'].'/index.php/contacts/index/';

                        $config['total_rows'] = $total;

                        $config['per_page']   = $per_page;

                        $config['full_tag_open'] = '<div id="pagination">';

                        $config['full_tag_close'] = '</div>';                       

                        $this->pagination->initialize($config);

                        $data['pagination'] =$this->pagination->create_links();                       

                        $data['query'] = $this->contacts_model->get_all($per_page,$offset);

                       

                        $this->load->view('contacts_view',$data);

            }

           

} // Contacts class

?>

Final Model “contacts_model.php”

<?php

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

class Contacts_model extends CI_Model{           

            public function __construct()

            {

                        parent::__construct();

                        $this->load->database();

            }           

            public function contacts_count()

            {

                        return $this->db->count_all('contacts');

            }           

            public function get_all($per_page,$offset)

            {

                        //$this->db->order_by('id','desc');

                        $query = $this->db->get('contacts',$per_page,$offset);

                        return $query->result();

            }

}

?>

Lets create our view “contacts_view.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><?php echo $title; ?> </title>

<link rel="stylesheet" type="text/css" href="<?php echo $base ?>css/style.css" />

</head>

<body>

<div id="main_wrap">

<h1>My Contacts</h1>

<div class="id"><span>Id</span></div>

<div class="name"><span>Name</span></div>

<div class="mobile"><span>Mobile</span></div>

<div class="email"><span>Email</span></div>

<?php

foreach($query as $row)

{

?>

<div class="contact_list">

            <div class="id"><?php echo $row->id; ?> </div>

            <div class="name"><?php echo $row->name; ?></div>

            <div class="mobile"><?php echo $row->mobile; ?></div>

            <div class="email"><?php echo $row->email; ?></div>  

</div>

<?php

}

?>

<?php

echo $pagination;

?>

</div>

</body>

</html>

Now add CSS by creating css folder and then style.css in it. Will not go into the details  since this just a basic stuff ,does not require much explaination.

body{

            background-color:#d6d6d6;

            font-family:Arial;

}

h1{margin-left:20px;padding:0px;}

 

.contact_list{

            width:660px;

            font-family:Helvetica;

            font-size:14px;

}

#main_wrap{

            width:800px;

            height:280px;

            background-color:#ffffff;

            margin:0 auto;

            border:1px solid #e6e6e6;

            margin-top:50px;

            -webkit-border-radius: 20px;

            -moz-border-radius: 20px;

            border-radius: 20px;

}

#pagination{

            float: left;

            font:11px Tahoma, Verdana, Arial, "Trebuchet MS", Helvetica, sans-serif;

            color:#3d3d3d;

            margin-top: 20px;

            margin-left:10px;

            margin-right:auto;

            margin-bottom:20px;

            width:100%;

}

#pagination a, #pagination strong{

            list-style-type: none;

            display: inline;

            padding: 5px 8px;

            text-decoration: none;

            background-color:inherit;

            color: #EC7117;

            font-weight: bold;

}

#pagination strong{

            color: #ffffff;

            background-color:#d6d6d6;

            background-position:top center;

            background-repeat:no-repeat;

            text-decoration:none;

}

#pagination a:hover{

            color:#ffffff;

            background-color:#d6d6d6;

            background-position:top center;

            background-repeat:no-repeat;

            text-decoration:none;

}

.id{width:50px;float:left;line-height:24px;margin-left:10px;}

.name{width:300px;float:left;line-height:24px;}

.mobile{width:200px;float:left;line-height:24px;}

.email{width:100px;float:left;line-height:24px;}

span{font-weight:bold;}

Now run your application for me following is the url

http://localhost/ci/pagination

Conclusion

 This CI library is very useful to create pagination without using any third party tool.

Database

In the previous post we have seen how to configure codeigniter  and created a view.

Now in this post we are going to create a database and then will fetch records from database.

In this post will learn how to create model in codeigniter

For this we will be using codeigniter 2.0 and mysql for the backend.

Go to application/config/config.php , here set the base url for me its

$config['base_url']        = 'localhost/ci/dbexample';

Now open database.php , which is also located in the same config folder

$db['default']['hostname'] = 'localhost';

$db['default']['username'] = 'root';

$db['default']['password'] = '';

$db['default']['database'] = 'ci';

Enter  values as per your settings.

First will create a table “friends” in database “ CI “

CREATE TABLE IF NOT EXISTS `myfriends` (

  `id` int(2) NOT NULL,

  `name` varchar(25) NOT NULL,

  `mobile` bigint(10) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `myfriends` (`id`, `name`, `mobile`) VALUES

(1, 'Devendra Verma', 9833199276),

(2, 'Ganesh', 6545256892),

(3, 'Navin', 65214875962),

(4, 'Pramod', 7854125965),

(5, 'Vaibhav', 8756924578);

Open routes.php and locate the following code

$route['default_controller'] = "welcome";

 This tells CI that welcome is the default controller , but for our example we change it to

$route['default_controller'] = "myfriends";

Now will create controller ,  

Open your favorite editor  and create a php file called “myfriends.php”

<?php

 

class MyFriends extends CI_Controller

{

            public function __construct()

            {

                        parent::__construct();

                        $this->load->model('myfriends_model');

            }

           

            public function index()

            {

                        $view_details['friend_details'] = $this->myfriends_model->getfriends();

                        $this->load->view('myfriends_view',$view_details);

            }

}

?>

 

controller will load model called “myfriends_model ”. myfriend model will communicate with the database and fetch the records.  

Our model would be something like below

<?php

class MyFriends_model extends CI_Model

{

            function __construct()

            {

                        parent::__construct();

                        $this->load->database();

                       

            }

            public function getfriends()

            {

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

                        $orderdb = $this->db->order_by("id","asc");

                       

                        if($query -> num_rows() >0)

                        {

                                    return $query->result_array($orderdb);

                        }

                       

            }

 

}

?>

Here , we are retrieving data from myfriends table and return the result.

Now controller will redirect this data to view “myfriends”.controller will load our View called “myfriends_new”.

<html>

<head>

<title>Fetching records from database in CI 2.0</title>

</head>

<body>           

                        <table align="center" width="60%" cellspacing="5" cellpadding="0">

                                    <tr><td colspan="3" align="center"><b>Friends Contact Details</b></td></tr>          

                                    <tr>

                                                            <td><b>Id</b></td>

                                                            <td><b>Name</b></td>

                                                            <td><b>Mobile No</b></td>

                                    </tr>

                                    <?php

                                                foreach($friend_details as $value)

                                                {

                                    ?>       

                                                            <tr>

                                                                                    <td><?php echo $value['id']; ?></td>

                                                                                    <td><?php echo $value['name']; ?></td>

                                                                                    <td><?php echo $value['mobile']; ?></td>

                                                            </tr>

                                    <?php             

                                                }

                                    ?>

                        </table>

</body>

</html>

Now open type http://localhost/ci/dbexample/ in your browser and you shold get something like this

Database_in_ci_2

Codeigniter for beginners-my first App(Hello world)

In the series of codeigniter for beginners here is the second post.In this post we will learn following things

       a) Download Codeigniter   

b)Configure Codeigniter

c) Create Controller

d)Create  View

e) Run the application

a)      Download Codeigniter

Now we are going to download Codeigniter .To download click here http://codeigniter.com/downloads/  we are going to download version 2.0.3

Codeigniter_download
Download the zip file and unzip it.

Copy the folder and paste it into c:\xampp\htdocs folder (here I am assuming that you are using Xampp server).

 Here I have create ci folder and under that I am going to create helloworld folder

 So my path is d://xampp/htdcos/ci/helloworld/

 b) Configure Codeigniter

 Now go to application\config and open routes.php in your favorite editor.On line 41 you will find some thing like this :

 $route['default_controller'] = "welcome";

 Change this to

 $route['default_controller'] = "HelloWorld";

   Basically this will tell CI that you want to load controller hello_world when the system is instantiated.

 c) Create Controller:

Here will create our controller .Go to application\controller and create a file hello_world.php   

And will write the following code into this file

<?php

class HelloWorld extends CI_Controller {

            public function index()

            {

                   $this->load->view('hello_world');                       

            }         

 } ?>

Here we are telling controller to load the hello_world  view.

d) Create View

 Now will create view . Create a file hello_world.php into application\views folder

 <html>

<head>

<title>My Codeigniter Application</title>

</head>

<body>

                             <h1>Hello world !!!</h1>       

 </body>

</html>

e)      Now start the apache server from your Xampp server

Apache_start_server

       Open your browser and  Type http://localhost/ci/helloworld/  

Hello_world_result
And now the result is in front of your eyes :)

Test cases for websites

Testing web applications is different because of many factors scenarios affecting the performance and user experience.

To prepare test case for a website following thing needs to be considered

a) Functional Testing

b) Performance Testing

c) Usability Testing

d) Server Side Compatibility

e) Client Side Compatibility

f) Security Testing

a) Functionality:

In testing the functionality of the web sites the following should be tested:

• Links
i. Internal Links  : Internal link are those which redirect you to other websites

ii. External Links: External links are the links which takes you to the same page content or any other part of the same website

iii. Mail Links    : Mail links should be tested to check whether it is getting executed or not

iv. Broken Links : 404 errors and broken links also have negative effects on your search engine rankings so it is quite reasonable to be proactive in avoiding them to improve exposure and increase site traffic.

• Forms
i. Field validation :All the required fields should be validated
ii. Error message for wrong input : Make sure to give an alert containing message regarding wrong input by the user
iii. Optional and Mandatory fields : Decide which fields are optional and which are mandatory, If it is mandatory then give alter to user and hallt the execution or redirection to another page.

• Database

Data integrity is tested by the following tests:

i. Verify that you can create, modify, and delete any data in tables.

ii. Verify that sets of radio buttons represent fixed sets of values.

iii. Verify that a blank value can be retrieved from the database.

iv. Verify that, when a particular set of data is saved to the database, each value gets saved fully, and the truncation of strings and rounding of numeric values do not occur.

v. Verify that the default values are saved in the database, if the user input is not specified.

vi. Verify compatibility with old data, old hardware, versions of operating systems, and interfaces with other software.

• Cookies

i.  Testing will be done on the client system side, on the temporary Internet files.

b) Performance :

Performance testing can be applied to understand the web site’s scalability, or to benchmark the performance in the environment of third party products such as servers and middleware for potential purchase.

• Connection Speed:
Tested over various networks like Dial Up, ISDN etc
• Load:
i. What is the no. of users per time?
ii. Check for peak loads and how system behaves
iii. Large amount of data accessed by user
• Stress:
i. Continuous Load
ii. Performance of memory, CPU, file handling etc..

c) Usability:
Usability testing is the process by which the human-computer interaction characteristics of a system are measured, and weaknesses are identified for correction.
• Ease of learning
• Navigation
• Subjective user satisfaction
• General appearance

d) Server Side Compability:
In web testing the server side interface should be tested. This is done by verify that communication is done properly. Compatibility of server with software, hardware, network and database should be tested.

e) Client Side Compatibility:
The client side compatibility is also tested in various platforms, using various browsers etc.

f) Security:
The primary reason for testing the security of a web is to identify potential vulnerabilities and subsequently repair them.
• Network Scanning
• Vulnerability Scanning
• Password Cracking
• Log Review
• Integrity Checkers
• Virus Detection

 

substract days,weeks,months,years from date in PHP

Subtracting Days from date:

$date = "1987-05-23";
$newdate = strtotime ( '-3 day' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );

echo $newdate;

Subtracting Weeks from a date

$date = "1987-05-23";
$newdate = strtotime ( '-3 week' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );

echo $newdate;

Subtracting Months from a date

$date = "1987-05-23";
$newdate = strtotime ( '-3 month' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );

echo $newdate;

Subtracting Years from a date

$date = "1987-05-23";
$newdate = strtotime ( '-3 year' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );

echo $newdate;

.htaccess tips and tricks..

One of the more powerful tricks of the .htaccess hacker is the ability to rewrite URLs. This enables us to do some mighty manipulations on our links; useful stuff like transforming very long URL’s into short, cute URLs, transforming dynamic ?generated=page&URL’s into /friendly/flat/links, redirect missing pages, preventing hot-linking, performing automatic language translation, and much, much more.

Make no mistake, mod_rewrite is complex. This isn’t the subject for a quick bite-size tech-snack, probably not even a week-end crash-course, I’ve seen guys pull off some real cute stuff with mod_rewrite, but with kudos-hat tipped firmly towards that bastard operator from hell, Ralf S. Engelschall, author of the magic module itself, I have to admit that a great deal of it still seems so much voodoo to me.

The way that rules can work one minute and then seem not to the next, how browser and other in-between network caches interact with rules and testing rules is often baffling, maddening. When I feel the need to bend my mind completely out of shape, I mess around with mod_rewrite!

After all this, it does work, and while I’m not planning on taking that week-end crash-course any time soon, I have picked up a few wee tricks myself, messing around with web servers and web sites, this place..

The plan here is to just drop some neat stuff, examples, things that have proven useful, and work on a variety of server setups; there are Apache’s all over my LAN, I keep coming across old .htaccess files stuffed with past rewriting experiments that either worked; and I add them to my list, or failed dismally; and I’m surprised that more often these days, I can see exactly why!

Very little here is my own invention. Even the bits I figured out myself were already well documented, I just hadn’t understood the documents, or couldn’t find them. Sometimes, just looking at the same thing from a different angle can make all the difference, so perhaps this humble stab at URL Rewriting might be of some use. I’m writing it for me, of course. but I do get some credit for this..

# time to get dynamic, see..
RewriteRule (.*)\.htm $1.php

beginning rewriting..
Whenever you use mod_rewrite (the part of Apache that does all this magic), you need to do..

Options +FollowSymlinks
RewriteEngine on

..before any ReWrite rules. note: +FollowSymLinks must be enabled for any rules to work, this is a security requirement of the rewrite engine. Normally it’s enabled in the root and you shouldn’t have to add it, but it doesn’t hurt to do so, and I’ll insert it into all the examples on this page, just in case*.

The next line simply switches on the rewrite engine for that folder. if this directive is in you main .htaccess file, then the ReWrite engine is theoretically enabled for your entire site, but it’s wise to always add that line before you write any redirections, anywhere.

* Although highly unlikely, your host may have +FollowSymLinks enabled at the root level, yet disallow its addition in .htaccess; in which case, adding +FollowSymLinks will break your setup (probably a 500 error), so just remove it, and your rules should work fine.

Important: While some of the directives on this page may appear split onto two lines in your browser, in your .htaccess file they must exist completely on one line. If you drag-select and copy the directives on this page, they should paste just fine into any text editor.

simple rewriting
Simply put, Apache scans all incoming URL requests, checks for matches in our .htaccess file and rewrites those matching URLs to whatever we specify. something like this..

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [NC]

Handy for anyone updating a site from static htm (you could use .html, or .htm(.*), .htm?, etc) to dynamic php pages; requests to the old pages are automatically rewritten to our new urls. no one notices a thing, visitors and search engines can access your content either way. leave the rule in; as an added bonus, this enables us to easily split php code and its included html structures into two separate files, a nice idea; makes editing and updating a breeze. The [NC] part at the end means “No Case”, or “case-insensitive”; more on the switches, later.

Folks can link to whatever.htm or whatever.php, but they always get whatever.php in their browser, and this works even if whatever.htm doesn’t exist! But I’m straying..

As it stands, it’s a bit tricky; folks will still have whatever.htm in their browser address bar, and will still keep bookmarking your old .htm URL’s. Search engines, too, will keep on indexing your links as .htm, some have even argued that serving up the same content from two different places could have you penalized by the search engines. This may or not bother you, but if it does, mod_rewrite can do some more magic..

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)\.htm$ http://corz.org/$1.php [R,NC]

This time we instruct mod_rewrite to do a proper external rewrite, aka, “redirection”. Now, instead of just background rewriting on-the-fly, the user’s browser is physically redirected to a new URI, and whatever.php appears in their browser’s address bar – search engines and other spidering entities will automatically update their links to the .php versions; everyone wins. You can take your time with the updating, too.

Note: if you use [R] alone, it defaults to sending an HTTP “MOVED TEMPORARILY” redirection, aka, “302″. But you can send other codes, like so..

RewriteRule ^(.+)\.htm$ http://corz.org/$1.php [R=302,NC]

not-so-simple rewriting … flat links and more
You may have noticed, the above examples use regular expression to match variables. What that simply means is.. match the part inside (.+) and use it to construct “$1″ in the new URL. In other words, (.+) = $1 you could have multiple (.+) parts and for each, mod_rewrite automatically creates a matching $1, $2, $3, etc, in your target (aka. ‘substitution’) URL. This facility enables us to do all sorts of tricks, and the most common of those, is the creation of “flat links”..

Even a cute short link like http://mysite/grab?file=my.zip is too ugly for some people, and nothing less than a true old-school solid domain/path/flat/link will do. Fortunately, mod_rewrite makes it easy to convert URLs with query strings and multiple variables into exactly this, something like..

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^files/([^/]+)/([^/]+).zip /download.php?section=$1&file=$2 [NC]

would allow you to present this link as..

http://mysite/files/games/hoopy.zip

and in the background have that transparently translated, server-side, to..

http://mysite/download.php?section=games&file=hoopy

which some script could process. You see, many search engines simply don’t follow our ?generated=links, so if you create generating pages, this is useful. However, it’s only the dumb search engines that can’t handle these kinds of links; we have to ask ourselves.. do we really want to be listed by the dumb search engines? Google will handle a good few parameters in your URL without any problems, and the (hungry hungry) msn-bot stops at nothing to get that page, sometimes again and again and again…

I personally feel it’s the search engines that should strive to keep up with modern web technologies, in other words; we shouldn’t have to dumb-down for them. But that’s just my opinion. Many users will prefer /files/games/hoopy.zip to /download.php?section=games&file=hoopy but I don’t mind either way. As someone pointed out to me recently, presenting links as standard/flat/paths means you’re less likely to get folks doing typos in typed URL’s, so something like..

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^blog/([0-9]+)-([a-z]+) http://corz.org/blog/index.php?archive=$1-$2 [NC]

would be a neat trick, enabling anyone to access my blog archives by doing..

http://corz.org/blog/2003-nov

in their browser, and have it automagically transformed server-side into..

http://corz.org/blog/index.php?archive=2003-nov

which corzblog would understand. It’s easy to see that with a little imagination, and a basic understanding of posix regular expression, you can perform some highly cool URL manipulations.

Here’s the very basics of regexp (expanded from the Apache mod_rewrite documentation)..

Escaping:

\char escape that particular char

For instance to specify special characters.. [].()\ etc.

Text:

. Any single character (on its own = the entire URI)
[chars] Character class: One of following chars
[^chars] Character class: None of following chars
text1|text2 Alternative: text1 or text2 (i.e. “or”)

e.g. [^/] matches any character except /
(foo|bar)\.html matches foo.html and bar.html

Quantifiers:

? 0 or 1 of the preceding text
* 0 or N of the preceding text (hungry)
+ 1 or N of the preceding text

e.g. (.+)\.html? matches foo.htm and foo.html
(foo)?bar\.html matches bar.html and foobar.html

Grouping:

(text) Grouping of text

Either to set the borders of an alternative or
for making backreferences where the nthe group can
be used on the target of a RewriteRule with $n

e.g. ^(.*)\.html foo.php?bar=$1

Anchors:

^ Start of line anchor
$ End of line anchor

An anchor explicitly states that the character right next to it MUST
be either the very first character (“^”), or the very last character (“$”)
of the URI string to match against the pattern, e.g..

^foo(.*) matches foo and foobar but not eggfoo
(.*)l$ matches fool and cool, but not foo

shortening URLs
One common use of mod_rewrite is to shorten URL’s. Shorter URL’s are easier to remember and, of course, easier to type. An example..

Options +FollowSymlinks
RewriteEngine On
RewriteRule ^grab /public/files/download/download.php

this rule would transform this user’s URL..

http://mysite/grab?file=my.zip

server-side, into..

http://mysite/public/files/download/download.php?file=my.zip

which is a wee trick I use for my distro machine, among other things. everyone likes short URL’s, and so will you; using this technique, you can move /public/files/download/ to anywhere else in your site, and all the old links still work fine; simply alter your .htaccess file to reflect the new location. edit one line, done – nice – means even when stuff is way deep in your site you can have cool links like this.. /trueview/sample.php and this; links which are not only short, but flat..

capturing variables
Slapping (.*) onto the end of the request part of a ReWriteRule is just fine when using a simple $_GET variable, but sometimes you want to do trickier things, like capturing particular variables and converting them into other variables in the target URL. Or something else..

When capturing variables, the first thing you need to know about, is the [QSA] flag, which simply tags all the original variables back onto the end of the target url. This may be all you need, and will happen automatically for simple rewrites. The second thing, is %{QUERY_STRING}, an Apache server string we can capture variables from, using simple RewriteCond (aka. conditional ) statements.

RewriteCond is very like doing if…then…do in many programming languages. If a certain condition is true, then do the rewrite that follows..

In the following example, the RewriteCond statement checks that the query string has the foo variable set, and captures its value while it’s there. In other words, only requests for /grab that have the variable foo set, will be rewritten, and while we’re at it, we’ll also switch foo, for bar, just because we can..

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} foo=(.*)
RewriteRule ^grab(.*) /page.php?bar=%1

would translate a link/user’s request for..

http://domain.com/grab?foo=bar

server-side, into..

http://domain.com/page.php?bar=bar

Which is to say, the user’s browser would be fed page.php (without an [R] flag in the RewriteRule, their address bar would still read /grab?foo=bar). The variable bar would be available to your script, with its value set to bar. This variable has been magically created, by simply using a regular ? in the target of the RewriteRule, and tagging on the first captured backreference, %1.. ?bar=%1

Note how we use the % character, to specify variables captured in RewriteCond statements, aka “Backreferences”. This is exactly like using $1 to specify numbered backreferences captured in RewriteRule patterns, except for strings captured inside a RewriteCond statement, we use % instead of $. Simple.

You can use the [QSA] flag in addition to these query string manipulations, merge them. In the next example, the value of foo becomes the directory in the target URL, and the variable file is magically created. The original query string is then tagged back onto the end of the whole thing..

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} foo=(.+)
RewriteRule ^grab/(.*) /%1/index.php?file=$1 [QSA]

So a request for..

http://domain.com/grab/foobar.zip?level=5&foo=bar

is translated, server-side, into..

http://domain.com/bar/index.php?file=foobar.zip&level=5&foo=bar

Depending on your needs, you could even use flat links and dynamic variables together, something like this could be useful..

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} version=(.+)
RewriteRule ^grab/([^/]+)/(.*) /%1/index.php?section=$1&file=$2 [QSA]

By the way, you can easily do the opposite, strip a query string from a URL, by simply putting a ? right at the end of the target part. This example does exactly that, whilst leaving the actual URI intact..

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} .
RewriteRule foo.php(.*) /foo.php? [L]

The RewriteCond statement only allows requests that have something in their query string, to be processed by the RewriteRule, or else we’d end up in that hellish place, dread to all mod_rewriters.. the endless loop. RewriteCond is often used like this; as a safety-net.

cooler access denied
In part one I demonstrated a drop-dead simple mechanism for denying access to particular files and folders. The trouble with this is the way our user gets a 403 “Access Denied” error, which is a bit like having a door slammed in your face. Fortunately, mod_rewrite comes to the rescue again and enables us to do less painful things. One method I often employ is to redirect the user to the parent folder..

# send them up!
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)$ ../ [NC]

It works great, though it can be a wee bit tricky with the URLs, and you may prefer to use a harder location, which avoids potential issues in indexed directories, where folks can get in a loop..
# send them exactly there!
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)$ /comms/hardware/router/ [NC]

Sometimes you’ll only want to deny access to most of the files in the directory, but allow access to maybe one or two files, or file types, easy..

# users can load only "special.zip", and the css and js files.
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^(.+)\.css$
RewriteCond %{REQUEST_FILENAME} !^(.+)\.js$
RewriteCond %{REQUEST_FILENAME} !special.zip$
RewriteRule ^(.+)$ /chat/ [NC]

Here we take the whole thing a stage further. Users can access .css (stylesheet) and Javascript files without problem, and also the file called “special.zip”, but requests for any other file types are immediately redirected back up to the main “/chat/” directory. You can add as many types as you need. You could also bundle the filetypes into one line using | (or) syntax, though individual lines are perhaps clearer.

Here’s what’s currently cooking inside my /inc/ directory..

RewriteEngine on
Options +FollowSymlinks
# allow access with no restrictions to local machine at 192.168.1.3
RewriteCond %{REMOTE_ADDR} !192.168.1.3
# allow access to all .css and .js in sub-directories..
RewriteCond %{REQUEST_URI} !\.css$
RewriteCond %{REQUEST_URI} !\.js$
# allow access to the files inside img/, but not a directory listing..
RewriteCond %{REQUEST_URI} !img/(.*)\.
# allow access to these particular files...
RewriteCond %{REQUEST_URI} !comments.php$
RewriteCond %{REQUEST_URI} !corzmail.php$
RewriteCond %{REQUEST_URI} !digitrack.php$
RewriteCond %{REQUEST_URI} !gd-verify.php$
RewriteCond %{REQUEST_URI} !post-dumper.php$
RewriteCond %{REQUEST_URI} !print.php$
RewriteCond %{REQUEST_URI} !source-dump.php$
RewriteCond %{REQUEST_URI} !textview.php$
RewriteRule ^(.*)$ / [R,NC,L]

Ban User Agents, referrers, script-kiddies and more..
There are many valid reasons to ban a particular request from sucking up your site’s resources; resources that could be better served to valid, interested users. It might be some cross-site attack script, or inward link from a place you don’t want to be associated with, or perhaps a web sucker or download manager, whatever; .htaccess + mod_rewrite provides ways to protect your content from unwanted “guests”.

The basic formula is standard if-then logic: if the request meets a particular CONDITION, then REWRITE the request. The “conditions” can be many things; perhaps the referrer header sent by their browser (the site they came from), or the page they asked for, or a particular query parameter, or the type of client (browser, etc.) they are using, or any other piece of information Apache has attached to the request. Here’s an example which will deny access to “Teleport Pro”, a download manager which is known to suck, hard..

RewriteCond %{HTTP_USER_AGENT} ^Teleport\ Pro [NC]
RewriteRule . abuse.txt [L]

It’s your site, and just like your home, you have every right to exert some control over who gets in. You may have a huge list of user agents you’d rather not have eating your bandwidth; so use the [OR] flag, and line ‘em up..

RewriteCond %{HTTP_USER_AGENT} ^BackWeb [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Bandit [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^BatchFTP [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^BecomeBot [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [NC,OR]
# etc..
RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [NC]
RewriteRule . abuse.txt [L]

This forms the basis of what often becomes a HUGE list of ban-lines. Remember, we aren’t limited to user agent strings..
# why not come visit me directly?
RewriteCond %{HTTP_REFERER} \.opendirviewer\. [NC,OR]
# this prevents stoopid cross-site discovery attacks..
RewriteCond %{THE_REQUEST} \?\ HTTP/ [NC,OR]
# please stop pretending to be the Googlebot..
RewriteCond %{HTTP_REFERER} users\.skynet\.be.* [NC,OR]
# really, we need a special page for these twats..
RewriteCond %{QUERY_STRING} \=\|w\| [NC,OR]
RewriteCond %{THE_REQUEST} etc/passwd [NC,OR]
RewriteCond %{REQUEST_URI} owssvr\.dll [NC,OR]
# you can probably work these out..
RewriteCond %{QUERY_STRING} \=\|w\| [NC,OR]
RewriteCond %{THE_REQUEST} \/\*\ HTTP/ [NC,OR]
# etc..
RewriteCond %{HTTP_USER_AGENT} Sucker [NC]
RewriteRule . abuse.txt [L]

Fortunately, mod_rewrite can parse enormous lists of ban-lines in milliseconds, so feel free to be as specific and comprehensive as required.

As ever, thorough testing is strongly recommended. Simply send requests matching your conditions and see what happens. And importantly; normal requests, too. Firefox, Opera, Konqueror, and most other decent browsers, allow you to alter the user agent string; though you would quickly find the process tedious in a testing situation. Far better to use some tool better designed to send fake HTTP requests..

It’s not too difficult to mock up a web request on the command-line with any-old user agent using a scripting language like php or Perl, if you have these things available (read: most Linux/UNIX/BSD/etc. as well as many other OS). Many examples exist online. In fact, you could quickly create a suite of tests, designed to interrogate all your rewrite rules, with results logging and much more, if required. cURL is always useful for jobs like this, so long as you don’t add a cURL ban-line!

On a Windows desktop, Sam Spade can send a single spoofed request with a couple of clicks, along with a stack of similarly handy tricks, and regularly proves itself invaluable.

Don’t let just anyone hammer your site!
While I’m on the subject of abusive web clients, you will probably have noticed that many clients (bots, spiders, automated suckers and such) like to disguise their user agent information, in fact any information, in an attempt to bring your site to its knees, hammering your pages so-many times per second in the process. Oh dear.

If you are interested in a way to defeat hammering web clients, regardless of who they pretend to be, or whether or not they accept cookies or any such malarkey, check out Anti-Hammer. It’s free.

prevent hot-linking
Believe it or not, there are some webmasters who, rather than coming up with their own content will steal yours. Really! Even worse, they won’t even bother to copy to their own server to serve it up, they’ll just link to your content! no, it’s true, in fact, it used to be incredibly common. These days most people like to prevent this sort of thing, and .htaccess is one of the best ways to do it.

This is one of those directives where the mileage variables are at their limits, but something like this works fine for me..

Options +FollowSymlinks
# no hot-linking
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?corz\.org/ [NC]
RewriteCond %{REQUEST_URI} !hotlink\.(gif|png) [NC]
RewriteRule .*\.(gif|jpg|png)$ http://corz.org/img/hotlink.png [NC]

Ref: http://corz.org/serv/tricks/htaccess2.php

Display image if flash is not present

Sometimes , we face problem when flash is not installed in the browser so that blank box looks ridiculous.
so if flash is not present will display an image .
here is the simple code to achieve this :

<object classid=”clsid:D27CDB6E-AE6D-11cf-96B8-444553540000″ width=”800″ height=”600″ id=”flashContent”>
<param name=”movie” value=”flash/flash.swf” />
<!–[if !IE]>–>
<object type=”application/x-shockwave-flash” data=”flash/flash.swf” width=”800″ height=”600″>
<!–<![endif]–>
<img src=”ogo.jpg” alt=”Put your alternate content here” />
<!–[if !IE]>–>
</object>
<!–<![endif]–>
</object>

CSS for beginners part (I)

What is CSS ?

CSS stands for Cascading Style Sheet. CSS controls the display of the elements. CSS was first developed in 1997 , to help developer to define look and feel of their web pages. CSS is first  incorporated in Html 4.0 .

Why CSS ?

When <font> tags were introduced in Html 3.2 specification , it became very difficult  for developers to maintain the site . For large sites you have to make changes to every page to change the look and feel of the site.

So, W3c created CSS and introduced it in  Html 4.0 specification.

Advantages of CSS

Here are some advantage of using CSS:

a)      Saves time : when we start with Html in early days we used to use font tag with face and color and all attributes. Hence we type again and gain the same thing whenever we use font tag . By using CSS we have to just specify the tag and its attribute at once in the CSS file , so it saves a lot of time .

b)     Page Loads Faster: Since the CSS codes are in different files so there is less code on each page which enables web pages to load faster. So the first time browser takes time to load the CSS file but after that life becomes much faster.

c)      Easy to maintain : Since we have to just make changes to only in CSS file the maintenance is faster.

Disadvantage of CSS :

The main disadvantage of using CSS is the browser compatibility . Some times the same CSS which is working fine for IE6 it may not work with IE 7 , even same browser with different version have compatibility issues. This is also true for other browser . You must test it on various browser .

Types Of CSS  style:

There are three types of CSS styles :

a) Inline Styles:

Inline styles are styles that are written directly in the tag.

<font face=”times new roman” size=”+1”>Hello </font>

b) Embedded Styles :

Embedded styles are embedded in the head of the document between <style></style> tag.

<style>

.body{

Margin:0px;

Padding:0px;

}

</style>

c) External Styles :

External styles are styles that are written in a separate CSS file and then attach that file to any webpage.

<link rel=”stylesheet”  type=”text/css” href=”css/style.css”>

Use of external styles are recommended.

PHP code to check mobile DND

The primary objective of the National Do Not Call Registry (NDNC Registry) is to curb Unsolicited Commercial Communication (UCC). UCC has been defined as "any message, through telecommunications service, which is transmitted for the purpose of informing about,or soliciting or promoting any commercial transaction in relation to goods, investments or services which a subscriber opts not to receive, but, does not include, ----

(i) any message (other than promotional message) relating to a service or financial transaction under a specific contract between the parties to such contract;or

(ii) any messages relating to charities, national campaigns or natural calamities transmitted on the directions of the Government or agencies authorized by it for the said purpose;

(iii) messages transmitted, on the directions of the Government or any authority or agency authorized by it, in the interest of the sovereignty and integrity of India, the security of the State, friendly relations with foreign States, public order, decency or morality.

" For customers who would like to register/de-register their request for NDNC registry may dial 1909 or SMS to 1909 with keywords 'START DND' for registration and 'STOP DND' for de-registration Here is the PHP code to check for DND

<html>
<body>
<form name="form1" action="" method ="POST">
Mobile Numer<input type="text" name="num"><input type="submit" value=" Check ">
<?php
if(isset($_POST['num']))
echo '<br>Status: '.ndncCheck($_POST['num']);
?>
</form>
</body>
</hmtl>
<?php
function ndncCheck($num){
$curl = curl_init();
$timeout = 60;
curl_setopt ($curl, CURLOPT_URL,$url);
curl_setopt ($curl, CURLOPT_POST, 1);
curl_setopt ($curl, CURLOPT_POSTFIELDS, "mobile=". $num);
curl_setopt ($curl, CURLOPT_MAXREDIRS, 20);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
$response= strip_tags(curl_exec($curl));
$out="";
if (trim($response)=="Active"){
$out= $num. " is an Active DND Number.";
}
else{
$out= $num. " is not an Active DND Number.";
}
return $out;
}