官术网_书友最值得收藏!

Creating the model

The Urls_model contains three functions; obviously it contains our __construct() function but we're not focusing on that at the moment as it's not doing anything except referencing its parent.

Instead, let's look at the two functions save_url() and fetch_url(). As their names suggest, one saves information to the database and the other fetches information from it. For now, let's go and create the code and we'll discuss in detail what each function does later: Create the urls_model.php model file and add the following code to it:

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

class Urls_model extends CI_Model {
  function __construct() {
    parent::__construct();
  }

  function save_url($data) {
    /*
    Let's see if the unique code already exists in 
    the database.  If it does exist then make a new 
    one and we'll check if that exists too.  
    Keep making new ones until it's unique.  
    When we make one that's unique, use it for our url 
    */
    do {
      $url_code = random_string('alnum', 8); 

      $this->db->where('url_code = ', $url_code);
      $this->db->from('urls');
      $num = $this->db->count_all_results();
    } while ($num >= 1);

    $query = "INSERT INTO `urls` (`url_code`, `url_address`) VALUES (?,?) ";
    $result = $this->db->query($query, array($url_code, $data['url_address']));

    if ($result) {
      return $url_code;
    } else {
      return false;
    }
  }

  function fetch_url($url_code) {
    $query = "SELECT * FROM `urls` WHERE `url_code` = ? ";
    $result = $this->db->query($query, array($url_code));
    if ($result) {
      return $result;
    } else {
      return false;
    }
  }
}

Let's take a look at save_url(). Notice the PHP construct do...while; it looks something like the following:

do {
// something
} while ('…a condition is not met');

So that means do something while a condition is not met.

Now, with that in mind, think about our problem. We have to associate the URL that the user has entered in the form with a unique value. We will use this unique value to represent the real URL.

Now there's no point using a sequential number (1, 2, 3, … 1000) as our unique value as someone can come along and iterate up through the numbers and get access to everyone's URLs. This may not be such a dreadful security risk as presumably all pages are accessible from the Internet anyway, but it's still not a good idea. So the unique value must not only be unique, it must be random and not easily guessed by passersby. Also, this unique value must only exist once in the database.

To ensure this, we will have to check if the unique value already exists and, if it does exist, make a new unique code and check in the database again.

So, let's look at the do while construct in the save_url() function in a bit more detail. The following is the code:

do {
            $url_code = random_string('alnum', 8); 

            $this->db->where('url_code = ', $url_code);
            $this->db->from('urls');
            $num = $this->db->count_all_results();
        } while ($num>= 1);

We use CodeIgniter's String helper and its random_string() function (make sure you include the String helper using $this->load->helper('string'); in your controllers' constructor). The random_string() function will create (as the name suggests) a random string of characters that we will use for our unique code.

In this case, we're asking random_string() to give us a string of characters made up of numbers and uppercase and lowercase letters; that string should be no more that 8 digits in length.

We then look into the database to see if the code random_string() has made for us already exists. We'll use the $this->db->count_all_results(); CodeIgniter function to count up the number of matching results.

If the unique string already exists, then the number returned by $this->db->count_all_results(); will be equal to 1 (as it already exists). If this happens, we will loop back to the beginning of the do while construct and start again by generating a new code.

We keep doing this until we find a code that does not exist in the database. When we do, we break out of the do while loop and save that unique code, along with the original URL to the database.

Now let's look at fetch_url(). We want to see if there is a record in the database that corresponds to the $url_code entered by the user (in this case, they have clicked on a URL). The fetch_url() function accepts $url_code as a function argument passed to it by the controller and looks for it in the database. If it is found, the entire record (table row) is returned to the controller; if not, it returns false. The controller handles the false result accordingly (it displays an error).

主站蜘蛛池模板: 淮滨县| 礼泉县| 布尔津县| 迁安市| 罗定市| 潞城市| 湖北省| 洛川县| 伊宁市| 孟州市| 大城县| 湘乡市| 新龙县| 和平区| 慈溪市| 崇左市| 海南省| 汶上县| 会昌县| 济阳县| 兴化市| 鄂尔多斯市| 鹤山市| 济宁市| 贞丰县| 石屏县| 都匀市| 宿迁市| 泸西县| 宁乡县| 寻乌县| 鄂托克旗| 丰宁| 奉节县| 和硕县| 靖江市| 台北县| 湘乡市| 吴江市| 岳阳市| 北川|