Rapid development of PHP applications using the CodeIgniter framework (6)

Source: Internet
Author: User
Tags php session
Theory is enough! Now let's start writing our own applications. In this chapter, we will give a general description of an application system we want to establish, and analyze some basic problems that will affect the website system, that is, session management and security. Simplify Session usage and security

Theory is enough! Now let's start writing our own applications. In this chapter, we will give a general description of an application system we want to establish, and analyze some basic problems that will affect the website system, that is, session management and security.

In this chapter, we will see:

. How to secure your webpage

. How to use the CI session class

Start designing a real website with CI

We have read the welcome page generated during CI installation and the action flows of controller files and view files in its internal actions. In fact, this is the CI's 'Hello, World! '.

Once upon a time, enthusiasts used open-source code systems for their websites, and were often regarded as low-end playmates by some so-called large companies.

However, the Times are different from the old saying. Many large companies are beginning to use open source code technology. For example, the US space agency and the associated press use MySQL, the US audit office, and Yahoo are using PHP applications. I believe that dynamic websites with moderate scale and high flexibility are growing rapidly. When large companies learn that the business technologies they have been using cannot meet new requirements, they have introduced a moderate scale and highly flexible application to replace the original system.

CI is undoubtedly a powerful tool with a moderate scale of design and development and high flexibility. It teaches you how to plan your website and make consistent and reliable use.

To demonstrate the flexibility of CI, let's start to build an application.

I want this website to solve my problems. I am maintaining some websites, some of which are my own and some of which are my customers. I need to perform routine maintenance on these websites and test them to ensure they work well. Most of the work is repetitive. I can hire someone to do it, but writing a website is a reasonable solution. it can automate the work, whether day or night.

Therefore, my requirements are:

1. manage one or more remote websites without manual intervention

2. regularly detect remote websites

3. generate reports to provide website details and test results

If ISP permits, I want to set the website to run Cron (note: the scheduled task software in linux). If not, I will run Cron twice a day or once an hour, run a preset test plan.

I don't want to know the details, unless something goes wrong (then I want it to send an email to tell me what is going on when I leave the hospital and what is going on ), then I want to print out the management report so that my customers can realize that I have been doing regular checks and running their websites properly.

To avoid code too long and too repetitive, the code in this book is not safe enough, so remember not to use the code in the actual application environment. This chapter covers the general concept of website security for unauthenticated users and other PHP security issues, which are not covered in this book.

At this stage, we can see that the CI implementation method is similar to the general dynamic website method. Therefore, let's put down the design topic and start with some very basic concepts.

About websites

Any website is a collection of various applications, and they should be able to interact with each other. We can see in chapter 3rd that CI uses URL for link. The following table lists typical URLs:

The basic url http://www.mysite.com. this is the most basic URL, which is used by the user
Your website. Users do not need to know the rest of the URL. The website will automatically add other parts as needed.

Index File Part 1: index. php
This is the main file of the CI website.

Class Part 2: start
(Or controller) if no controller is set, CI will find the default controller from the config file.

Method Part 3: assessme
(Or called a function) if no function is set, CI will use the default function in this controller.
Redirect to 404 page

Any added parameter Part 4: fred
Parameters passed to the function
Part 5: 12345, Part 6: Hello, and so on.



Therefore, call the accessme function in the start controller and input two parameters, fred and 12345. your website will be:

Http://www.mysite.com.index.php/start/assessme/fred/12345


The system will look for start. php, where there is a Start class, which has an internal accessme method, two parameters need to be input, and now the values passed to these two parameters are fred and 12345 respectively. A url can call any function in any controller on your website.

To learn how it works, let's build the first page of our website. We will create a controller called Start and set it as the default controller.

Well, first, because it specifies the welcome as the default controller when installing CI, I need to change this setting.

The default CI route is stored in the following path:

/System/application/config/routes

Currently set:

$ Route ['default _ controller'] = "welcome ";

We changed it ::

$ Route ['default _ controller'] = "start ";

(Remember, if you do not have an index method in your default controller, if you use a basic URL, the system displays error 404)

Now I need to write my start controller. Remember the basic format:

Class Start extends Controller {
Function start (){
Parent: Controller ();
}

Function assessme ($ name, $ password ){
If ($ name = 'Fred '& $ password = '000000 '){

$ This-> mainpage ();
}
}

}
?>

Save the file as/system/application/controllers/start. php.

The second line tells you that this is a controller. Then the constructor loads the parent controller constructor. The assessme function requires two variables: $ name and $ password. CI (from version 1.5) automatically allocates the relevant part of the URL as the parameter, so fred and 12345 will change to the $ name and $ password.

Therefore, if we enter the URL above and the password is correct if the user exists, I will be redirected to the mainpage () function. We will add this function to the start controller. (If the detection fails, the system stops running .)

For those who have always used procedural programming rather than OO programming, note that the methods in a class must be expressed as $ this-> xxxx. Therefore, if I call the mainpage () function in the start controller, it must be $ this-> mainpage (). otherwise, CI cannot find it.

Of course, a general user will not locate a website like this:

Http://www.mysite.com.index.php/start/assessme/fred/12345.

They only enter:

Http://www.mysite.com

You also want the website to provide a navigation bar. So let's start here.

Generally, the first page you see on a website is the logon page. So let's do it. First, I add a new function to the start controller. I want the website to call this function by default, so I name it index ().

Function (){

$ Data ['mytitle'] = "My site ";
$ Data ['base'] = $ this-> config-> item ('base _ url ');
$ Data ['css '] = $ this-> config-> item ('css ');
$ Data ['mytitle'] = "A website to monitor other websites ";
$ Data ['text'] = "Please log in here! ";

$ This-> load-> view ('entrypage', $ data );
}

It calls the view: entrypage. The View contains a table that allows users to enter their usernames and passwords. The HTML table must specify a function for processing $ _ POST. we have put it in the start controller, that is, assessme (). In HTML code, the table on our view should be:



I have explained the assessme function a little. it accepts a user/password combination and I need to query it in a database. To make the code more structured, we need to introduce a function called checkme ().

Therefore, you will see that assessme () calls checkme () and Checkme () in the database to check whether the user exists and whether the password is valid, then, return 'yes' or 'non' to assessme (). If yes is returned, assessme () calls another function, mainpage (), and returns a view.

Pay attention to the benefits of the code module. Each function plays a role. If I need to change the system password check method, I only need to change the checkme () function. If you need to modify the page, you only need to modify the mainpage () function.

Let's take a look at the code structure and how each part interacts. (Note: To make the example concise, we do not verify user input. Of course, this will not cause problems. The CI table class automatically "sanitize" the input data ".

/* Es the username and password fromthe POST array */
Function assessme (){
$ Username = $ _ POST ['username'];
$ Password = $ _ POST ['password'];

/* The checkme function to see if the inputs are OK */
If ($ this-> checkme ($ username, $ password) = 'yes '){
/* If the inputs are OK, callthe mainpage function */
$ This-> mainpage ;()
}
/* If they are not OK, goes back to the index function, which re-presents the log-in screen */
Else
{
$ This-> index ();
}
}
/* Called with a u/n and p/w, this checks them against some list. for the moment, there's just one option. returns 'yes' or 'no '*/

Function checkme ($ username = '', $ password = ''){
If ($ username = 'Fred '& $ password = '000000 '){
Return 'yes ';
} Else {
Return ('no ';
}

}

On row 6, assessme () receives the $ _ POST array from the table, which contains the following data:

[Username] => fred
[Password] = & gt; 12345

The assessme () function passes these two variables to another function checkme (). This function checks if user fred with a password of 12345 is a legal user. if they are, it returns 'yes'. Obviously, it is more complicated on a real website. You may perform database queries for valid usernames/passwords. Defining it as a separate function means that I can test other parts of my code and improve the checkme () function later.

If the user name and password are a valid combination, the assessme () function calls another function mainpage () to allow the user to access the website. Otherwise, it returns to the index () function-that is, the logon window is displayed again.

The next question is how to handle the status. In other words, how to identify a logged-on user when entering another page.

Security/Session: use another CI class

How much code is required if I want to establish a session mechanism to ensure that unauthorized users cannot access my files?

The Internet works through a series of requests. Your browser sends a request to my server, requesting a specific page. My browser processes the page and returns it to your server. After processing, the server sends another page to the browser. you can press a hyperlink to send a new page request to my server. That's all.

The Internet is 'stateless '-that is, every request your browser makes to my server is treated as a separate event, HTTP cannot associate your request with any other request.

If you want to establish a connection between your website page and the page, you must manage the "status" and remember which requests come from your browser on the server, which requires special processing.

PHP provides two ways to manage the status: using cookies or using sessions. PHP session automatically checks whether your browser accepts cookies. if it does not, it uses the session ID method, which is passed directly through the URL.

Cookies are small pieces of data sent by the server to your browser. The browser automatically saves it. Once the cookie is saved, when the browser attempts to access the website, the website will check whether there is a cookie. If it finds the correct cookie, it can read the data in it and configure it as appropriate. It is possible to close a specific page or display your personal data.


Because some people set that their browsers do not accept cookies, PHP provides other alternatives. Each time a browser requests access, the website generates a 'session ID' and sends it to the browser. when the browser sends the next request, the ID is added to the URL, so the website can recognize the browser.

CI has a session class to process session-related work. In fact, it greatly reduces the amount of encoding. In the previous chapter, we learned that CI has various libraries, which greatly simplifies PHP programming. These are the core of the framework: integrating a large amount of code to provide you with various powerful functions. All you have to do is use them without worrying about how they work. As a result, your application uses the most specialized code, but you do not need to write them yourself!

If you want to use a function in a class in your controller or model, you must first load the class (for example, config is always automatically loaded, this is why we don't need to load it in code .)

You can load the library as follows:

$ This-> load-> library ('newclass ');

Generally, put this line in your controller or model constructor.

If you think that you will use a library in each controller, you can automatically load it like the config class. Find the/system/application/config/autoload file and add the class name you want to automatically load:

$ Autoload ['libraries'] = array ();

So it looks like this:

$ Autoload ['libraries'] = array ('newclass', 'oldclass ');

Here, we first need to use the session class, which helps you maintain the status and identify users. This is quite simple. The following lists the enhanced assessme () functions:

Function assessme (){

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

$ Username = $ _ POST ['username'];
$ Password = $ _ POST ['password'];

If ($ this-> checkme ($ username, $ password) = 'yes '){
$ This-> mainpage ;()
} Else {
$ This-> index ();
}
}

(You can see that the session library is loaded at the beginning of the function, but normally we will load it in the controller's constructor. therefore, other functions in this class can use this class .)

When this class is loaded, it immediately provides functions such as reading, creating, and modifying sessions through its powerful functions.

Well, frankly speaking, it's not just a line of code. You must first modify the config file to tell the session class what you want to do.

Check your system/application/config. php file and you will find a part like this:
--------------------------------------------------------------------------
| Session Variables
| --------------------------------------------------------------------------
|
| 'Session _ cookie_name '= the name you want for the cookie
| 'Encrypt _ sess_cookie '= TRUE/FALSE (boolean). Whether to encrypt the cookie
| 'Session _ Expiration' = the number of SECONDS you want the session to last.
| By default sessions last 7200 seconds (two hours). Set to zero for no expiration.
|
*/
$ Config ['sess _ cookie_name '] = 'ci _ session ';
$ Config ['sess _ expiration '] = 7200;
$ Config ['sess _ encrypt_cookie '] = FALSE;
$ Config ['sess _ use_database '] = FALSE;
$ Config ['sess _ table_name '] = 'ci _ session ';
$ Config ['sess _ match_ip '] = FALSE;
$ Config ['sess _ match_useragent '] = FALSE;

Now, make sure that [sess_use_database] is set to FALSE.

Save Settings. now, each time your customer logs on to the website, the website will save a cookie on your machine, containing the following data:

. A unique session id generated by CI, which is a string generated by CI for any combination of sessions.

. User's IP address

. User proxy data (the first 50 characters of browser data)

. Max validity period

If you set sess_encrypt_cookie to FALSE, you can see the cookie content in your browser: (it is partially encoded, but you can recognize it ):

Ip_address % 22% 3Bs % 39% 3% 22127.0.0.1% 22% 3Bs % 310% 3A22

This includes the user's URL, which is 127.0.0.1 in this example). If you set sess_encrypt_cookie to TRUE, the cookie is encrypted, just a line of meaningless code. The browser cannot recognize it, and the user cannot modify it.

When a user sends another page request, the website will check whether the session ID has been saved as a cookie on the user's machine. If yes, this will be part of an existing session, if not, a new session is created. Remember to load session classes on all other controllers. CI will perform the same check. All I have to do is tell each controller how to operate when no cookie is available.

Make sessions safer

This would not have caused security problems. Any user accessing the website will start a session. The code only determines whether they are a new user. One way to prevent unauthorized users from accessing certain pages is to add some information to the cookie if they have logged on, so we can verify this. Once the user enters the correct user name and password, it is recorded in the cookie. when a new request is sent, the session mechanism checks the cookie. if the user is logged on, return the page requested by the user. if not, return the logon screen.

It is easy to add information to cookies. In my assessme () controller, if the password and user name are verified, add the following code:

If ($ this-> checkme ($ username, $ password) = 'yes '){
$ Newdata = array (
'Status' => 'OK ',
);
$ This-> session-> set_userdata ($ newdata );
$ This-> mainpage ();
}

In this way, only one variable in the content in the $ newdata array is added to the cookie. Now, whenever the password/user name combination is acceptable, assessme () will add 'OK' to the cookie, and we can add the code to each controller:

/* Remember to load the library! */
$ This-> load-> library ('session ');

/* Look for a 'status' variable in the contents of the session cookie */
$ Status = $ this-> session-> userdata ('status ');

/* If it's not there, make the user log in */
If (! Isset ($ status) | $ status! = 'OK ')
{/* Function to present a login page again... */}

/* Otherwise, go ahead with the code */

In this way, you can build a secure foundation around your website. You can easily make it more refined. For example, if some of your users have more advanced permissions, you can save an access level code in the cookie, instead of simply putting it in an "OK ", you can use this for more detailed permission control.

It is worse to store plaintext data in a cookie because the user can open the cookie and view its content, and of course it can be easily modified. Therefore, using CI to encrypt cookies is a good method. In addition, you can create a user table in the database, modify the logon status of the user table after the user logs on, and maintain some permission attributes in the user table, it is also a good practice to read permission information from the user table of the database. if combined with the cache technology, the system performance problem will be solved.

It is very easy to save session data in your database. First, create a database table. If you are using MySQL, use this SQL statement:

Create table if not exists 'ci _ session '(
Session_id varchar (40) DEFAULT '0' not null,
Ip_address varchar (16) DEFAULT '0' not null,
User_agent varchar (50) not null,
Last_activity int (10) unsigned DEFAULT 0 not null,
Status varchar (5) DEFAULT 'no ',
Primary key (session_id)
);

Then, modify the connection parameter in the system/application/config/database. php file to tell the CI database where it is. For more information, see Chapter 4th.

If it works properly, you can add related data to your database table when you log on or exit. If you store a session in a database table, when the user logs on to your website, the website will find the cookie. if it finds the cookie, the session ID will be read, use this ID to match the ID saved in the database table.

You now have a strong session mechanism. All this requires only one line of code!

It is declared that PHP session classes can be handled when users disable the cookie function. (Instead of generating a cookie, it adds session data to the URL) the CI class will not do this. if you use CI, once the user disables the cookie, he cannot log on to your website. In this regard, features need to be enhanced. Hopefully Rich will soon upgrade CI.

Security

Note: The session class automatically saves information about the visitor's IP address and user. You can use some enhanced security measures.

You can add security by modifying the configuration in the config file:

. Sess_match_ip: If you set this parameter to TRUE, when it reads session data, CI will try to match the user's IP address. This prevents users from using the cookie information obtained by 'snatching. However, some servers (ISP and large company servers) may have login requests from the same user on different IP addresses. If you set this parameter to TRUE, it may cause problems for them.

. Sess_match_useragent: If you set this to TRUE, CI will try to match the user agent when reading session data. This means that the user who tries to "snatch" The session also needs to match the real user's user agent settings. It makes it a little difficult to "snatch.

CI also has a user_agent class. you can load it like this:

$ This-> load-> library ('User _ agent ');

Once loaded, you can ask it to return various information about the browsers and operating systems that access your website, whether it is a browser, mobile phone or robot. For example, if you want to list robots that visit your website, you can:

$ Fred = $ this-> agent-> is_robot ();
If ($ fred = TRUE)
{$ Agent = $ this-> agent-> agent_string ();
/* Add code here to store or analyze the name the user agent is returning */
}

The class starts to work after being loaded. it is compared with an array of other types such as agent, browser, robot, and other types. this array is stored in system/application/config/user_agents.

If you wish, you can easily develop functions that enable your website to lock specific robots and specific browser types. However, remember that an attacker can easily write a proxy type and return the type he wants to throw to you. Therefore, they can easily pretend to be common browsers. Many robots, including the Googlebot listed in the user_agents array like CI, are 'good status '. This means that if you set your robots.txt file to exclude them, they will not be forcibly attacked. There is no easy way to block an unknown manipulator, unless you know their names in advance!

In the CI framework, the session mechanism saves the requested IP address, so you can use this function to maintain a website blacklist. You can use the following code to retrieve the IP address from the session:

/* Remember to load the library! */
$ This-> load-> library ('session ');
/* Look for an 'IP _ address' variable in the contents of the session cookie */
$ Ip = $ this-> session-> userdata ('IP _ address ');

Therefore, you can perform security processing on the blacklist, such as rejecting logon.

You can also use the CI session mechanism to restrict damage from repeated requests-like a robot that repeatedly requests a webpage to overload your website. You can also use this mechanism to handle dictionary attacks, that is, a robot keeps trying hundreds or thousands of combinations of passwords/usernames until it finds the correct group.

Because the CI session class saves the last_activity of each session, you can do this. Each time, when a webpage is requested, you can check how long ago a user from this IP address sent a request. If the interval between the two requests is not normal, you can terminate the session, or slow down the response speed.

Summary

We have outlined an application we want to establish and the problems that almost all applications need to solve: Session management and security assurance.

To do this, we have learned the details of the CI session class and how it generates session records and generates cookies in the visitor's browser.

When subsequent requests occur, you can read cookies to control the response.

Next Chapter

CodeIgniter and object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.