Bebo Report121

download Bebo Report121

of 43

Transcript of Bebo Report121

  • 7/30/2019 Bebo Report121

    1/43

    1

    CHAPTER.1

    LAMP

    1.1 LAMP Architecture

    The strength of the world wide web and the internet are that they stand upon open standards

    such as TCPIP,SMTP, UDP, HTTP and the like. This allows a Mac to talk to another systems

    mainframe and to sendemail to a windows computer. This open-ness may or may not extend

    to the tools used to deliver or createcontent on the world wide web. Proprietary tools such as

    Macromedia/Adobe FLASH, ADOBE, ColdFusion, Microsoft IIS are tools developed by

    companies to generate revenue.

    The Open source tools are Linux, Apache, MySQL and PHP. In many ways they can be used

    as areplacement or alternative to IDE's such as J2EE, ASP.NET.

    Linux -This is the operating system (O/S) of the LAMP architecture and serves asfoundation for therest of the applications used in the architecture. Linux, which refers to

    the Linux kernel that is aUnix-like operating system kernel, can be seen in many different

    "flavors" of operating system distributions that utilize the linux kernel to include Fedora,

    Ubuntu, Knoppix, OpenSUSE, etc. The majority of the distributions (along with the

    Linux kernel itself) is released under the GNU General Public License (GPL) and

    developed by contributors worldwide.

    .Apache-The apache folder contains the detail of apache server.It contains information like

    configuration of apache, port no. given to apache, proxies, logs and errors appeared in

    connection.Other important folders like php, FilezillaFTP, perl are used in their specific

    purpose. Xampp also supports FTP, SMTP server to communicate in file transfer and mail

    servers respectively. .

    MySQL -MySQL refers to the multithreaded, multi-user SQL database managementsystem which has more than 10 million installations worldwide. Supported by MySQL

    AB, a company which is dual headquartered in Uppsala, Sweden and Cupertino,

    California, USA maintains the mysql DBMS system and holds the copyright to most of

    the codebase.

  • 7/30/2019 Bebo Report121

    2/43

    2

    PHP -PHP refers to the programming language that is used in the design of a largenumber ofdynamic web pages. PHP is a reflective programming language, meaning the

    program code can be modified in the process of being executed based on its runtime

    behavior. This is ideal for thedynamic and interactive nature of the web. The rights to the

    PHP falls under a group called the "The PHP Group" and the ability to use the software is

    based on the PHP License, which according the free software is the licence that identifies

    itself as being free software.

    1.2Apache Server

    Being one of the components of the LAMP architecture, it is important to ensure that theApache Server is installed and running on the Linux distribution being used. The easiest andleast intrusive way of checking this is by opening a web browser on the local system andattempting to view thelocalhost web location.

    Downloading the Software:-The Apache Software Foundation is responsible formaintaining and supporting the Apache HTTP Server. Its website is http://www.apache.orgwhich provides the details associated with the product lines that it offers and furtherinformation to install, configure and run the Apache HTTP Server on a wide range ofoperating systems.

    Installing the Software:-Once the files are downloaded to the operating system, it is time toextract the download file to an appropriate location for the server to execute from. In thelinux environment, the choice used for the classrooms will be the /user/local directory.

    Configuring the Install Script:The next step is to configure the Apache HTTPd source treefor the Linux operating system and any additional specific requirements needed. Theconfiguration of the install script is accomplished using the script configure included in theroot directory of the distribution.

    Build the Package:-The next step is to build the various parts which form the Apache

    HTTPd package by simply running the make command. Due to the fact that the makecommand will build a base configuration it will take several minutes to compile.

    Configuring:-The Apache server is configured by placing directives (which pass optionalsettings into the Apache server) in plain text configuration files. By default, the mainconfiguration file that the Apache server will look for is called httpd.conf. This file is locatedin the apache2/conf directory by default.

    Starting and Testing the Server:-To start the Apache server, choose the apache2/bindirectory. This directory contains the files associated with executing the components of theApache server.

  • 7/30/2019 Bebo Report121

    3/43

    3

    To test if the Apache server is working on the system, open a web browser on the localsystem and attempt to open http://localhost.

    1.3 MySQL Server

    Being another of the components of the LAMP architecture, it is important to ensure that theMySQL Server is installed and running on the Linux distribution being used.

    Downloading the Software:-MySQL AB is responsible for maintaining and supporting theMySQL Relation Database Server. Its website is http://www.mysql.com which provides thedetails associated with the product lines that it offers and further information to install,configure and run the MySQL Server on a wide range of operating systems.

    Installing the Software:-There are multiple methods for installing the MySQL Server on theoperating system being used. For Linux, the easiest and least cumbersome is using a non-

    RPM distribution. These files can be located under the "Linux (non RPM packages)downloads" section.

    Setting the MySQL user:-The MySQL server should not be run as root but instead shouldbe run as another user whose sole purposeis to execute the MySQL server. This can beaccomplished by creating a user called mysql that isassigned to a group called mysql. Oncethe user is created, all the data directory (/usr/local/mysql/data) should be assigned to thisuser and group.

    Initializing the MySQL databases:-There are a few databases that must be initialized priorto running MySQL for the first time. These databases include the mysql database which is

    used to control the security of all the databases on the server and test database which can beused for testing the server. There is a built in script to accomplish this step(/usr/local/mysql/scripts/mysql_install_db). Starting and Testing the Server:- MySQL provides multiple ways to start the server, butthe safest and most user friendly is using the mysqld_safescript located in the/usr/local/mysql/bin directory. This script should be run as the mysqluser by executing thefollowing conditions: /usr/local/mysql/bin/mysql_script -u mysql&After starting the MySQLserver, the MySQL client (/usr/local/mysql/bin/mysql) can be run tointerface with the server itself.

    1.4 PHPWith PHP being the final component of the LAMP architecture to be setup, it is important toensure that PHP is installed and running on the Linux distribution being used. The majority ofthis course will be based on PHP and setting up the service correctly at this point willminimize problems in the long run. Similar to the process of installing the Apache server,PHP should be compiled for the server that it will be running on.

    Downloading the Software:-The sole implementation of PHP is produced by "The PHPGroup" and released under the PHP License. There are many locations in which the sourcecode for PHP can be obtained; however, php.net provides the most current and up to dateversion.

  • 7/30/2019 Bebo Report121

    4/43

    4

    Installing the Software:-Once the files are downloaded to the operating system, it is time toextract the download file to anappropriate location for the server to execute from. In the linuxenvironment, the choice used for theclassrooms will be the /usr/local directory. This will bethe location for all the software that will be installed in this class.

    Configuring the Install Script:-The next step is to configure the PHP source tree for theLinux operating system and any additional specific requirements needed. The configurationof the install script is accomplished using the script configure included in the root directory ofthe distribution. There are multiple installation options that can be manipulated during theconfiguration.

    Build the Package:-The next step is to build the various parts which form the PHP packageby simply running the make command. Due to the fact that the make command will build abase configuration it will take several minutes to compile.

    Configuring PHP:-PHP is configured through an initialization file (php.ini) which cancontain multiple options to support the PHP implementation for your server. The mostcommon options to be addressed in this file is the location of the document root for theApache server and components to add additional layers of security to the implementation.

    1.5 Putting It All TogetherRestarting Apache:-Apache was shutdown during the installation of MySQL and PHP andshould be started back up to provide the web services necessary to test the PHP installation.To start the Apache server again, choose the apache2/bin directory.

    Testing PHP:-This is accomplished by creating a test PHP file in the/usr/local/apache2/htdocs directory. This file (which is usually called test.php) will contain aPHP command () that will display all the configuration informationassociated with the local PHP installation.

    Automatic Starts of Apache and MySQL:-Up to this point, Apache and MySQL weremanually being started and would need to continue to be manually started every time theoperating system was restarted. This is not the most effective approach for many reasons,least of them being they are easy to forget at start up time when needing to be startedmanually.

  • 7/30/2019 Bebo Report121

    5/43

    5

    CHAPTER 2

    PHP FOUNDATIONS

    2.1Delimiting PHP codePHP was originally designed to be used in conjunction with a web server, and in the case ofthe LAMP architecture, the Apache Web Server. PHP applications are designed embeddingPHP scripts within a web page along with its HTML. Unlike standard HTML pages whichare sent directly from the web server to the end user, PHP files are first interpreted by thePHP application which then converts the PHP script into another form for display. This

    process eliminates the end user from being able to see the original PHP script that wasembedded in the HTML and provides true interaction in HTML files.

    PHP Tags

    PHP scripts are distinguished from the HTML scripts by using delimiting characters that tellthe server to execute the PHP application to interpret that which is contained in the code.There are four ways to accomplish this:

    Default Syntax-The default syntax is starting the PHP script with example with in html:]PHP Default Syntax

    PHP Default Syntax

    Script Syntax - Due to limitations with certain HTML editors, PHP added the ability tosupport a mainstream look like this:

    print "This is an example of using PHP script delimiting syntax";

    Short Tags -Due to the fact that many programmers are interested in minimizing theamount of code.Instead of needing to type

  • 7/30/2019 Bebo Report121

    6/43

    6

    ?> ASP-Style - There are many PHP programmers that have experience with other similar

    programming languages, such as ASP. ASP delimits code using . PHP hasprovided support for this type of delimiting.

    Syntax:

    2.2 Comments

    When it comes to commenting code, the consensus is it is necessary but the reality isit rarely is done.

    It has been said that commenting code is like cleaning the bathroom - no one everwants to do it but a clean bathroom creates a more pleasant experience for all that willneed to use it.

    There are many types of commenting strategies with each having advantages anddisadvantages over each other. The key is to comment, how that is accomplished is

    best worked within a team environment and calls for a great deal offlexibility.

    Code Commenting

    This form of commenting is not traditional commenting (in the sense of creating remarks tosupport the code) but is closer related to good programming design principles.

    Example:

    $MarriageDate = "July 14, 1970";functiondeleteOrder (orderID, actionDate);These examples show that the variable or function name give a description of what is being

    performed.

    InLine Commenting

    The most basic form of commenting is that which is referred to as inline or single linecommenting. PHP supports this type of commenting by using two consecutive forward

    slashes (//) preceding any comments added.$MarriageDate = "July 14, 1970"; // Official Marriage Date// This function will provide the code required to delete an orderfunctiondeleteOrder (orderID, actionDate);.

    Muliple-Line Commenting

    It is possible to use inline commenting to create a more verbose and descriptive comment;however, there is an alternative when a comment requires the use of multiple lines. By

    preceding comments with a forward slash followed by an asterisk (/*) and then closing out

  • 7/30/2019 Bebo Report121

    7/43

    7

    the comments with an asterisk followed by a forward slash (*/) multiple lines of commentscan be added to the code.Example:

    /* Script General Information

    File Name: default.phpCreator: Joe Smith, +1(313) 443-4433, [email protected]: The default script for all scripts created by Joe Smith*/

    HTML Comment Tag

    The commenting types up to this point addressed the commenting capabilities in PHP code;however, due to the fact that PHP code is embedded in HTML .In HTML, commenting isavailable by creating a comment tag which consists of a less than character followed by anexclamation point and two dashes ().Example:

    2.3 Construct Feedback

    The strength of the web has been the ability for practically anyone to provide information(accurate or not). With HTML, the static nature of the information being displayed limits theamount of true customization that can be provided.To accomplish this display of information, PHP has four functions:

    print()- This statement isdesigned to provide user feedback; in other words, this function"prints" content to the HTML code which in turn will be displayed on the web page whencalled. The print() function can display both raw strings and variables.

    echo- The echo function is similar to the print function in that it can "print" content to theHTML Code.With that thought in mind, many programmers choose to just use the printfunction to prevent this limitation as they advance in their programming skills.

  • 7/30/2019 Bebo Report121

    8/43

    8

    printf() - The printf function performs the same function as the print command with theexception that there is greater control over the formatting of the "printed" text. The printffunction is the standard printing approach.

    sprintf() - The sprintf function performs the same functions as the printf function except itstores the result of the function into a variable.2.4 PHP Data Types

    A data type identifies the characteristics that the assigned data will be interpreted by wheninteracting with the PHP programming language. When a value is assigned a specific datatype, the PHP interpreter will Work with the data based on the expected type of data it is.Assigning the correct data type to the expected value is an important part of working withPHP.

    There are three categories of data types in PHP:1. Scalar2. Compound3. Special.

    2.4.1Scalar Data Types

    A scalar data type is identified as being able to hold one value at a time. In PHP, there arefour data types that fall into this category. Boolean - A boolean value is a truth value, either 'true' or 'false', often coded 1 and 0,respectively.

    Integer - An integer is a whole numeric data type (meaning it does not contain anyfractions) .Example:

  • 7/30/2019 Bebo Report121

    9/43

    9

    $z = 0x5E5B; // $z is an integer number (hexadecimal)?>The maximum number that can be assigned to an integer is based on the system.

    Float - Floating point numbers are any number that has a fractional component or exceedtheinteger maximum values. This data type is also referred to as floats, doubles or realnumbers.Floats are used to represent such numbers as monetary values, distances, weights,scientificnotations and a host of other values:

    String - A string data type is a series of characters that are associated with each other in a

    definedorder. There is no limit to the length of a string data value.Example:

    2.4.2 Compound Data TypesA compound data type allows for multiple values to be associated with a single entity. The

    primary purpose of a compound data type is to act as containers for other kinds of data.

    In PHP, there are two types of datatypes that fall under into this category.

    Arrays - These are a series of like values that are assigned to an individual variable witheach individual value in the array being referenced with a unique identifier.

  • 7/30/2019 Bebo Report121

    10/43

    10

    }}$boss = new respect;$boss->setRespect("Jane Riker");?>In this simple object example, the result of all this coding is a proper title being placed infront ofthe boss' name.]

    2.5.3 Special Data TypesIn almost every programming language, there are data types that serve a distinct purpose butdo not associate with any other data type. Inphp this datatypeis a data type heading calledspecial.The two data types that fall under this heading are:

    Resource - One of the benefits of using PHP is its ability to interact with some external datasource: databases, files, network streams, etc. To utilize these external data sources.In the example above, the $dbLink variable is assigned a resource data type based on theactionthat is taking place (connecting to the local MySQL database server). Null - The term Null is a perplexing concept that is surrounded by a lot of confusion. Nulldoesnot mean a blank space or zero; it truly means nothing or no value. In PHP, a variable isidentified as a Null data type when:

    The variable has not been set to any predefined value; thus it has no value. The variable has been assigned the explicit value of Null.

    The variable has been erased using the function unset().

  • 7/30/2019 Bebo Report121

    11/43

    11

    2.5Flow Control StatementsFlow control statements, or instructions, when executed redirect the normal sequence of theoriginal program execution, or the execution logic.Within PHP, two categories of flow control statements can be identified:

    Conditionalthese statements alter the normal sequence of the original program executionbased on the value of an expression. These expressions can be any expression that is usablewithin MySQL stored routines and return a value.Ex:if and switch statements.

    Iterative - these statements provide for the repeated processing of commands based on acondition that must be met. The most common reason to use iterative statements orinstructions within a LAMParchitecture is to process all the returned rows of a MySQLSELECT statement.

    Executing more complex mathematical algorithm. Processing an external file by looping through each record in that file

    In PHP these are represented in the while, do...while, for and foreach statements.

    2.5.1 if ... else ... elseif

    In most programming languages, including PHP, the ifstatement is the most basic of allchoice flow controls or conditional constructs.Syntax:

    if (test_condition1){... -- statements that execute if test_condition1 is True} else if (test_condition2) {... -- statements that execute if test_condition2 is True} else {... -- statements that execute if all precedingtest_conditions are False or Unknown}test_conditioncan result in three different returned values:

    True - the statements enclosed within an if condition (or else if) will be executed whentheexpression results in a true condition.

    False - when an expression results in a false condition, the statement enclosed isbypassed. Afalse condition in a numeric value expression (or a value that PHP perceivesas numeric) when the returned result is zero (0).

    Unknown - when an expression can not be evaluated to either a true or false condition,SQLreturns an unknown (or null) condition. Most errors in stored routines stem from notdevelopingguards to manage null conditions.

  • 7/30/2019 Bebo Report121

    12/43

    12

    2.5.2 Switch

    The switch statement provides a means of developing complex conditional constructs. Theswitch choice works on the principle of comparing a given value with specified constants andacting upon the firstconstant that is matched.switch(variable){case option1:-- statements that execute if option1 is equal to variable

    break;case option2:-- statements that execute if option2 is equal to variable

    break;default:-- statements that execute if none of the case optionsmatched the variable}

    2.5.3WhileThe while function is the simplest of all the iterative control statements. The statement listwithin a while statement is repeated as long as the condition evaluated has not been met.

    while (expression){-- statements that execute while the expression evaluatesfalse}

    2.5.4 Do ... WhileThe do ... while function is based on the while iterative control statement .The statement listwithin a do ... while function is repeated as long as the condition evaluatedhas not been met.This statement excuteatleast once.do {-- statements that execute while the expression evaluates falseand then it iterates through the statements one more time}while (expression);

    2.5.5 ForThe for function is the more complex sibling of the while function and provides a morestreamline and complex looping mechanism. The for function takes three expressions; thefirst expression is evaluated by default at the first iteration of the loop, the second expressionis evaluated at the beginning of each iteration (and determines if the loop will continue) andthe third expression is evaluated at the conclusion of each loop.for (expression1; expression2; expression3) {-- statements that execute while the expressions evaluates false}

    The following examples demonstrate how the foriterative control statement can work:

  • 7/30/2019 Bebo Report121

    13/43

    13

    2.5.6 Foreach

    The foreach function is the iterative control statement that is designed specifically forhandling arrays (and objects as of PHP 5). There are two ways of using the

    foreachiterative control statement. The first ways is by looping over the array given by the

    array_expressionand assigning the current array element to the $value variableforeach (array_expression as $value){-- statements that execute until the array reaches the end or amanual break is inserted}The second way of using the foreach function is similar to the first, except the element valueis assigned to a $key variable.

    foreach (array_expression as $key => $value) {-- statements that execute until the array reaches the end or amanual break is inserted}

    2.5.6.1Break and Continue

    With iterative control statements, PHP provides two means of manually interrupting the flowof the loops.These two commands include break and continue.

  • 7/30/2019 Bebo Report121

    14/43

    14

    The following output would be displayed when this PHP script was run:

    The test number is 1The test number is 2The test number is 4

    The test number is 5

    2.6 User Defined Functions

    PHP is packed full with many useful built-in functions, such as print() and

    mysql_query(),which meet a variety of needs.The programmercan of course write the samepiece of code over and over again in their applications to produce the result orthey can createa user defined function that can be reused over and over again. Next comes the parentheses,which may contain variable names, and the actual function code itself, enclosed in curly

    braces:functionfunction_name(){-- Statements that make up the function code}The following examples demonstrate some of the uses and capabilities for creating a userdefined function:

  • 7/30/2019 Bebo Report121

    15/43

    15

    CHAPTER 3

    MYSQL FOUNDATIONS

    3.1 MySQL General ArchitectureMySQL operates in a networked environment usinga client/server architecture. In otherwords, a central program acts as a server, and various client programs connect to the server tomake requests.A MySQL installation has the following major components:

    MySQL ServerClient programs

    MySQL nonclientutilities.

    3.1.1 MySQL Server

    MySQL Server, ormysqld, is the database server program. The server manages access to theactual database (schema) on disk and in memory. Clients can connect via several connection

    protocols. For managing database contents, the MySQL server features a modulararchitecture that supports multiple storage engines that handle different types of tables (forexample, it supports both transactional and non-transactional tables).

    3.1.2 Client Programs

    These are programs that are used for communicating with the server to manipulate thedatabases that are managed by the server. MySQL AB provides several client programs.

    MySQL Query Browser and MySQL Administrator are graphical interfaces to the server.mysqlis a command-line program that acts as a text-based front end for the server. It's

    usedfor issuing queries and viewing the results interactively from a terminal window.

    Other command-line clients include mysqlimportfor importing data files,mysqldumpfor making backups, mysqladminfor server administration, andmysqlcheckfor checking theintegrity of the database files.

    MySQL Client/Server Model

  • 7/30/2019 Bebo Report121

    16/43

    16

    FIGURE 3.1

    MySQL runs on many varieties of Windows, Unix, and Linux, but client/servercommunication is not limited to environments where all computers run the same operatingsystem. Client programs can connect to a server running on the same host or a different host,and the client and server host need not have the same operating system. For example, client

    programs can be used on Windows to

    connect to a server that is running on Linux.Most of the concepts discussed here apply universally to any system on which MySQL runs.Platform specific information is so indicated. Unless otherwise specified, Unix as used hereincludes Linux and other Unix-like operating systems.

    3.2 SQL Parser and Storage Engine Tiers

    A client retrieves data from tables or changes data in tables by sending requests to the serverin the form of SQL statements. The server executes each statement using a two-tier

    processing model:

    The upper tier includes the SQL parser and optimizer.

    The lower tier comprises a set of storage engines.

  • 7/30/2019 Bebo Report121

    17/43

    17

    For the most part, the SQL tier is free of dependencies on which the storage engine managesany given table. This means that clients normally need not be concerned about which enginesare involved in processing SQL statements, and can access and manipulate tables usingstatements that are the same no matter which engine manages them. Exceptions to thisengine-independence of SQL statements include the following:

    CREATE TABLE has an ENGINE option that enables you to specify which storage

    engine to use on a per-table basis. ALTER TABLE has an ENGINE option that enables youto convert a table to use a different storage engine. Some index types are available only for particular storage engines. For example, only the

    MyISAMengine supports full-text or spatial indexes.

    3.2.1 Storage Engine BreakdownThe following properties are storage engine dependant: Storage MediumEach table uses its own method of storing the data it contains. Transactional Capabilities Certain storage engines handle transactional processing

    which ensures that integrity of a database is maintained during the processing of multipleSQL statements. Locking Each storage engines handles the processes of the synchronization mechanismfor enforcing limits on access to a resource in an environment where there are many threadsof execution. Backup and Recovery Based on the storage medium used, the backup of the table dataand the recovery of that data can be distinct. Optimization There are specific issues associated with each storage engine for theoptimization of the storage of the data and retrieval of the data through the MySQL server. Special FeaturesThere are a number of features that exist only in certain engine types toinclude full-text search, referential integrity and the ability to handle spatial data.

    3.3 ThemysqlClient

    This section discussesmysql, a general-purpose client program for issuing queries andretrieving their results.

    3.3.1 Using mysqlInteractively

    Themysqlclient program enables the sending of queries to the MySQL server with anyresults being displayed in the same interface. Interactive mode is useful for day-to-day usage, for quick one-time queries, and for testing

    how queries work. MySQL statements such as the version query, shown below as executed within the

    mysqlclient, can also be run from the shell command prompt as part of the mysql clientstartup;

    mysql>SELECT VERSION();+-----------------+| VERSION() |+-----------------+| 5.0.41-log |------------------+

  • 7/30/2019 Bebo Report121

    18/43

    18

    3.3.2 Statement Terminators

    There are numerous terminators that can be used in the mysql client to end a statement. Two

    terminators are the semicolon character (';') and the \g sequence. They're equivalent and

    may be used interchangeably:mysql>SELECT VERSION(), DATABASE();+-----------------+--------------------+| VERSION() | DATABASE() |+-----------------+--------------------+| 5.0.40-log | INFORMATION_SCHEMA |

    The \G sequence also terminates queries, but causesmysqlto display query results in avertical style that shows each output row with each column value on a separate line:

    mysql>SELECT VERSION(), DATABASE()\G

    ************************** 1. row **************************VERSION(): 5.0.40-logDATABASE(): INFORMATION_SCHEMAThe \G terminator is especially useful if a query produces very wide output lines becausevertical format can make the result much easier to read.

    Themysqlclient allows a single query to be entered using multiple input lines. This makesit easier to issue a long query because you can enter it over the course of several lines.

    mysqlwill wait until it sees the statement terminator before sending the query to the serverto be executed. For example:

    mysql>SELECT TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE

    ->FROM INFORMATION_SCHEMA.TABLES->WHERE TABLE_NAME LIKE 'E%';+--------------------+------------+-------------+| TABLE_SCHEMA | TABLE_NAME | TABLE_TYPE |+--------------------+------------+-------------+| information_schema | ENGINES | SYSTEM VIEW || information_schema | EVENTS | SYSTEM VIEW || mysql| event | BASE TABLE |+--------------------+------------+-------------+3 rows in set (#.## sec)In the preceding example,mysqlchanges the prompt frommysql>to ->to provide

    feedback that it's still waiting to see the end of the statement.If a statement results in an error,mysqldisplays the following error message:

    mysql>This is an invalid statement;ERROR 1064 (42000): You have an error in your SQL syntax.If it is necessary to cancel a statement once mysql has already received some of the input,

    enter\c andmysqlwill cancel the statement and return themysql>prompt:mysql>SELECT * FROM INFORMATION_SCHEMA>WHERE \cmysql>

    To quitmysql, use \q, QUIT, orEXIT: mysql>\

  • 7/30/2019 Bebo Report121

    19/43

    19

    3.4 MySQL Query Browser

    MySQL Query Browser is a cross-platform GUI client program that's intuitive and easy touse. It provides a graphical interface to the MySQL server for querying and analyzing data.

    3.4.1 Using the Connection Dialog

    MySQL Query Browser presents a Connection dialog when it starts or when the NewInstance Connection is selected from the File menu. Connecting to a MySQL server can

    be accomplished either by filling in the connection dialog box fields with the parametersrequired to connect to a server or selecting from among any predefined connection profiles

    Connection Dialog Window:

    To connect to a MySQL server by specifying connection parameters directly, fill in theappropriate fields beginning with the Username field and click the OK button. To connectusing the parameters stored in a connection profile, select the profile from the Connection

    drop-down list and click the OK button

    3.4.2 The MySQL Query Browser Window

    The main MySQL Query Browser window is divided up into several sections:

  • 7/30/2019 Bebo Report121

    20/43

    20

    FIGURE 3.2

    Query Toolbar The query toolbaris where queriescan be created andexecuted. Itiscomposed of threenavigation buttons (Go Back, Next,Refresh), the queryarea, two

    actionbuttons (Executeand Stop), and astatus indicator.

    AdvancedToolbarTheadvanced toolbar contains three sets of buttons: the TransactionButtons (Start, Commit, Rollback), thequery management buttons (Explain, Compare),and the query building buttons (Select, From, Where,and so on.).

    Results Area - All query results are displayed in the result area. Multiple tabs can beactive at onetime, allowing multiple queries to be worked on. The result area can be splitvertically andhorizontally for performing comparisons, and queries in different parts of asplit result area can bejoined together for master-detail analysis.

    Object Browser - The object browser is part of the sidebar and allows for themanagement of thedatabases, bookmarks, and history. Databases and tables can be chosen

    to query, in addition to theability to add commonly-used queries to a collection ofbookmarks, and browse through previouslyissued queries in order to use them again.

    Information Browser - The Information Browser is part of the sidebar and is used tolook up built-infunctions, and to manage queries that contain parameters. One example ofthis is when establishing amaster-detail pair of queries.

  • 7/30/2019 Bebo Report121

    21/43

    21

    CHAPTER 4

    MANAGING DATABASES

    4.1 Database Properties:

    The heart of any database is the tables, because the tables contain the data that is used toprovide information to the end users. Tables are contained in databases, and in MySQL eachdatabase has an associated "data directory" to store all the physical components of thedatabase, to include tables. This physical representation on disk of the tables is dependent onthe type of storage engine that the table is utilizing.In addition to the physical representationof the table, there is also the better known logical aspect of the table. This logical aspect isrepresented in rows and columns. Without the ability to obtain information from the database,there is no need for the data to be stored. This is where the database comes in. For its part, thedatabase can be thought of as the container for the tables (which are the containers for thedata). In MySQL, databases manage their associated components in locations called "datadirectories".

    Data Directory - In MySQL, there is a parent directory for all the databases that aremanaged by that instance of the MySQL Server.

    Database Name - The database name given to the represent the database in the MySQLserver is also the name of the associated data sub-directory.

    Database Components - The data directory is responsible for managing the majority ofcomponent associated with the associated database in the MySQL server.

    Database Character Set Support - Each database is defined with a default character setand collation (a character set is a set of symbols and encodings and a collation is a set of rulesfor comparing characters in a character set).

    Database Hierarchy - Databases are "flat" in the sense that they can not be nested,meaning a database can not contain a database itself.

    Unlimited Databases - The MySQL server has no limit on the number of databases that itcan contain; however, the operating system may limit the number of sub-directories that adirectory can contain thus limiting the number of databases that can be created.

    4.2 Creating DatabasesTo create a new database, use the CREATE DATABASE statement. The following statementcreates adatabase named my_db:CREATE DATABASE my_db;If an attempt is made to create a database that already exists, an error occurs. To ensure that

    the database exists, add an IF NOT EXISTS clause to the statement:

  • 7/30/2019 Bebo Report121

    22/43

    22

    CREATE DATABASE IF NOT EXISTS my_db;With the additional clause, the statement creates the database only if it does not already exist.Otherwise, the statement does nothing and no error occurs.

    Displaying Database Structure

    The easiest way to display the database structure (as far asthe database container) is to issue a SHOW CREATE DATABASEcommand. This command shows the CREATE DATABASE statement that was used tocreate the database (or could be used to recreate the database structure):

    mysql> SHOW CREATE DATABASE my_db\G************************* 1. row *************************Database: my_dbCreate Database: CREATE DATABASE `my_db`

    4.3 Drop a Database

    When a database is no longer needed, it can be removed with DROP DATABASE:DROP DATABASE my_db;It is an error if the database does not exist. To cause a warning instead, include an IFEXISTS clause;DROP DATABASE IF EXISTS my_db;Any warning generated when IF EXISTS is used can be displayed with SHOW

    WARNINGS.

  • 7/30/2019 Bebo Report121

    23/43

    23

    CHAPTER 5

    SQL DML COMMANDS

    5.1 The INSERT Statement

    Now that tables have been created, the next step is to populate them with data. Although there

    are a variety of ways to get data into MySQL tables, the INSERT statement is the mostcommon method for getting data into a table. The INSERT statement uses the followinggeneral syntax;INSERT INTO table_name (column_list)VALUES(value_list);An insert can include a only the value(s) without a column list (if the exact column order,quantity and types are known), as follows;INSERT INTO numbers VALUES(250);

    Row contents will be as follows;+------+| n |--------| 250 |+------+

    5.2 The UPDATE Statement

    The UPDATE statement modifies the contents of the existing records. To use it, name thetable needing to be updated, provide a SET clause that lists one or more column valueassignments.The Update statement uses the following general syntax;UPDATE table_name SET column=expression(s) WHERE condition[options];For example, to update the Country table by doubling the Population column for everycountry, the following statement would be used;

    mysql>UPDATE Country->SET Population = Population * 2;Query OK, 232 rows affected, 1 warning (#.## sec)Rows matched: 239 Changed: 232 Warnings: 1

    5.3 The REPLACE Statement

    The MySQL-specific statement REPLACE works exactly like INSERT, except that if an oldrow in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index,the old row is deleted before the new row is inserted. REPLACE is a MySQL extension tothe SQL standard. It either inserts, ordeletes and inserts. Uses the following general syntax;REPLACE INTO table_name (column_list)

    VALUES(value_list);database;REPLACE INTO people (id,name,age)VALUES(12,'Bruce',25);

    5.4 The DELETE Statement:-The DELETE statement allows aWHERE clause thatidentifies which records to remove. use thefollowing syntax:

  • 7/30/2019 Bebo Report121

    24/43

    24

    DELETE FROMtable_name;To a DELETE statement needs to be issued with aWHEREclause that.identifies which records to remove:DELETE FROM table_name WHERE ;

  • 7/30/2019 Bebo Report121

    25/43

    25

    CHAPTER 6

    SQL JOINS

    6.1What is a join?

    The SELECT queries shown thus far in this training guide retrieve information from asingle table at a time. However, not all questions can be answered using just one table. Whenit's necessary to draw on information that is stored in multiple tables, use a join conditionan operation that produces a result by combining (joining) information in one table withinformation in another.The contents of two original tables are shown below. These tables can be joined together

    using a SELECT query which retrieves data from more than one table at a time.

    table1+----+----+| i1 | c1 |+----+----+| 1 | a || 2 | b || 3 | c |+----+----+3 rows in set (#.## sec)table2+----+----+| i2 | c2 |+----+----+| 2 | c || 3 | b |

    | 4 | a |+----+----+3 rows in set (#.## sec)

    mysql>SELECT * FROM table1 JOIN table2;+----+----+----+----+| i1 | c1 | i2 | c2 |+----+----+----+----+| 1 | a | 2 | c || 2 | b | 2 | c || 3 | c | 2 | c || 1 | a | 3 | b || 2 | b | 3 | b || 3 | c | 3 | b || 1 | a | 4 | a || 2 | b | 4 | a || 3 | c | 4 | a |

  • 7/30/2019 Bebo Report121

    26/43

    26

    Types of joins:1. Inner join

    2. Outer join

    6.2 Inner Joins

    A join that identifies combinations of matching rows from two tables is called an inner join.The joining is done by connecting one table, using the primary key, another table thatreferences it with aforeign key. Inner joins may be written using two different syntaxes. The

    other uses the INNER JOIN keywords.

    6.2.1 Comma Separated Inner JoinTo combine data from two or more tables to find the detail of records referenced in a foreignkey , a table join must be performed. The most common way to do this is by specifying a list

    (comma separated) of tables in the FROM clause of the SELECT and using theWHEREclause to indicate the relationship between the tables.Example:mysql>SELECT Name, Capital->FROM Country;+---------------+---------+| Name | Capital |+---------------+---------+| Afghanistan | 1 |...| Sweden | 3048 |...| Germany | 3068 |...| United States | 3813 |...+---------------+---------+239 rows in set (#.## sec)

    mysql>SELECT Id, Name FROM->City;+------+------------+| Id | Name |+------+------------+

    | 1 | Kabul |...| 3048 | Stockholm |...| 3068 | Berlin |...| 3813 | Washington|+------+------------+4079 rows in set (#.## sec)

    mysql>SELECT Country.Name, City.Name, City.Id FROM Country,City

  • 7/30/2019 Bebo Report121

    27/43

    27

    ->WHERE Country.Capital = City.Id;+----------------------+------------------+------+| Name | Name | Id |+----------------------+------------------+------+| Afghanistan | Kabul | 1 |

    ...| Sweden | Stockholm | 3048 |...| Germany | Berlin | 3068 |...| United States | Washington | 3813 |...+----------------------+------------------+------+232 rows in set (#.## sec)

    6.3 OUTER JOINS:

    Whereas an INNER JOIN will find combinations of matching rows from joined tables, theOUTER JOIN also finds the instances where a row in one table has no match in anothertable. An OUTER JOIN find matches (just like an INNER JOIN), but also identifiesmismatches.Two forms of outer joins are LEFT JOIN and RIGHT JOIN. These do not use the commaseparator or the INNER JOIN keywords. They each answer the same kinds of questions,

    but differ slightly in their syntax. That is a LEFT JOIN can always be re-written into aequivalent RIGHT JOIN.

    6.3.1 Left Outer Join

    A left join is a type of outer join, written using the LEFT JOIN keywords. A left join treatsthe left table (the first one named) as a reference table and produces output for each rowselected from it, whether or not the row is matched by rows in the right table. Like a join

    written with the INNER JOIN keywords, a LEFTJOIN is written using either ON orUSING() after the table names in the FROMclause.Example:

    mysql>SELECT Country.Name, CountryLanguage.Language->FROM Country

    ->LEFT JOIN CountryLanguage->ON Country.Code = CountryLanguage.CountryCode;

    +-----------------------------+------------------+| Name | Language |

  • 7/30/2019 Bebo Report121

    28/43

    28

    +-----------------------------+------------------+| Aruba | Dutch || Aruba | English || Aruba | Papiamento || Aruba | Spanish || Afghanistan | Balochi |...| Antarctica | NULL || French Southern territories | NULL || Antigua and Barbuda | Creole English || Antigua and Barbuda | English || Australia | Arabic || Australia | Canton Chinese || Australia | English || Australia | German |

    ...990 rows in set (#.## sec)

    6.3.2 RIGHT OUTER JOIN:

    A right join is another type of outer join, written using the RIGHT JOIN keywords. EveryRIGHT JOIN corresponds to an equivalent LEFT JOIN. The only difference is that theroles of the tables are reversedrelative to the roles in a RIGHT JOIN. That is, the right tableis the reference table, so a RIGHT JOIN produces a result for each row in the right table,whether or not it has any match in the left table.The previous example showed the result of aLEFT JOIN . The example below is the same statement, butwith a RIGHT JOIN:

    mysql>SELECT Name, Language->FROM Country

    ->RIGHT JOIN CountryLanguage

    ->ON Code = CountryCode

    ->WHERE CountryCode IS NULL;Empty set (#.## sec)

  • 7/30/2019 Bebo Report121

    29/43

    29

    CHAPTER 7

    MYSQLDATA DRIVEN WEB BASED FORMS

    7.1Connecting to MySQL

    PHP and MySQL are two different technologies that have found favor in the community ofweb developers based on their combined strength. This of course has given rise to bothtechnologies finding great success in the marketplace that they may not have enjoyedotherwise.

    User PrivilegesMySQL has a very strong authentication system that allows multiple security levels for eachuser that can access the server. MySQL's highly effective security system can cause

    headaches for those trying to break into the data, but likewise can cause headaches for thosethat are authorized to access the data. MySQL sees any requests from PHP in the same waythat it sees requests from any other API (such as the mysqlclient or MySQL Query Browser).

    PHP MySQL APIPHP and MySQL both offer an Application Programming Interface (API), each creating theability to interface between the two technologies. The basics of both API's offer multiple PHPfunctions which are capable of performing a wide array of tasks against the data in theMySQL Server.

    Connecting to MySQL

    The most basic request necessary when working with PHP and MySQL is the ability toconnect to the MySQL server itself. mysql_connect() - This function (which is a PHP resource type) is used to establish aninitialconnection to the MySQL server. Believe it or not, each parameter in the functionmake-up below is optional (a connection can be made to MySQL that would have no rightswhatsoever):

    $link_id = mysql_connect([hostname [:port] [:/path/to/socket][, username] [,password]])In the case of this training, the hostname will be referred to as 'localhost' due to the fact that

    thewebserver is local and use 'root' as our username. As far as the password, the password'training' will be used; however, check with the instructor to ensure that this is the passwordthat should be used.

    Disconnecting from MySQLEven though it is important to understand the process of connecting to the MySQL serveritself, it is also important to terminate the MySQL connection properly to ensure that there isno possibility of a connection remaining open beyond the need (which of course could

    become a security concern).

  • 7/30/2019 Bebo Report121

    30/43

    30

    mysql_close($link_id) - This use of the mysql_close() function, which would includethe $link_idof the connection resource that connected PHP to the mysql server would beclosed. By identifying the $link_id, PHP looks for that connection to the MySQL server toclose.mysql_close($link_id) mysql_close() - This use of the mysql_close() function, which does not include the$link_id, the most recently open link is assumed.mysql_close()

    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 theconnection to the MySQL server (the other details of this script will be discussed throughoutthe remainder of this chapter):

  • 7/30/2019 Bebo Report121

    31/43

    31

    mysql_select_db($db_name, $link_id) or die("Could not selectthe $db_name database!");

    mysql_select_db($db_name)Using the mysql_select_dbfunction in this fashion forcesPHP to use the last connection made to the MySQL server to submit the request. Without a$link_id to choose from, the MySQL server chosen could be the wrong one to use (notcontaining the database identified by $db_name). Best practice is to include the $link_id, butit is not necessary.mysql_select_db($db_name) or die("Could not select the$db_namedatabase!");

    Querying MySQL

    In the mysql client, any interaction is accomplished through a query command. These querycommands include data definition language (DDL) and data manipulation language (DML)commands that pretty much include every command that can be issued into MySQL. Of

    course, MySQL has non-standard SQL commands such as SHOW ... which can also bequeried and can be called from PHP. To query the MySQL server in PHP, the mysql_query()function is used. Similar to the other functions mentioned up to this point, there are two waysto use this function:

    mysql_query($query, $link_id) Using the mysql_queryfunction in this fashionensures that the resource that initiated the connection to the MySQL server would be selectedwith the $link_id. The variable, that is identified here as $query, would be the query thatwould be executed against the MySQL server.$query_results = mysql_query($query, $link_id);

    mysql_query($query) Using the mysql_queryfunction in this fashion forces PHP to

    use the lastconnection made to the MySQL server to submit the request. Without a $link_idto choose from, the MySQL server chosen could be the wrong one to use (not being able toreturn the results of $query because the server does not contain the data). Best practice is toinclude the $link_id, but it is not necessary.$query_results = mysql_query($query);

    Combining mysql_select_db() and mysql_query()

    The PHP MySQL API includes a function that is able to group the selection of a database anda 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);

    Displaying Query ResultsThe majority of query commands that are sent to MySQL are of the SELECT nature in whicha set of data will be returned from the query. Understanding how to deal with the queryresults from SELECT statements is probably one of the most important tasks associated withPHP and MySQL interactions.

  • 7/30/2019 Bebo Report121

    32/43

    32

    There are four main ways to accomplish this:

    mysql_result($query_result, $row_id, $column_name) Using themysql_result() function will return a single row, single column of data from the queryoutput. The $row_id is anoffset numeric identifier (0 being the first row, 1 being the secondrow and so on). The$column_name is the actual column identifier that is returned by

    MySQL. In the event that the queryused an alias to identify the column, the alias name mustbe used to identify the column. In a majorityof cases, a single row of data is not that useful;however, using a looping construct with themysql_result() function can prove quite useful:$query = "SELECT * FROM world.Country LIMIT 5";$query_results = mysql_query($query, $linkID1);for ($count=0; $count

  • 7/30/2019 Bebo Report121

    33/43

    33

    CHAPTER 8

    SESSION HANDLING

    8.1 Session Handling

    Hyper Text Transfer Protocol (HTTP) is the method on which information is transferred froma server to a client on the world wide web. This protocol is static in nature, that is everyrequest is a new request and no persistence (or memory of a previous transfer) remains withinthe protocol itself.

    Maintaining State

    Telling PHP to Remember a Visitor

    The Process of Remembering a Visitor

    8.2 Session Handling TasksAs stated earlier, the process of PHP maintaining information from one session to the next fora visitor is pretty straight forward without lacking in capability. This maintaining ofinformation (getting to know the end user) is accomplished through session handling tasks.

    Starting a Session: This process is accomplished through the function session_start(). Thisfunction initializes the session data or continues the current session that is being passed by arequest, such as a GET, POST or a cookie.Setting up the Session "Key": This key is stored on the end users machine and is calledwhen interacting with the end user machine with the same function; session_id().

    Replacing the Session "Key"In the example above, the old session ID is removed and a new session ID is made using therand function. This works fine; however, there is a simpler approach to the idea of replacing(or regenerating) a new session ID.

  • 7/30/2019 Bebo Report121

    34/43

    34

    ?>

    Remembering the SessionWhen working with sessions, it is important to understand that keeping track of the session isutmost for this recall to take place. If a session ID is lost, then the information that isassociated with it is useless because the key is lost. Without the key, the session informationis wasted space:

    Retrieving the Session Data

    The following demonstrates how this is accomplished:

    Terminating a Session

    The function session_destroy is responsible for handling the described actions; however, thisfunction is limited in its ability by not unsetting (or clearing) the global variables tied to thesession or the respective cookies. This requires a more detailed approach:It can be by two functions:session_unset()

    session_destroy()

    8.3 PHP Session Handling with MySQLThere are many ways that session handling can be used to provide a dynamic and non-staticexperience for the end user. Sessions can be used for providing a more personal experiencefor the end users by keeping track of them as they roam through a site providing content thatis more tailored to their likes and dislikes (by monitoring the choices they make in what theychoose to view).

  • 7/30/2019 Bebo Report121

    35/43

    35

    CHAPTER 9

    OBJECT ORIENTED PROGRAMMING

    9.1 Benefits of OOP

    Object-oriented programming (OOP) is a programming model that uses "objects" in thedesign of the applications. Standard programming is seen as a list of instructions read morefrom top to bottom, while OO programming is better identified as a collection of "objects"working together to create the application. OO programming is modular in nature which isdesigned to support greater flexibility while also being easier to maintain. Objects, whendesigned properly, become "black boxes", where the only concern is inputting data andreceiving output data. The innards, although important to the programmer when developingthe object, become less important as the object is put into production and reused.

    BenefitsMany of the benefits of OO programming have already been presented in the introduction,

    but for the purposes in being straight-forward, the following list is more complete:

    Encapsulation - The object is an enclosed and complete program that for the most part canstand on its own. All the code required to take an input and provide an appropriate output

    based on the design of the object is located in one complete package.

    Reuse - Once an object is created, it is easy to drop that object into another piece of code(or share with others) that requires a similar procedure. (ex. Login object, databaseconnection, etc.)

    Quality - When using code that has already been used in another application, the chances of

    the bugs being worked out is high. This produces code that had a greater quality and lesslikelihood of being latent with bugs. Maintainability - Using objects creates a central location to change code if need be. If thecode is in one place, being called by other programs, it is easier to change that one piece ofcode ratherthan having to locate and change numerous pieces of code.

    9.2 Working with ObjectsTwo terms that are often heard when discussing OOP are class and object. A class isessentially a description of an object (the code itself), while an object is an instance of that

    class. One method to thinkabout it is that an object has a particular class for example,$myDog is an object of class Dog. Generally,a class represents a particular type of object,either a physical object (such as a Dog) or a conceptual one (such as a Poll). The methods in aclass represent either things that an object can do itself, or that another object can cause theclass to do.

    Public, Private, Protected, StaticMethods and properties can be declared in one of three ways: public, private, or protected.

    Public - Public methods and properties can be accessed by any code, inside or outside oftheobject, for example by other objects.

  • 7/30/2019 Bebo Report121

    36/43

    36

    Private - Private methods and properties can only be accessed internally, by other codeinside of the class.

    Protected - Protected methods and properties can be accessed internally, as well as byparent or inherited classes.

    Static - Methods can also be declared static, which means that it is not required to create an

    object in order to call that method. Some static methods may be purely informational, whileothers perform a 'one-off' function such as deletion of a record, as it may not make sense to

    populate an object with data just to delete it from the database. Static methods may alsoreturn an instance of a class, which can be an easier way to fetch an object under a certaincondition (for example, if a given ID is not available).

    Working with classesIn order to use a class, it must be instantiated. Instantiation is the act of allocating a newinstance of the class. Put simply, to use a class, an object must be created. This is done usingthe 'new' operator. For example, this statement would create an object $myCanine of class

    Dog: $myCanine= new Dog();Code Example

  • 7/30/2019 Bebo Report121

    37/43

    37

    able to pet (or try to pet) the dog. Perhaps if the dog is not feeling sociable, it may try to getaway, calling the 'Run()' method to escape.

    Instantiate a ClassAfter the class is defined, an object of class Dog is instantiated, using the example seen

    earlier. This creates a new variable in PHP and allocates a Dog object that can be accessedusing that variable, providing access to the public properties and methods of that class.

    Accessing Public Properties and Methods

    Next, the public properties and methods of the object is accessed, by changing the color ofthe dog's fur (perhaps dying it), and then by petting the dog afterwards.$myCanine->furColor = 'brown';$myCanine->Pet();

    Accessing Private Properties and Methods

    Afterwards, an attempt is made to access private properties and methods to which the enduser does not have permissions. In PHP, any attempt to access a private property or methodthrows an immediate fatal error, and script execution halts; in this case, the code will never

    reach the second attempt.$myCanine->Run(); /* Illegal - Private method */echo $myCanine->age; /* Illegal - Private property */Get and Set FunctionsA common convention in object-oriented programming is to use get and set functions. Forexample, a getAge() method could be defined that would allow access to read the canine'sage, but not change it. The canine's fur could also be changed to be a private property, andthen provide a getColor() method to read the value, and a dyeFur() method to attempt tochange the value.

    9.3 Exception Handling

    Exception handling is a core feature of almost any programming language and is designed tohandle the occurrence of some condition that changes the normal flow of execution. Theterm, exception, comes from the fact that an exceptional condition has taken place that has

    prevented the continuing flow of the script in which it occurred.

    The Exception FlowIn the operation of a normal script, there is always the potential for an unexpected event(exception) to creep into the execution of the script. By placing conditional tests at certain

    points in the operation of the script, the programmer can test to see if everything is

    working correctly.

    PHP's Exception-Handling Implementation

    In PHP 5, the implementation of the exceptionhandling capabilities is accomplished with theimproved object-oriented programming (OOP) capabilities.There are two ways to initiate the

    base exception class:

    Default Constructor - A constructor is a block of code that automatically executes at thetime an object is created (or instantiated). The default constructor for the base exception classcontains no parameters to initiate the class.throw new Exception();

  • 7/30/2019 Bebo Report121

    38/43

    38

    The command throw, identifies the function used to initiate an exception being captured.The term, new, refers to the fact that a new object is being created and the class is calledException. Overload Constructor - This constructor method is similar to the default constructor, withthe exception that parameters can be added to personalize the base exception class. The two

    parameters are message and error code:

    omessage - This is the message that will be stored for use in the output of any exceptions thatare captured.

    oerror code - This is a code that is stored (similar to the message) and can be used in theoutput of any exceptions that are captured. This code can be used in an identifier-to-messagetable that displays specific messages based on the audiences needs (ex. language).

    Methods

    After initializing the base exception class, there are six methods that are available for use inany output based on the exception that is caught:

    getMessage() - This returns the message that was passed into the overload constructor, if

    any.

    getCode() - This returns the error code that was passed into the overload constructor, ifany. getLine() - This returns the line number where the exception was thrown in the script.

    getFile() - This returns the name of the file where the exception was thrown. getTrace() - This returns an array consisting of important information that would be usefulin tracing where an exception was thrown: file name, line, function and function parameters. getTraceAsString() - This is identical to getTrace(), but returns the values as a stringrather than an array.

    Putting It All TogetherThe example below demonstrates how the base exception-handling class, with the use of theoverload base class constructor, can throw and capture exceptions:

  • 7/30/2019 Bebo Report121

    39/43

    39

    CHAPTER 10

    ESTABLISHING USER AUTHENTICATION

    10.1 HTTP Authentication

    The HTTP authentication protocol is a basic authentication scheme to allow a client program(like a web browser) to provide credentials in the form of a username and password whenrequesting a request (like a web page) that is protected by this level of authentication.The process of the authentication starts with a user requesting a resource that is protected

    by the http authentication method. Theserver responds with a 401 (unauthorized access)response message. The client program (web browser) recognizes the 401response andproduces a pop-up authentication prompt thatrequests the username and password be

    entered. If the username andpassword match a username and password combination stored ontheserver (and on the appropriate resource), the resource is then made available to the enduser. The server maintains the username andpassword entered in until the browser is closedor a different httpauthentication protected resource is requested. If the username and

    password combination do not match arecognized username and password combination on theserver (and the appropriate resource), the clientprogram produces a response identifying a401 unauthorized access.

    Types of HTTP AuthenticationThere are currently 2 modes of authentication built into HTTP 1.1 protocol, termed 'Basic'and 'Digest' Access Authentication.

    Basic Authentication transmits the username:password pair in an unencrypted form frombrowser to server and in such should not be used for sensitive logins unless operating over anencrypted medium such as Secure Socket Layer (SSL). Digest Authentication sends the server a one way hash of the username:password paircalculated with a time sensitive, server supplied salt value. The use of a salt value means thatevery authentication attempt with the same username:password pair will result in a uniquehash and is not vulnerable to replay attacks.The Digest Authentication Mechanism was developed to provide a general use, simpleimplementation, access control that could be used over unencrypted channels. Users shouldnote that it is not as secure as client-side private-key authentication mechanisms. It is alsoimportant to note that only the username:password is protected by the hashing mechanism

    and that without the use of an encrypting medium such as SSL all retrieved documents willstill be visible to all parties with access to network traffic.These two types of authentication do have their place in applications that requireauthentication; however, they should not be considered high grade protection for sensitiveinformation or access as they do not address network level attacks.

    10.2 PHP Authentication

  • 7/30/2019 Bebo Report121

    40/43

    40

    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 bothconvenient (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 onelocation). PHP allows three types of authentication:

    Hard-coded, file-based and database authentication.Authentication VariablesWithin 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 forauthentication.

    $_SERVER['PHP_AUTH_PW'] - This variable holds the password that is needed forauthentication.

    Limitations of Authentication Variables

    When using the predefined authentication variables, it is important to keep in mind thefollowinglimitations:

    Both variables must be verified at the start of every page. This limitation can beovercome by having each restricted page wrapped in authentication code (in a separate file)

    using the REQUIRE()function. The functions do not work properly with the CGI version of PHP - When running PHPthrough a web server, there are two distinct options: running it using PHP's CGI SAPI, orrunning it as a module for the web server. The CGI version has the advantage of having the

    php.ini read every time a PHP page is called up; thus allowing changes in the php.ini to takeplace immediately (not requiring a restart of the web server). However, the fact that everytime a PHP file is read, the php.ini has to be read, set its settings and load all of its extensions

    prior to actually reading the script makes this choice an unreasonable choice for productionenvironments (may be appropriate in development because changes made can be seenimmediately). These functions do not work on Microsoft's IIS server - the username and password areassigned to the $_SERVER['HTTP_AUTHENTICATION'] variable and must be parsed toobtain the separate username and password.

    10.2.1 Hard-Coded AuthenticationThis is the simplest PHP authentication to implement but has the problem of being limited onflexibility and high on maintenance cost. It literally places the username and password intothe script as seen in the following example:

  • 7/30/2019 Bebo Report121

    41/43

    41

    Using the same username - As the code stands, every user requiring access to this webpage would need to use the same login name and password. This is not the way mostapplications in production work.

    Maintenance nightmare - If the username and password are compromised, a newusername and password have to be hard-coded in and everyone using that username and

    password have to be notified of the change.

    10.2.2 File-Based AuthenticationUsing file-based authentication can eliminate the single username and password problem ofthe hard-coded solution; however, there can still be limitations that must be considered inimplementing this authentication solution.The Users Text FileThe following is the contents of the /tmp/auth_users.txt file:Candance:90e0b2ef171cf8edd7f58527f3134f634ccb7091Celine:44c40e17b33ee3fd125120b7ccddbeed2b2d7db3Frank:ef1c3c9da92b9f869ea684808312525130c7f530

    Granny:eaf7def567e8c7462a7f5530328016203409c474Hank:70f7ec35e966287aefd78352828f21fc0c8fae33Howard:38c260888790bbe43e7ec191fd90544d2c8c59d0Jarel:c968edd668e273763e039a511b76609b195570fdMildred:a9e4af8f7113527a04defa057a7a65136cdae803Pierre:72a3925b00f932dbe79e6ee99818b3556b27e88cRoberta:160409a52594eab968f03a46019ea2ab8e9606a7Rudy:70f08ceac2f2428e3f3b87e2bc5e23d2c3c6f447Tawanda:b5a03cd9c9eaf136aa704e00008b60855903477fYogi:3234eec08278d9c9a22d7478f7adbe0d245dae45

    The File-Based Authentication scriptPrior to showing the example script for using file-based authentication, there are a fewfunctions that need to be discussed: file() - The file() function has one parameter, the location of the file to be read in entered asa string. The function will read the contents of the file into an array, with every line being anarray element. explode() - The explode() function is similar to the split() function, but does not require theuse of PHP's regular expression parsing engine, making it perform quicker. The explode()function has two parameters. sha1() - This function calculates the sha1 hash of the string parameter (the only parameterfor this function) using the US Secure Hash Algorithm 1, and returns that hash.

    The File-Based Authentication Script

  • 7/30/2019 Bebo Report121

    42/43

    42

    list($user,$pswd) = explode(":", $row);// Remove the new line character from the password$pswd = trim($pswd);if (($_SERVER['PHP_AUTH_USER'] == $user) &&

    (sha1($_SERVER['PHP_AUTH_PW']) == $pswd)) {$authorized_user=TRUE;break;}}}// Test to see if there is an authorized userif (!$authorized_user) {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?>

    Limitations of File-Based AuthenticationAlthough this method is much more robust over hard-coding authentication, it still has itslimitations:

    Large Number Of Users - As the user base grows, so does the need to maintain and updatetheauthorized users file. This can become a maintenance time drain and/or a coding nightmare to

    parse and edit with supporting code.

    Limited Infrastructure - The use of file-based authentication schemes are designed forrelatively small data infrastructures. As the data complexity grows, so does the problems

    associated with connecting a flat-file (or multiple flat-files) with other data storage techniques(such as databases).

    Database AuthenticationThe final, and most complete of the three PHP authentication methods, is the utilization of adatabase to maintain and manage the usernames and passwords used to access PHP files. Thissolution provides advanced capabilities in administering authentication systems but also

    provides incredible flexibility and scalability to incorporate the authentication system into thedatabase system as a whole.

    Storing Authentication Data

    The following table will be used to manage the storage of the login information that will beused by PHP to manage logins:CREATE TABLE `customers` (`customerEmail` VARCHAR(40) NOT NULL, `lname` VARCHAR(25) NOTNULL,`fname` VARCHAR(25) NOT NULL, `title` ENUM('Mr.', 'Mrs.','Miss', 'Ms.','Dr.'),`passwd` VARCHAR(30), PRIMARY KEY (`customerEmail`));

  • 7/30/2019 Bebo Report121

    43/43

    CHAPTER 11

    CONCLUSION

    11.1 Course ObjectivesThis course provided developers with the development skills to use PHP and MySQL as acohesive platform for the development of complex dynamic web applications. Uponcompletion of this course you should now be able to: Verify the correct installation of the LAMP Components Utilize the basic components of PHP to build a foundation for more complex webapplications

    Understand the basic components of MySQL to build a foundation for the development offully dynamic and database-driven sites

    Manage databases within MySQL

    Manage Tables within MySQL Utilize SQL query commands to retrieve data from the MySQL Database

    Utilize SQL expressions Manipulate table data using the SQL Data Manipulation Language (DML) commands Retrieve data from multiple MySQL tables using Joins Create web based forms that interact with the end user and the data within MySQL Utilize session handling within PHP to track user-specific behavior and preferences. Utilize error and exception handling in PHP to detect, log and report issues that may ariseduring program execution Integrate PHP's object oriented programming (OOP) functionality into the design of webapplications Authenticate user identities utilizing PHP built-in authentication capabilities and MySQL'suser and privilege management capabilities