CodeIgniter system Folder

The system/ folder is where all the action happens. This folder contains all the CodeIgniter code of
consequence, organized into various folders:

application —  The   application foldercontains the application you ’ re building. Basically, this
folder contains your models, views, controllers, and other code (like helpers and class
extensions). In other words, this folder is where you ’ ll do 99 percent of your work.

cache —  The   cache foldercontains all cached pages for your application. In Chapter 9 , you learn
more about caching and how to turn your super - speedy development application into a
blazingly fast live application.

codeigniter —  The   codeigniter folderis where CodeIgniter ’ s core classes live. You have almost no
reason to go in here. All of your work will occur in the application folder. Even if your intent is
to extend the CodeIgniter core, you would do it with hooks, and hooks live in the application
folder.

database —  The   database foldercontains core database drivers and other database utilities. Again,
there ’ s no good reason for you to be in this folder.
fonts —  The   fonts foldercontains font - related information and utilities. Again, there ’ s no reason
to spend any time here.

helpers —  The   helpers foldercontains standard CodeIgniter helpers (such as date, cookie, and
URL helpers). You ’ ll make frequent use of helpers in your CodeIgniter career and can even
extend helpers thanks to improvements introduced in CodeIgniter version 1.6.

language —  The   language foldercontains language files. You can ignore it for now.

libraries —  The   libraries foldercontains standard CodeIgniter libraries (to help you with e - mail,
calendars, file uploads, and more). You can create your own libraries or extend (and even
replace) standard ones, but those will be saved in the application/libraries directory to keep
them separate from the standard CodeIgniter libraries saved in this particular folder.

logs —  The   logs folderis the folder CodeIgniter uses to write error and other logs to.


plugins —  The   plugins foldercontains plugins. Plugins and helpers are very similar, in that they
both allow developers to quickly address an issue or create content like forms, links, etc..

However, the main difference between them is that plugins usually consist of one function,
while helpers often have many functions bundled inside them.

CodeIgniter config.php

The  config.php filecontains a series of configuration options all of them stored in a PHP array called,
appropriately enough, $config) that CodeIgniter uses to keep track of your application ’ s  information
and settings.

The first configuration option you need to set inside config.php is the base URL of your application. You
do that by setting the absolute URL (including the http:// part) for $config[ ‘ base_url ’ ], like so:
$config[‘base_url’] = “http://www.example.com/test/”;

Once  you ’ ve set this configuration option, you can recall it whenever you want using the CodeIgniter
base_url()function, which can be a very handy thing to know. This one feature keeps you from
having to rewrite hard - coded URLs in your application, when you migrate from development to test or
from test to production.

The second thing you need to do is set a value for your home page by editing the $config[ ‘ index_
page ’ ]configuration option. CodeIgniter ships with a value of “ index.php ”  for  this  option,  which
means that index.php will appear in all of your URLs. Many CodeIgniter developers prefer to keep this
value blank, like so:
$config[‘index_page’] = ‘’;
To make this work, you need to include an .htaccess file to the CodeIgniter root directory, After  you ’ ve set this option value, there ’ s very little to do.
 For now, leave all the other values at their
default settings:
$config[‘uri_protocol’] = “AUTO”;
$config[‘url_suffix’] = “”;
$config[‘language’] = “english”;
$config[‘charset’] = “UTF-8”;
$config[‘enable_hooks’] = FALSE;
$config[‘subclass_prefix’] = ‘MY_’;
$config[‘permitted_uri_chars’] = ‘a-z 0-9~%.:_-’;
$config[‘enable_query_strings’] = FALSE;
$config[‘controller_trigger’] = ‘c’;
$config[‘function_trigger’] = ‘m’;
$config[‘log_threshold’] = 0;
$config[‘log_path’] = ‘’;
$config[‘log_date_format’] = ‘Y-m-d H:i:s’;


$config[‘cache_path’] = ‘’;
$config[‘encryption_key’] = “enter_a_32_character_string_here”;
$config[‘sess_cookie_name’] = ‘ci_session’;
$config[‘sess_expiration’] = 7200;
$config[‘sess_encrypt_cookie’] = TRUE;
$config[‘sess_use_database’] = FALSE;
$config[‘sess_table_name’] = ‘ci_sessions’;
$config[‘sess_match_ip’] = FALSE;
$config[‘sess_match_useragent’] = TRUE;
$config[‘cookie_prefix’] = “”;
$config[‘cookie_domain’] = “”;
$config[‘cookie_path’] = “/”;
$config[‘global_xss_filtering’] = TRUE;
$config[‘compress_output’] = FALSE;
$config[‘time_reference’] = ‘local’;
$config[‘rewrite_short_tags’] = FALSE

For more details on each of these configuration options, simply read the comments embedded in /
system/application/config/config.php. You will also get more detail on certain settings as you work
through the sections of the book and tweak the configuration as needed. For example, at some point, you
will want to use encryption for security purposes or set your logging threshold for debugging, and they
both require making changes to this file.

CodeIgniter ’ s Global XSS Filtering option is set to FALSE by default. The online User Guide suggests
that setting this to TRUE adds a lot of performance overhead to the system. However, at this point, it is
better to have some global protection put in place. That way you can be assured of some security
precautions while you ’ re in development. Chapter 9 discusses security issues in more depth, but for
now, it ’ s good to have something in place while you ’ re  developing.

In the same security vein, notice that sess_encrypt_cookie has been set to TRUE, and that you are to
enter a 32 - character encryption salt in encryption_key. Doing these two things will encrypt any
sessions and provide a salt for any hashing methods you use. Be sure to use a random string of upper -
and lowercase letters and numbers.

One final note before moving on: Make sure that you write down your encryption key and keep it safe
somewhere, or, at least, maintain good backups. You ’ ll need the key to retrieve other information, so if
your site is compromised or erased or if you lose your key any other way, you ’ ll be glad you have a
record  of  it.

Yahoo! Directory

While Yahoo! Search tries to include as many sites as possible in its index, the Yahoo! Directory is more like an exclusive club, where sites have to be approved by Yahoo! Editors. Because Yahoo! wants to maintain a highly useful directory, the steps for inclusion are a bit more involved.
To see if your site is already listed in the Yahoo! Directory, browse to http://dir.yahoo.com and search for the title of your site. If you don't see your site among the results, you can suggest your site to the Yahoo! Directory.

The first thing you need to determine about your site is whether it's commercial or noncommercial, because you'll need to pay $299 to submit a commercial site. According to Yahoo!, "If your site sells something, promote[s] goods and services, or represents a company that sells products and/or services," your site is commercial and should be listed somewhere in the Business and Economy category within the directory. If your site is purely personal, informational, or not-for-profit, your site is noncommercial. A banner ad or text ad on your site doesn't necessarily make your site commercial; if you have such an ad, it'll be up to the Yahoo! Editors to decide whether your site is commercial.


Adding a noncommercial site.
The first step to adding a noncommercial site is to find the appropriate category for your site. If you know of some sites that are similar to yours, you might try searching for the titles of those sites within the directory to see how they're categorized. Otherwise, start browsing through the directory at http://dir.yahoo.com for the most appropriate place for your site. If your site is a personal home page, browse to "Society and Culture"  People  Personal Home Pages. If your site is a weblog, you'll want to browse to "Computers and Internet"  Internet  World Wide Web  Weblogs.
Once you've found the appropriate category, click the "Suggest a Site" link at the top of the page. Choose Standard Consideration and follow the instructions for adding a site. You'll have the option to include a site title, URL, geographic location, and description. If you have suggestions about other categories that your site might be appropriate for, you can include those suggestions in notes to Yahoo! Editors.
Once you've made your submission, the waiting game begins. Yahoo! doesn't guarantee that all sites submitted will be reviewed, and many sites are not included in the directory. If your site doesn't show up in the directory within two or three weeks, you can resubmit your site using the same process. Multiple submissions in a short period of time could exclude your site from consideration altogether. To be guaranteed a response about your site's placement within the directory, you can submit your site as if it were a commercial site, paying the commercial fee.


What is Web browser?

Software that lets a user view HTML documents and access files and software related to those documents. Originally developed to allow users to view or browse documents on the World Wide Web, Web browsers can blur the distinction between local and remote resources for the user by also providing access to documents on a network, an intranet, or the local hard drive. Web browser software is built on the concept of hyperlinks, which allow users to point and click with a mouse in order to jump from document to document in whatever order they desire. Most Web browsers are also capable of downloading and transferring files, providing access to newsgroups, displaying graphics embedded in the document, playing audio and video files associated with the document, and executing small programs, such as Java applets or ActiveX controls included by programmers in the documents. Helper applications or plug-ins are required by some Web browsers to accomplish one or more of these tasks. Also called: browser.

What is timing attack?

An attack on a cryptographic system that exploits the fact that different cryptographic operations take slightly different amounts of time to process. The attacker exploits these slight time differences by carefully measuring the amount of time required to perform private key operations. Taking these measurements from a vulnerable system can reveal the entire secret key. Cryptographic tokens, network-based cryptosystems, and other applications where attackers can make reasonably accurate timing measurements are potentially at risk from this form of attack.

What is macro assembler?

An assembler that can perform macro substitution and expansion. The programmer can define a macro that consists of several statements and then use the macro name later in the program, thus avoiding having to rewrite the statements. For example, a macro called swap exchanges the values of two variables: After defining swap, the programmer can then insert an instruction such as “swap a, b” in the assembly language program. While assembling, the assembler replaces the instruction with the statements within the macro that swap the values of the variables a and b.

E-Mail Security

When an e-mail message is sent between two distant sites, it will generally transit dozens of machines on the way. Any of these can read and record the message for future use. In practice, privacy is nonexistent, despite what many people think. Nevertheless, many people would like to be able to send e-mail that can be read by the intended recipient and no one else: not their boss and not even their government. This desire has stimulated several people and groups to apply the cryptographic principles we studied earlier to e-mail to produce secure e-mail. In the following sections we will study a widely-used secure e-mail system, PGP, and then briefly mention two others, PEM and S/MIME. For additional information about secure e-mail.

PGP supports four RSA key lengths. It is up to the user to select the one that is most appropriate. The lengths are
  1. Casual (384 bits): can be broken easily today.
  2. Commercial (512 bits): breakable by three-letter organizations.
  3. Military (1024 bits): Not breakable by anyone on earth.
  4. Alien (2048 bits): Not breakable by anyone on other planets, either.

Since RSA is only used for two small computations, everyone should use alien strength keys all the time.

Key management has received a large amount of attention in PGP as it is the Achilles heel of all security systems. Key management works as follows. Each user maintains two data structures locally: a private key ring and a public key ring. The private key ring contains one or more personal private-public key pairs. The reason for supporting multiple pairs per user is to permit users to change their public keys periodically or when one is thought to have been compromised, without invalidating messages currently in preparation or in transit. Each pair has an identifier associated with it so that a message sender can tell the recipient which public key was used to encrypt it. Message identifiers consist of the low-order 64 bits of the public key. Users are responsible for avoiding conflicts in their public key identifiers. The private keys on disk are encrypted using a special arbitrarily long password to protect them against sneak attacks.

The public key ring contains public keys of the user's correspondents. These are needed to encrypt the message keys associated with each message. Each entry on the public key ring contains not only the public key, but also its 64-bit identifier and an indication of how strongly the user trusts the key.


Digital Signatures

The authenticity of many legal, financial, and other documents is determined by the presence or absence of an authorized handwritten signature. And photocopies do not count. For computerized message systems to replace the physical transport of paper and ink documents, a method must be found to allow documents to be signed in an unforgeable way.
The problem of devising a replacement for handwritten signatures is a difficult one. Basically, what is needed is a system by which one party can send a signed message to another party in such a way that the following conditions hold:

  1. The receiver can verify the claimed identity of the sender.
  2. The sender cannot later repudiate the contents of the message.
  3. The receiver cannot possibly have concocted the message himself.

The first requirement is needed, for example, in financial systems. When a customer's computer orders a bank's computer to buy a ton of gold, the bank's computer needs to be able to make sure that the computer giving the order really belongs to the company whose account is to be debited. In other words, the bank has to authenticate the customer (and the customer has to authenticate the bank).
The second requirement is needed to protect the bank against fraud. Suppose that the bank buys the ton of gold, and immediately thereafter the price of gold drops sharply. A dishonest customer might sue the bank, claiming that he never issued any order to buy gold. When the bank produces the message in court, the customer denies having sent it. The property that no party to a contract can later deny having signed it is called nonrepudiation. The digital signature schemes that we will now study help provide it.
The third requirement is needed to protect the customer in the event that the price of gold shoots up and the bank tries to construct a signed message in which the customer asked for one bar of gold instead of one ton. In this fraud scenario, the bank just keeps the rest of the gold for itself.

Symmetric-Key Signatures

One approach to digital signatures is to have a central authority that knows everything and whom everyone trusts, say Big Brother (BB). Each user then chooses a secret key and carries it by hand to BB's office. Thus, only Alice and BB know Alice's secret key, KA, and so on.
When Alice wants to send a signed plaintext message, P, to her banker, Bob, she generates KA(B, RA, t, P), where B is Bob's identity, RA is a random number chosen by Alice, t is a timestamp to ensure freshness, and KA(B, RA, t, P) is the message encrypted with her key, KABB sees that the message is from Alice, decrypts it, and sends a message to Bob as shown. The message to Bob contains the plaintext of Alice's message and also the signed message KBB (A, t, P). Bob now carries out Alice's request.

Public-Key Signatures

A structural problem with using symmetric-key cryptography for digital signatures is that everyone has to agree to trust Big Brother. Furthermore, Big Brother gets to read all signed messages. The most logical candidates for running the Big Brother server are the government, the banks, the accountants, and the lawyers. Unfortunately, none of these organizations inspire total confidence in all citizens. Hence, it would be nice if signing documents did not require a trusted authority.
Fortunately, public-key cryptography can make an important contribution in this area. Let us assume that the public-key encryption and decryption algorithms have the property that E(D(P)) = P in addition, of course, to the usual property that D(E(P)) = P. (RSA has this property, so the assumption is not unreasonable.) Assuming that this is the case, Alice can send a signed plaintext message, P, to Bob by transmitting EB(DA(P)). Note carefully that Alice knows her own (private) key, DA, as well as Bob's public key, EB, so constructing this message is something Alice can do.


Network Security


For the first few decades of their existence, computer networks were primarily used by university researchers for sending e-mail and by corporate employees for sharing printers. Under these conditions, security did not get a lot of attention. But now, as millions of ordinary citizens are using networks for banking, shopping, and filing their tax returns, network security is looming on the horizon as a potentially massive problem. In this chapter, we will study network security from several angles, point out numerous pitfalls, and discuss many algorithms and protocols for making networks more secure.

Security is a broad topic and covers a multitude of sins. In its simplest form, it is concerned with making sure that nosy people cannot read, or worse yet, secretly modify messages intended for other recipients. It is concerned with people trying to access remote services that they are not authorized to use. It also deals with ways to tell whether that message purportedly from the IRS saying: Pay by Friday or else is really from the IRS and not from the Mafia. Security also deals with the problems of legitimate messages being captured and replayed, and with people trying to deny that they sent certain messages.

Network security problems can be divided roughly into four closely intertwined areas: secrecy, authentication, nonrepudiation, and integrity control. Secrecy, also called confidentiality, has to do with keeping information out of the hands of unauthorized users. This is what usually comes to mind when people think about network security. Authentication deals with determining whom you are talking to before revealing sensitive information or entering into a business deal. Nonrepudiation deals with signatures: How do you prove that your customer really placed an electronic order for ten million left-handed doohickeys at 89 cents each when he later claims the price was 69 cents? Or maybe he claims he never placed any order. Finally, how can you be sure that a message you received was really the one sent and not something that a malicious adversary modified in transit or concocted?

All these issues (secrecy, authentication, nonrepudiation, and integrity control) occur in traditional systems, too, but with some significant differences. Integrity and secrecy are achieved by using registered mail and locking documents up. Robbing the mail train is harder now than it was in Jesse James' day.
Also, people can usually tell the difference between an original paper document and a photocopy, and it often matters to them. As a test, make a photocopy of a valid check. Try cashing the original check at your bank on Monday. Now try cashing the photocopy of the check on Tuesday. Observe the difference in the bank's behavior. With electronic checks, the original and the copy are indistinguishable. It may take a while for banks to learn how to handle this.

PHP Networking Functions

People authenticate other people by recognizing their faces, voices, and handwriting. Proof of signing is handled by signatures on letterhead paper, raised seals, and so on. Tampering can usually be detected by handwriting, ink, and paper experts. None of these options are available electronically. Clearly, other solutions are needed.

Before getting into the solutions themselves, it is worth spending a few moments considering where in the protocol stack network security belongs. There is probably no one single place. Every layer has something to contribute. In the physical layer, wiretapping can be foiled by enclosing transmission lines in sealed tubes containing gas at high pressure. Any attempt to drill into a tube will release some gas, reducing the pressure and triggering an alarm. Some military systems use this technique.

Introduction to Cryptography

Historically, four groups of people have used and contributed to the art of cryptography: the military, the diplomatic corps, diarists, and lovers. Of these, the military has had the most important role and has shaped the field over the centuries. Within military organizations, the messages to be encrypted have traditionally been given to poorly-paid, low-level code clerks for encryption and transmission. The sheer volume of messages prevented this work from being done by a few elite specialists.

Until the advent of computers, one of the main constraints on cryptography had been the ability of the code clerk to perform the necessary transformations, often on a battlefield with little equipment. An additional constraint has been the difficulty in switching over quickly from one cryptographic method to another one, since this entails retraining a large number of people. However, the danger of a code clerk being captured by the enemy has made it essential to be able to change the cryptographic method instantly if need be. 

The messages to be encrypted, known as the plaintext, are transformed by a function that is parameterized by a key. The output of the encryption process, known as the ciphertext, is then transmitted, often by messenger or radio. We assume that the enemy, or intruder, hears and accurately copies down the complete ciphertext. However, unlike the intended recipient, he does not know what the decryption key is and so cannot decrypt the ciphertext easily. Sometimes the intruder can not only listen to the communication channel (passive intruder) but can also record messages and play them back later, inject his own messages, or modify legitimate messages before they get to the receiver (active intruder). The art of breaking ciphers, called cryptanalysis, and the art devising them (cryptography) is collectively known as cryptology.

The nonsecrecy of the algorithm cannot be emphasized enough. Trying to keep the algorithm secret, known in the trade as security by obscurity, never works. Also, by publicizing the algorithm, the cryptographer gets free consulting from a large number of academic cryptologists eager to break the system so they can publish papers demonstrating how smart they are. If many experts have tried to break the algorithm for 5 years after its publication and no one has succeeded, it is probably pretty solid.
Since the real secrecy is in the key, its length is a major design issue. Consider a simple combination lock. The general principle is that you enter digits in sequence. Everyone knows this, but the key is secret. A key length of two digits means that there are 100 possibilities. A key length of three digits means 1000 possibilities, and a key length of six digits means a million. The longer the key, the higher the work factor the cryptanalyst has to deal with. The work factor for breaking the system by exhaustive search of the key space is exponential in the key length. Secrecy comes from having a strong (but public) algorithm and a long key. To prevent your kid brother from reading your e-mail, 64-bit keys will do. For routine commercial use, at least 128 bits should be used. To keep major governments at bay, keys of at least 256 bits, preferably more, are needed.

From the cryptanalyst's point of view, the cryptanalysis problem has three principal variations. When he has a quantity of ciphertext and no plaintext, he is confronted with the ciphertext-only problem. The cryptograms that appear in the puzzle section of newspapers pose this kind of problem. When the cryptanalyst has some matched ciphertext and plaintext, the problem is called the known plaintext problem.

The next improvement is to have each of the symbols in the plaintext, say, the 26 letters for simplicity, map onto some other letter. For example,
plaintext: a b c d e f g h i j k l m n o p q r s t u v w x y z
ciphertext: Q W E R T Y U I O P A S D F G H J K L Z X C V B N M
The general system of symbol-for-symbol substitution is called a monoalphabetic substitution, with the key being the 26-letter string corresponding to the full alphabet. For the key above, the plaintext attack would be transformed into the ciphertext QZZQEA.



Program Yahoo! with PHP 5

Take advantage of some of the latest features in PHP to quickly add Yahoo! data to PHP-powered pages.
The recursively named PHP Hypertext Processor language is a popular choice for building dynamic web applications. In fact, Yahoo! itself has made PHP its development platform of choice across the company.

 The PHP platform is continually evolving, and the latest version Version 5 includes a handy XML parser called SimpleXML. As the name implies, it's easy to work with. And as long as the XML that SimpleXML is parsing is fairly simple, it's the perfect tool for getting XML data into objects PHP can easily manipulate.
Yahoo! Search Web Services responses definitely qualify as simple XML, and this hack shows how easy it is to request and parse this data with PHP. You'll need PHP 5 for this hack, but you won't need any external modules.

<?php
// yahoo_search.php
// Accepts a search term and shows the top results.
// Usage: yahoo_search.php?p=<Query>
//
// You can create an AppID, and read the full documentation
// for Yahoo! Web Services at http://developer.yahoo.net/

// Set your unique Yahoo! Application ID
$appID = "insert your app ID";

// Grab the incoming search query, and encode for a URL
$query = $_GET['p'];
$query = urlencode($query);

if ($query == "") { 
 print "usage: yahoo_search.php?p=&lt;Query&gt;"; die;
}

// Construct a Yahoo! Search Query with only required options
$language = "en";
$req_url = "http://api.search.yahoo.com/";
$req_url .= "WebSearchService/V1/webSearch?";
$req_url .= "appid=$appID";
$req_url .= "&query=$query";
$req_url .= "&language=$language";

// Make the request
$yahoo_response = file_get_contents($req_url);

// Parse the XML
$xml = simplexml_load_string($yahoo_response);

// Initialize results counter
$i = 0;
?>
<html>

<body>
<h2>Yahoo! Search Results</h2>
<ol>
<?php
// Loop through the items returned, printing them out
foreach ($xml->Result as $result) {
 $i++;
 $title = $result->Title;
 $summary = $result->Summary;
 $summary = preg_replace("/</i","&lt;",$summary);
 $clickurl = $result->ClickUrl;
 $url = $result->Url;
 print "<li><div style=\"margin-bottom:15px;\">";
 print "<a href=\"$clickurl\">$title</a><br />";
 print "$summary<br />";
 print "<cite>$url</cite></div></li>\n";

}
?>
</ol>
-- Results Powered by Yahoo!
</body>
</html>

This script uses the value of the querystring variable p to build a Yahoo! Web Search request URL and fetches the XML with the file_get_contents() function. Once the script has the XML in the $yahoo_response string, it calls the SimpleXML function simplexml_load_string( ), which parses the XML and makes the data available to PHP as an object. Finally, the script loops through the objects, using print to send the data to the browser.

To run the script, point your web browser to the location of the script on your server and add the querystring variable p:
http://example.com/yahoo_search.php?p=insert word

You can add multiple words by encoding spaces for URLs. For example, here's the search string for "PHP encoding":
http://example.com/yahoo_search.php?p=PHP%20encoding
 
As the results indicate, you can read the official documentation for PHP's 
SimpleXML function at http://www.php.net/simplexml. With this function, working with 
Yahoo! Search Web Services data is much more 
intuitive than with earlier versions of PHP.