Skip to main content

Posts

Showing posts from May, 2012

Data Encryption

Data encryption is the process of scrambling stored or transmitted information so that it is unintelligible until it is unscrambled by the intended recipient. The intended recipient can then decode (or decrypt) the information. PHP offers multiple means to make this happen. However, none of these solutions are very effective without the applications running on secure servers and connections. The following are a list of the more common encryption functions in PHP: • md5() - MD5 is a third-party hash algorithm that PHP can use to create a digital fingerprint of a piece of data. It is next to impossible to (efficiently) recover the original text when a piece of data has been encrypted with the md5 hash algorithm. It is also vastly unlikely that any different text string will create an identical hash - a 'hash collision'. These properties make hashes ideally suited for storing an application's passwords because although an attacker may compromise a part of the system

Database Authentication

The final, and most complete of the three PHP authentication methods, is the utilization of a database to maintain and manage the usernames and passwords used to access PHP files. This solution provides advanced capabilities in administering authentication systems but also provides incredible flexibility and scalability to incorporate the authentication system into the database system as a whole. The first step of the process involves creating the user tables that will be used to house the authentication data. Storing Authentication Data The following table will be used to manage the storage of the login information that will be used by PHP to manage logins: CREATE TABLE `customers` ( `customerEmail` VARCHAR(40) NOT NULL, `lname` VARCHAR(25) NOT NULL, `fname` VARCHAR(25) NOT NULL, `title` ENUM('Mr.', 'Mrs.', 'Miss', 'Ms.','Dr.'), `passwd` VARCHAR(30), PRIMARY KEY (`customerEmail`) ); The idea of using the customerEmail as the lo

File-Based Authentication

Using file-based authentication can eliminate the single username and password problem of the hard-coded solution; however, there can still be limitations that must be considered in implementing this authentication solution. The first things that needs to be created when using this solution to authentication is to create a users text file. This file should be located in a directory that is not in or under the htdocs directory of the web server (to eliminate someone being able to access the file through the website). It also needs to be in a directory that the server can read and write from. For the example below, the /tmp directory will be used; however, in production this directory should not be used because it is cleaned out every time the server restarts and is easily accessible to anyone who can access the server. The Users Text File The following is the contents of the /tmp/auth_users.txt file: Candance:90e0b2ef171cf8edd7f58527f3134f634ccb7091 Celine:44c40e17b33ee3f

PHP Authentication

When addressing the need to authenticate a web page (and subsequent pages/resources), integrating user authentication directly into the design of the web application logic is both convenient (in the sense that additional layers of communication is unnecessary) and flexible (in the sense that it is easier to integrate into other applications/scripts when contained in one location). PHP allows three types of authentication: Hard-coded, file-based and database authentication. Authentication Variables Within PHP, there are two pre-defined variables that are used in the authentication of users: • $_SERVER['PHP_AUTH_USER'] - This variable holds the username that is needed for authentication. • $_SERVER['PHP_AUTH_PW'] - This variable holds the password that is needed for authentication. Limitations of Authentication Variables When using the predefined authentication variables, it is important to keep in mind the following limitations: • Both variables must

Hard-Coded Authentication

This is the simplest PHP authentication to implement but has the problem of being limited on flexibility and high on maintenance cost. It literally places the username and password into the script as seen in the following example: <?php if (($_SERVER['PHP_AUTH_USER'] != 'root') || ($_SERVER['PHP_AUTH_PW'] != 'training')) { header('WWW-authenticate: Basic Realm="Photo Album"'); header('HTTP/1.0 401 Unauthorized'); print "You must provide a valid username and password!"; exit; } // Remainder of script ?> In this example, the first portion of the script reads in the username and password variables. If the variables do not match the hard-coded user name or password, then the script prints out some HTTP header information and text saying that the username and/or password was not valid. It then exits the script and terminates the rest of the script processing. If, though, the username and password ar

Session Handling Configuration Options

By default, the time that a session handler remains on the client side is set to 0, meaning that the session identifier will be "lost" when the web browser that initiated the original session handler page is shut down. This can be changed in the php.ini file by the configuration setting of session.cookie_lifetime. This is one of many configuration options that must be considered when setting up session handling for the specific instance of PHP: • session.save_handler - This configuration options defines the method in which the storage of the session will be handled. There are three options to choose from: o files - This method is the default and the most common. When this setting is set, the session handler uses files on the operating system to track the session information. o mm - This method stores the session information in shared RAM. Of the three, this option is the fastest but also the most volatile. o user - This method refers to using user-defined func

PHP Session Handling with MySQL

There are many ways that session handling can be used to provide a dynamic and non-static experience for the end user. Sessions can be used for providing a more personal experience for the end users by keeping track of them as they roam through a site providing content that is more tailored to their likes and dislikes (by monitoring the choices they make in what they choose to view). Sessions can also be used to make sure that only those who have a valid username and password can gain access to a specific part of a site, or in the case of any online store; keep track of what is in the shopping chart at any given time. These are just some examples of how session handling have added value to the web experience. MySQL is a perfect companion to session handling by being able to help with the process of storing and retrieving the data that gives extra life to the session handling capabilities. With the ability to connect multiple types of information (data stored in the database s

Terminating a Session

There are times when it is necessary (and good practice) to terminate a session and destroy all data associated with the current session. The function session_destroy is responsible for handling the described actions; however, this function is limited in its ability by not unsetting (or clearing) the global variables tied to the session or the respective cookies. This requires a more detailed approach: <?php session_start(); // Unset all session variables $_SESSION = array(); // Unset all cookie variables if(isset($_COOKIE[session_name()])){ setcookie(session_name(),'', time()-48000,'/'); } ?>

Encoding/Decoding Session Data

PHP stores all the session data associated with a session ID in a single string and handles the decoding of this string automatically. However, there are times when it may be necessary or beneficial to handle this process manually. The first thing to understand is how the string is put together. In the following example, three session variables are stored (last name, first name and phone number): lname|s:6:"Gordon";fname|s:6:"Jethro";phone|s:10:"7197235674"; The session variables are separated by a semicolon (;) and then can be broken down into their individual components: name of the variable, length of the string that is contained and the value itself. For the session variable lname, the length of the string is 6 characters long and the value that is stored in the string is "Gordon". Encoding the Session Variables The function session_encode allows for all the session variables available to the user to be encoded into a single

Retrieving the Session Data

Once the session data has been stored, retrieving (or recalling) this information is also very easy to setup. The following demonstrates how this is accomplished: <?php print "Dear ".$_SESSION['fname']." ".$_SESSION['lname'].","; ?>

Storing the Session Data

Once the session has been initialized, the data that must remain persistently can be stored in the superglobal $_SESSION array. The following are examples of storing persistence data to this superglobal array: <?php $_SESSION['fname'] = 'George'; $_SESSION['lname'] = 'Burnes'; ?>

Session Handling Tasks

As stated earlier, the process of PHP maintaining information from one session to the next for a visitor is pretty straight forward without lacking in capability. This maintaining of information (getting to know the end user) is accomplished through session handling tasks. Starting a Session It is necessary to tell PHP when to open up its eyes and prepare for the possibility of having to get to know an end user. This process is accomplished through the function session_start(). This function initializes the session data or continues the current session that is being passed by a request, such as a GET, POST or a cookie. <?php session_start(); ?> Setting up the Session "Key" After starting the session process, it is important to identify the "key" by which the user will be remembered. This key is stored on the end users machine and is called when interacting with the end user machine with the same function; session_id(). <?php session_s

SESSION HANDLING

What is Session Handling Hyper Text Transfer Protocol (HTTP) is the method on which information is transferred from a server to a client on the world wide web. This protocol is static in nature, that is every request is a new request and no persistence (or memory of a previous transfer) remains within the protocol itself. This has its advantages in the form of safety, the requests by either the client or the server has no long term affects on the other. This provides a level of security that could be related to a friendly acquaintance with each other and no long term affects are felt by the interaction. However, for the application developer (and dare it be said, also for the end user), there are times when a more intimate relationship is needed to add value to the experience. This is where session handling comes in. Basically, when a user interacts with a web page, the application attempts to get to know the person and retain a memory of their visit. Maintaining State I

MySQL Error Information

Even though developers (most at least) strive for an application free of bugs, no application (except minor projects) can be expected to be completely bug-free. For that purpose, a good practice for programmers is to build in code that will trap and display errors in a way that is both meaningful and useful to assist in the correction of the error. PHP offers two functions that can display error messages from MySQL: • mysql_error() - This function displays the error message (if there was one) from the last MySQL function. The language that the message will be displayed in is based on the target language that is setup in the MySQL server. However, even if a fluent speaker of the message language were to read the majority of error messages returned, they would most likely still have a difficult time understanding what was said. Needless to say, error messages from MySQL are not very verbose or informative. <?php // Load variables used in mysql_connect and connect to serv

PHP Functions for Retrieving Metadata

The most complete way to retrieve metadata is by using a SELECT statement against the INFORMATION_SCHEMA database in the MySQL server. However, there are times that is overkill for the data needing to be collected for a PHP application. With that said, PHP offers multiple functions that provide methods for retrieving a small amount of metadata about the data in the MySQL server. Database Metadata The mysql_list_dbs() function retrieves the name of all the databases found on the server that are accessible by the user requesting the information: <?php // Load variables used in mysql_connect and connect to server include "connect_info.php"; $linkID1 = mysql_connect($dbhost,$dbuser,$dbpass) or die("Could not connect to MySQL server"); // Retrieve the names of the databases accessible by the user $schema_results = mysql_list_dbs($linkID1); print "The databases available to the root user are:<br>\n"; while (list($schema) = mysql_fetch

Viewing MySQL Metadata

The INFORMATION_SCHEMA is a virtual database that is automatically created and populated by MySQL, there is no need to create an INFORMATION_SCHEMA database. There also is no associated file structure due to the fact that the contents of the data are actual views, rather than logical data being stored in any one location. Only SELECT statements are allowed against the tables in the INFORMATION_SCHEMA database. The following SELECT example demonstrates some of the metadata that can be viewed: <?php // Load variables used in mysql_connect and connect to server include "connect_info.php"; $linkID1 = mysql_connect($dbhost,$dbuser,$dbpass) or die("Could not connect to MySQL server"); // Execute Query to Collect Metadata $query = "SELECT TABLE_NAME, ENGINE, TABLE_ROWS, UPDATE_TIME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='world'"; $results = mysql_query($query, $linkID1); // Build HTML Table of Results print "<table

MySQL Metadata

Databases contain data, but information about the way databases are structured is metadata. The primary way of obtaining metadata is by using the INFORMATION_SCHEMA database to access metadata. MySQL produces metadata for several aspects of database structure. To name a few, metadata can be obtained from such database information as names of databases and tables, information about columns and indexes in tables, or stored routine definitions. Database Information In the world of web based applications. getting information about databases is important to be able to create generic and scalable applications. This section will demonstrate how to obtain information concerning the databases, the tables and the columns located in the MySQL server. Due to the fact that the root user is being used to log into the MySQL server, the resulting queries against the INFORMATION_SCHEMA database will result in a display of all information contained on the server. However, the majority of users

Displaying Query Results

The majority of query commands that are sent to MySQL are of the SELECT nature in which a set of data will be returned from the query. Understanding how to deal with the query results from SELECT statements is probably one of the most important tasks associated with PHP and MySQL interactions. There are four main ways to accomplish this: • mysql_result($query_result, $row_id, $column_name) – Using the mysql_result() function will return a single row, single column of data from the query output. The $row_id is an offset numeric identifier (0 being the first row, 1 being the second row and so on). The $column_name is the actual column identifier that is returned by MySQL. In the event that the query used an alias to identify the column, the alias name must be used to identify the column. In a majority of cases, a single row of data is not that useful; however, using a looping construct with the mysql_result() function can prove quite useful: $query = "SELECT * FROM w

Combining mysql_select_db() and mysql_query()

The PHP MySQL API includes a function that is able to group the selection of a database and a query against that database. This function is called mysql_db_query() and can be used in place of mysql_select_db() and mysql_query(). The syntax for the proper way to use this command is: $query_result = mysql_db_query($db_name, $query, $link_id); ... or without the $link_id variable ... $query_result = mysql_db_query($db_name, $query);

Retrieving Data,Selecting a Database,Querying MySQL

Retrieving Data The process of retrieving data once a connection has been made to the MySQL server is similar to the process of interacting with the data through the mysql client. The first thing that needs to be addressed is the database that holds the table (which in turn holds the data). Selecting a Database In the mysql client, a database is identified (or selected) by the USE <database> command. In PHP, this is accomplished with a PHP MySQL API function called mysql_select_db(). This function identifies the database that should be used for any subsequent requests to the data, which eliminates the need to qualify every table (or other MySQL resource) called with the database name. There are two ways to use this function: • mysql_select_db($db_name, $link_id) – Using the mysql_select_db function in this fashion ensures that the resource that initiated the connection to the MySQL server would be selected with the $link_id. The variable, that is identified here

Independent Connection Information

For many programmers, the idea of storing connection information (such as username and password) directly in the script itself is a little unnerving and rightfully so. Even though, with the correct privileges assigned to the actual file housing the php script, there would be little concern for the scripts themselves from being seen. As a best practice, it is wise to create a separate PHP script file that would contain variables that would contain the connection information and could be used in the PHP script that is actually connecting to the MySQL server. A typical file containing this connection information would look something like the example below: <?php // MySQL Server Connection Information $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'training'; ?> In this example, the file would be saved as "connect_info.php" and stored in the same folder as our php script (most likely the htdocs folder of the apache server). Using t

Putting it all together

The following example demonstrates an example of PHP connecting to the MySQL server, completing a query against the data contained in the MySQL server and then closing out the connection to the MySQL server (the other details of this script will be discussed throughout the remainder of this chapter): <?php /* Connect to MySQL server */ $linkID1 = mysql_connect('localhost','root','training') or die("Could not connect to MySQL server"); /* Query the MySQL Server for Information */ $query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'world'"; $result = mysql_query($query, $linkID1); while ($row = mysql_fetch_array($result)) { print $row[0]."<br>"; } /* Close the connection to the MySQL server */ mysql_close($linkID1); ?> Even though it is not necessary to provide the link identifier in the mysql_close() function seeing there is only one open connect; however, it is be