400 likes | 425 Vues
Review for Finals (2010). Important Dates. 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. Topics & Distribution of Marks. CGI CSS Applets Javascript HTML Cookies & Sessions
E N D
Important Dates • 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
Topics & Distribution of Marks CGI CSS Applets Javascript HTML Cookies & Sessions MySQL Relational Database JSP-Servlets-MySQL Webserver-MySQL-PHP-TCP/IP-HTTP HTML-PHP-MySQL-AJAX Integration – 26 marks Security – 11 marks PHP-Object Orientation – 6 marks 43 marks 17 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 methodattribute • 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!
PHP-MySQL-AJAX Example #1 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 AJAXcan be used to runPHP scripts that obtain up-to-the-minute information stored on a database. The database is queriedwhen the user interacts with the application, delivering accurate information without the inconvenience of a page reload.
Database Stock Example <!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> ... example18-2.htm We have two Javascript filesin our example. They are loaded in the <head> section of our HTML file.
Database Stock Example <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> … example18-2.htm (continuation…) We have a query inputtext field and a submit button The submit button includes an onclick event which invokes thestartJS()function when clicked (example18-2.js).
Database Stock Example <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> <divid="strStockResult"></div> </form> </body> </html> example18-2.htm (continuation…) The <div> element defines a sectionused to display the outputfrom the PHP script.
AJAX – connect to server, send request example18-2.js function startJS() { xhrequest = null; try { xhrequest = getXMLHttpRequest(); } catch(error) { document.write("Cannot run Ajax code using this browser"); } if(xhrequest != null) { // get form values varstrStock = document.getElementById("strStock").value; varstrUrl = "example18-2.php?strStock=" + strStock; xhrequest.onreadystatechange = changePage; xhrequest.open("GET", strUrl, true); xhrequest.send(null); } } ... Checks if AJAX is supported. It checks if the xmlhttprequestobject can be created. Obtain query data entered on the form PHP script file + User’s query Sets a function that obtains the data output from PHP script Open a connection to the PHP script, then pass the data Null because we have appended the query parameters already startJS() is invoked when the button is clicked.
AJAX – obtain output from server function changePage() { if (xhrequest.readyState == 4 && xhrequest.status == 200) { varstrResponse= xhrequest.responseText; document.getElementById("strStockResult").innerHTML = strResponse; } } example18-2.js (continuation…) Check if data is available 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 The window object represents an open window in a browser. function getXMLHttpRequest() { varxhrequest = null; if(window.XMLHttpRequest) { // If IE7, Mozilla, Safari, etc: Use native object try { xhrequest = newXMLHttpRequest(); return xhrequest; } catch(exception) { // OK, just carry on looking } } Check if this property is present Use native scripting 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 varIEControls = ["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"]; for(vari=0; i<IEControls.length; i++) { try { xhrequest = newActiveXObject(IEControls[i]); return xhrequest; } catch(exception) { // OK, just carry on looking } } // if we got here we didn’t find any matches throw new Error("Cannot create an XMLHttpRequest"); } } Microsoft has developed different implementations of the XMLHttpRequest object over time. ActiveXObject is an older version implementation.
PHP Script <?php $strStock = $_GET["strStock"]; $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 * FROMstock WHEREName='$strStock' ", $dbLocalhost) or die("Problem reading table: " . mysql_error()); $intRecords = mysql_num_rows($dbRecords); if ($intRecords == 0) echo "<p>Stock Item '$strStock' Unknown.</p>"; else { while ($arrRecords= mysql_fetch_array($dbRecords)) { $strDescription = $arrRecords["Description"]; $intQuantity = $arrRecords["Quantity"]; echo "<p>$strDescription: Currently we have $intQuantity of boxes.</p>"; } } ?> example18-2.php Contains the user’s query Table named stock • 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 INSERTtag to add more data entries.
Prevent your code from being probed by attackers The first step is to scrutinize all functions, and attempt to compensate for the bulk of the errors. The second is to disable error reporting entirely on the running code. 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. 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. error_reporting = E_ALL PHP.ini approach error_reporting(0); PHP script approach http://nz2.php.net/manual/en/security.errors.php
SQL Injection-prone 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()); $dbRecords= mysql_query("SELECT * FROMusers WHEREuserName= '$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>"; ?> An attacker could use the following combination sqlInjection_prone2.php
SQL Injection-prone script! <?php $strUserName= "' OR '0 "; $strPassword = ' '; ... mysql_query("SELECT * FROMusers WHEREuserName= '$strUserName' "); After substitution of values, the statement becomes: mysql_query("SELECT * FROMusers WHEREuserName= ' ' OR '0 ' "); • 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-safescript! <?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-safescript! <?php $strUserName= "' OR '0 "; $strPassword = ' '; ... $strUserName = mysql_real_escape_string($strUserName); mysql_query("SELECT * FROMusers WHEREuserName= '$strUserName' "); After substitution of values, the statement becomes: mysql_query("SELECT * FROMusers WHEREuserName= ' \' OR \'0 ' "); • 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 Data members <?php class Person{ private $strFirstname = “Napoleon"; private $strSurname = “Reyes"; function getFirstname() { return $this->strFirstname; } function getSurname() { return $this->strSurname; } } // outside the class definition $obj = newPerson; // an object of type Person echo "<p>Firstname: " . $obj->getFirstname() . "</p>"; echo "<p>Surname: " . $obj->getSurname() . "</p>"; ?> Methods Example16-1.php
function getName(){ return $this->strName; } $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; }
We need a method to access and change its value: function setNumber($intNumber) { $this->intNumber = $intNumber; } Modifying data members • intNumberis private • Outside the class, trying to execute the following: $clMyObj->intNumber++; • will fail!... Look at the position of the dollar sign ($) – no longer attached to the variable name
PHP-Object-Orientation Multiple Files
function __autoload() • The function is invokedautomatically 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'; } $objSimon = newperson; $objSimon->setDisplayFirstnameSurname(“Napoleon", “Reyes"); $objBike = newvehicle("Bicycle"); echo "<p>Vehicle: " . $objBike->getDescription() . "</p>"; ?> Class definition comes from another file. Example16-7.php
5. Send generated page back to browser via HTTP Server-Client Interaction Glassfish Java EE application server 2. Initiate query on subject table 1. Request for index.jsp Index.jsp JSTL codes ------------ ------------ ------------ 4. Insert records into page by referring to the name of data source ------------ ------------ ------------ ------------ ------------ ------------ Jsf-impl.jar submit Web browser MySQL Server MyNewDatabase 3. Send records based on query result Subject (Table) Data resource: Name:jdbc/IFPWAFCAD Counselor(Table)