Texas A&M University
PHP working with HTML FormsThe HTML Form – The TheoryThe HTML form is where we place values to be acceptedlog ins, account creation, anything you have to type in valueHTML Form and PHP MechanicsThe HTML form is specialrequires special tags<form>requires <inputs>types of inputs (HTML 5 has new ones!!)radio buttonstext boxesetc…new HTML 5 inputs old stuff a <SUBMIT> button!!a form MUST be used in order to transfer data to our PHP scriptthere are several ways of transferring dataPOST – data is encrypted by the browserGET – data appears in the URL bodyCommunication between Form and ScriptBrowser sends the data using the POST value to the ServerServer then translates, and responses using the PHP scriptbut the name of the HTML component MUST MATCH!!!How communication is handledThe HTML Form – Basic SetupForm only portion of HTML document that collects data and can send to our PHP scriptmust containactionwhere (what PHP script) the data will be sent tomethod, how the data is sentalways POST for usnamename of the formreally used for JavaScript validationThe basic form setupOverall LookHeadBodyFormTailHTML code (extreme basic)<html><head><title>Lupoli’s First Form Example</title></head><body><form action="LoginOptions.php" method="post" name="Form1"><!— HTML Form Components go here –-> <input type='submit' value='submit'></form></body></html>List and Naming Scheme of Simple Form Componentskeeping with a naming scheme is helpfulnaming scheme examplestfFnametext fieldrbCandidateradio buttonpfPasswordpasswordcbOption2checkboxetc…Reducing repetitive code using includesmuch like includes in other programming languagesinclude custom codefor our example will use includes to eliminate HEAD and TAIL of HTML pageBUT!!the “form” page must NOW be PHP in order to work!!but it looks very similar!!Overall setup with includesheadHTML.html<html><head><title>CMSC 331 PHP</title></head><body><!-- rest of HTML code -->newForm.php<?phpinclude("headHTML.html");// Start form?><form action="LoginOptions.php" method="post" name="Form1"><input type="text" size="25" maxlength="25" name="tfFname"><input type="text" size="25" maxlength="25" name="tfLname">33623255334000<input type="submit" value="submit"> <!-- ONLY ONE SUBMIT BUTTON!! </form><?php// End of forminclude("tailHTML.html");?>tailHTML.html</body></html>Receiving the value in the PHP scriptwe first have to remember how we transmitted the dataPOST/GETthen we need to capture the values using the syntax $_POST[‘formItem’]inputs send data as a StringScript accepting Form values #1<?php$Fname = $_POST['tfFname']; // was name tfFname on HTML FORM!!!$Lname = $_POST['tfLname']; // was name tfLname on HTML FORM!!!print ($Fname . “ “ . $Lname);?>Converting a string to a PHP int or double value$value = intval($_POST[‘tfbox’])$value = doubleval($_POST[‘tfbox’]);Script accepting Form values #2<?php$debug = true; session_start(); include('../CommonMethods.php');$COMMON = new Common($debug); // common methodsprint($_POST['tfUsername']);print($_POST['tfPassword']);$rank = getRank($_POST['tfUsername'], $_POST['tfPassword']);switch ($rank){case 'T': print("You are a teacher"); break;case 'S': print("You are a student"); break;default: print("You are NOTHING!!!"); break;}function getRank($u, $p){global $debug; global $COMMON;$sql = "select `rank` from user_info where `password` = '$p' AND `username` = '$u'";$rs = $COMMON->executeQuery($sql, __FILE__);$row = mysql_fetch_array($rs); // collects row data into an array named rowreturn $row['rank'];}?>First Full Form and Result ExampleVersion 1<html><head></head><body><form action='results.php' method='post' name='form1'>365887058420value 1:<input type='text' name='value1'>value 2:<input type='text' name='value2'>value 3:<input type='text' name='value3'><input type='submit'></form></body></html> $num1 = doubleVal($_POST['value1']);$num2 = doubleVal($_POST['value2']);$num3 = doubleVal($_POST['value3']);$average = ($num1 + $num2 + $num3) /3;echo($average . " is the average of the 3 values");?>Version 2<?phpecho("<html>");echo("<head>");echo("</head>");33667701397000echo("<body>");echo("");echo("<form action='results.php' method='post' name='form1'>");echo("value 1:<input type='text' name='value1'>");echo("value 2:<input type='text' name='value2'>");echo("value 3:<input type='text' name='value3'>");echo("");echo("<input type='submit'>");echo("</form>");2903220762000echo("</body>");echo("</html>");?>Version 3<?phpinclude('../headHTML.html'); ?><form action='results.php' method='post' name='form1'>value 1:<input type='text' name='value1'>value 2:<input type='text' name='value2'>value 3:<input type='text' name='value3'><input type='submit'><?phpinclude('../tailHTML.html');?>Watch for smart quotes!if you are copying (cheating) from my code, be careful that the text does not copy over as smart quotes!!will treat each quote type differentlydifference between working or not!!Smart Quotes!!WorkingNot working!!print($_POST['tbValue1']);print($_POST[‘tbValue1’]);Exercise in PHP #1Suppose that we want to find the height of this tree.Create an HTML page “angle.html” that will accept:an angledistance from tree (x)Create a PHP page “results.php” that will answer the heightneed to use PHP’s tan function (need to look up)Checking you answerFrom a point on the ground, a tree has an angle of elevation 27o and it is 34m away. How tall is the tree (to 1 decimal place)? = 17.3Exercise in PHP #2You’re going bowling!! Each person on your team will bowl 1 GAME!!! (ONLY 1) You will enter each score, and the script will determine the highest score!!Use the bowling game at:, treat the mouse as your arm, move it forward and backwardCreate an HTML page that will accept:3 bowling scoresCreate a PHP page that will determine the highest scoreuse a PHP array to orderUsing the header to move to other pagespersonally, I find it easier to create a page for each action that happenssome early PHP programmers will have the SAME page do multiple “applications”this makes the code unorganized and cumbersomehere we will have separate PHP pages to go to that have the different applicationsin this scenario a user logs in, and depending on type, some session variables are set so other pages can use themUser Login ScenarioLakCar14using a headermoves to another “pre-created” pageoften used when determining a user, and what page they seeSample header codeif ($rank == 0) // a Teacher { header('Location: teacher.php'); }else // a student { header('Location: student.php'); }Handing passwords from formstwo stageswhen the user creates an account with a passwordmust encrypt when entering that data in DBwhen user re-enters application, password is validatedmust compare given password with MD5 version in DBthe HTML form should encrypt the password being typed inthe database should encrypt the passwordso how do we compare the encrypted password with the form value given?use MD5 hash to encrypt the password data on the DBFrom RFC 1321 - The MD5 Message-Digest Algorithm:?"The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA."“Salt” is the newest password encryption but many servers don’t support itHTML Form password encryption...<div class="field"> <label for="PassW">Password</label> <input id="PassW" size="20" maxlength="50" type="password" name="PassW" required></div>...Inserting new password into DB<?phpsession_start();$debug = false;include('CommonMethods.php');$COMMON = new Common($debug);$sql = "INSERT INTO user_accounts (username,password) VALUES('slupoli','".md5('slupoli')."')";$rs = $COMMON->executeQuery($sql, $_SERVER["SCRIPT_NAME"]);?>Checking the password when user logs in<?phpsession_start();$debug = false;include('CommonMethods.php');$COMMON = new Common($debug);//$passW = $_POST['password'];$sql = "SELECT * FROM user_accounts WHERE username = 'slupoli' AND password = '".md5('slupoli')."'";$rs = $COMMON->executeQuery($sql, $_SERVER["SCRIPT_NAME"]);$num_rows = mysql_num_rows($rs);if($num_rows == 1) // so only one match!!{echo("password correct");}else{echo("password INCORRECT");}?>Answerscode for average.html<html><head><title>Averaging values</title></head><body><form action="results.php" method="post" name="Form1">Please enter 3 values, the average will be determined after submitting<br><input type="text" size="25" maxlength="25" name="tbValue1"><br><input type="text" size="25" maxlength="25" name="tbValue2"><br><input type="text" size="25" maxlength="25" name="tbValue3"><br><br><input type='submit' value='submit'></form></body></html>Answer for results.php<html><head><title>Results of Average</title></head><body><?php// checking that the values came through//print($_POST['tbValue1']);//print($_POST['tbValue2']);//print($_POST['tbValue3']);$value1 = doubleval($_POST['tbValue1']);$value2 = doubleval($_POST['tbValue2']);$value3 = doubleval($_POST['tbValue3']);$average = ($value1 + $value2 + $value3)/3;print $average?></body></html>Resources:html/html_forms.asp ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.