Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Entity–attribute–value model wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Functional Database Model wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Relational model wikipedia , lookup
Oct. 22 – deadline for the submission of Assignment #2 • submit a CD and a hard copy of the documentation Nov. 9 – Final Exam, 2:15pm CGI CSS Applets Javascript HTML Cookies & Sessions MySQL Relational Database JSP-Servlets-MySQL Webserver-MySQL-PHP-TCP/IP-HTTP 17 marks HTML-PHP-MySQL-AJAX Integration – 26 marks Security – 11 marks PHP-Object Orientation – 6 marks 43 marks Total = 17+43 = 60 marks HTML Document <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>My first HTML document</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" > </head > <body> <p> Hello world! </p> </body > </html > Examples of Forms Text Field with Fieldset <fieldset> <legend> User Info </legend> <form action= "response.php" method="get"> First name: <input type="text" name="firstname" ><br> Last name: <input type="text" name="lastname" > </form> </fieldset> GET and POST form submission • The Form tag specifies a method attribute – GET submits form data using the get method • The form data is encoded into the URL and visible in most browsers • There are practical limits to the size of encoded URIs received by servers • Some characters are not allowed in the URI (only ASCII) http://www.someurl/cgi-bin/script?var1=1&var2=4 – POST submits the form data using the post method • Form Data is encoded using the Enctype specified, default encoding is url encoding Using CGI: POST method (GET was originally used only to get data from server) data is passed via standard input stream (stdin) the length (in bytes) of the data passed via $CONTENT_LENGTH. If the program reads more than the length, ...unpredictable behaviour may happen! Files • MySQL database (*.sql) • PHP script (*.php) • HTML document (*.htm) • Javascript (*.js) Communicates with the MySQL server to retrieve records based on a user’s query Database Stock Example Contains the user’s query PHP script output AJAX can be used to run PHP scripts that obtain up-to-theminute information stored on a database. The database is queried when the user interacts with the application, delivering accurate information without the inconvenience of a page reload. Database Stock Example example18-2.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Stock Script</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <script type="text/javascript" src="getxmlhttprequest.js"> </script> <script type="text/javascript" src="example18-2.js"> </script> </head> ... We have two Javascript files in our example. They are loaded in the <head> section of our HTML file. Database Stock Example example18-2.htm (continuation…) <body> <h2>Fruit Stock Information:</h2> <form action="" method="post"> <p> <label for="strStock">Stock Query: </label> <input type="text" name="strStock" id="strStock"/> </p> <p> <input type="button" value="Check" onclick="startJS();"/> </p> … We have a query input text field and a submit button The submit button includes an onclick event which invokes the startJS() function when clicked (example18-2.js). Database Stock Example example18-2.htm (continuation…) <body> <h2>Fruit Stock Information:</h2> <form action="" method="post"> <p> <label for="strStock">Stock Query: </label> <input type="text" name="strStock" id="strStock"/> </p> <p> <input type="button" value="Check" onclick="startJS();"/> </p> <div id="strStockResult"></div> </form> </body> </html> The <div> element defines a section used to display the output from the PHP script. AJAX – connect to server, send request example18-2.js function startJS() { xhrequest = null; Checks if AJAX is supported. try { It checks if the xmlhttprequest xhrequest = getXMLHttpRequest(); object can be created. } catch(error) { document.write("Cannot run Ajax code using this browser"); } Obtain query data entered on the form if(xhrequest != null) { // get form values var strStock = document.getElementById("strStock").value; var strUrl = "example18-2.php?strStock=" + strStock; xhrequest.onreadystatechange = changePage; xhrequest.open("GET", strUrl, true); xhrequest.send(null); PHP script file + User’s query Sets a function that obtains the data output from PHP script } } ... Null because we have appended the query parameters already Open a connection to the PHP script, then pass the data startJS() is invoked when the button is clicked. AJAX – obtain output from server example18-2.js (continuation…) Check if data is available function changePage() { if (xhrequest.readyState == 4 && xhrequest.status == 200) { var strResponse = xhrequest.responseText; document.getElementById("strStockResult").innerHTML = strResponse; } } Retrieve response from the server changePage() obtains the data output from the PHP script then stores it into a variable named strResponse. The data is then injected into the strStockResult <div> section defined in the HTML. This is accomplished using the innerHTML method. getXMLHttpRequest() – user-defined getxmlhttprequest.js function getXMLHttpRequest() { var xhrequest = null; The window object represents an open window in a browser. Check if this property is present if(window.XMLHttpRequest) { // If IE7, Mozilla, Safari, etc: Use native object try { xhrequest = new XMLHttpRequest(); return xhrequest; Use native scripting } catch(exception) { // OK, just carry on looking } Continued... } Our Javascript needs to be able to acquire the appropriate type of XMLHttpRequest object, depending on the browser the script is running in. getXMLHttpRequest() – user-defined getxmlhttprequest.js Testing is done starting from the most recent backwards. else { // ...otherwise, use the ActiveX control for IE5.x and IE6 var IEControls = ["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"]; for(var i=0; i<IEControls.length; i++) { try { Microsoft has developed different xhrequest = new ActiveXObject(IEControls[i]); implementations of the XMLHttpRequest return xhrequest; object over time. } catch(exception) { ActiveXObject is an older version // OK, just carry on looking implementation. } } // if we got here we didn’t find any matches throw new Error("Cannot create an XMLHttpRequest"); } } PHP Script <?php $strStock = $_GET["strStock"]; example18-2.php $dbLocalhost = mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error()); mysql_select_db("stock", $dbLocalhost ) or die("Could not find database: " . mysql_error()); $dbRecords = mysql_query("SELECT * FROM stock WHERE Name='$strStock' ", $dbLocalhost ) or die("Problem reading table: " . mysql_error()); $intRecords = mysql_num_rows($dbRecords ); Contains the user’s query if ($intRecords == 0) echo "<p>Stock Item '$strStock' Unknown.</p>"; Table named stock else { while ($arrRecords = mysql_fetch_array($dbRecords)) { $strDescription = $arrRecords ["Description"]; $intQuantity = $arrRecords["Quantity"]; echo "<p>$strDescription: Currently we have $intQuantity of boxes.</p>"; } } ?> • Queries the database and outputs the corresponding records found Stock Table (Structure) Id is a primary key, also set to auto_increment. You need to create your database first using phpMyAdmin, then import the stock.sql file containing the structure and data entries. Stock Table (data) •You can populate the database easily using phpMyAdmin. •You can import the stock.sql file containing the structure and initial data entries. •You can select the INSERT tag to add more data entries. Prevent your code from being probed by attackers 1. The first step is to scrutinize all functions, and attempt to compensate for the bulk of the errors. 2. The second is to disable error reporting entirely on the running code. 3. The third is to use PHP's custom error handling functions to create your own error handler. http://nz2.php.net/manual/en/security.errors.php Prevent your code from being probed by attackers One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. PHP.ini approach error_reporting = E_ALL Once you are ready for deployment, you should either disable error reporting completely by setting error_reporting() to 0, or turn off the error display using the php.ini option display_errors, to insulate your code from probing. PHP script approach error_reporting(0); http://nz2.php.net/manual/en/security.errors.php SQL Injection-prone script! <?php $strUserName = " ' OR '0 "; $strPassword = ''; An attacker could use the following combination $dbLocalhost = mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error()); mysql_select_db("users", $dbLocalhost) or die("Could not find database: " . mysql_error()); $dbRecords = mysql_query("SELECT * FROM users WHERE userName= '$strUserName' "); $intCount = mysql_num_rows($dbRecords ); echo "<p>Count: " . $intCount . "</p>"; $arrRecords = mysql_fetch_array($dbRecords); echo $arrRecords["password"]; if ($strPassword != $arrRecords["password"]) echo "<p>Invalid Password/UserName</p>"; else echo "<p>Password and UserName match!</p>"; ?> sqlInjection_prone2.php SQL Injection-prone script! <?php $strUserName = " ' OR '0 "; $strPassword = ' '; ... mysql_query("SELECT * FROM users WHERE userName= '$strUserName' "); After substitution of values, the statement becomes: ("SELECT * FROM users WHERE userName= ' ' OR '0 ' "); mysql_query • This statement will force the query not to return any records, and as the password is set to NULL, the if statements comparing the passwords evaluates to true. • Therefore, the script thinks that the username and password matches. sqlInjection_prone2.php SQL Injection-safe script! <?php $strUserName = "' OR '0"; $strPassword = ''; $dbLocalhost = mysql_connect("localhost", "root", "“) or die("Could not connect: " . mysql_error()); mysql_select_db("users", $dbLocalhost) or die("Could not find database: " . mysql_error()); $strUserName = mysql_real_escape_string($strUserName); $dbRecords = mysql_query("SELECT * FROM users WHERE userName='$strUserName'"); $arrRecords = mysql_fetch_array($dbRecords); if (mysql_num_rows($dbRecords) != 1) echo "<p>Username not found!</p>"; else { if ($strPassword != $arrRecords["Password"]) echo "<p>Invalid Password/UserName</p>"; else echo "<p>Password and UserName match!</p>"; } ?> sqlInjection_secure.php SQL Injection-safe script! <?php $strUserName = " ' OR '0 "; $strPassword = ' '; ... $strUserName = mysql_real_escape_string($strUserName); mysql_query("SELECT * FROM users WHERE userName= '$strUserName' "); After substitution of values, the statement becomes: ("SELECT * FROM users WHERE userName= ' \' OR \'0 ' "); mysql_query • The mysql_real_escape_string function escapes quotation characters in the SQL string removing the danger of the quotes being interpreted incorrectly by the SQL parser. • In addition, it is important to count the number of records returned using mysql_num_rows() as another security measure. sqlInjection_secure.php Defining classes <?php class Person { private $strFirstname = “Napoleon"; private $strSurname = “Reyes"; function getFirstname() { return $this->strFirstname; } function getSurname() { return $this->strSurname; } Data members Methods } // outside the class definition $obj = new Person; // an object of type Person echo "<p>Firstname: " . $obj->getFirstname() . "</p>"; echo "<p>Surname: " . $obj->getSurname() . "</p>"; ?> Example16-1.php $this object pointer As with so many languages, there is a special pointer that references an instance of a class: $this function getName(){ return $strName; } function getName(){ return $this->strName; } Modifying data members intNumber is private Outside the class, trying to execute the following: $clMyObj->intNumber++; will fail!... We need a method to access and change its value: function setNumber($intNumber) { $this->intNumber = $intNumber; } Look at the position of the dollar sign ($) – no longer attached to the variable name function __autoload() • The function is invoked automatically each time a class is required but has not been defined. • We can insert this function into our script: function __autoload($class_name) { require_once $class_name . '.php'; } Note: Class_name = File_name Example16-7.php function __autoload() <?php function __autoload($class_name) { require_once $class_name . '.php'; } Class definition comes from another file. $objSimon = new person; $objSimon->setDisplayFirstnameSurname(“Napoleon", “Reyes"); $objBike = new vehicle("Bicycle"); echo "<p>Vehicle: " . $objBike->getDescription() . "</p>"; ?> Example16-7.php Server-Client Interaction 1. Request for index.jsp 5. Send generated Glassfish 2. Initiate Java EE application server page back to browser via query on Index.jsp HTTP subject table JSTL codes ---------------------------------- ---------------------------------- submit Web browser 4. Insert records into page by referring to the name of data source ---------------------------------- Jsf-impl.jar MySQL Server MyNewDatabase 3. Send records based on query result Subject (Table) Data resource: Counselor(Table) Name: jdbc/IFPWAFCAD