Question? Leave a message!




Introduction to PHP

Introduction to PHP 21
PHP/MySQL Introduction Goal • Not to teach everything about PHP, but provide the basic knowledge • Explain code of examples • Provide some useful references PHP Basics: Introduction to PHP • a PHP file, PHP workings, running PHP.  Basic PHP syntax • variables, operators, if...else...and switch, while, do while, and for.  Some useful PHP functions  How to work with • HTML forms, cookies, files, time and date.  How to create a basic checker for userentered dataServerSide Dynamic Web Programming • CGI is one of the most common approaches to serverside programming  Universal support: (almost) Every server supports CGI programming. A great deal of readytouse CGI code. Most APIs (Application Programming Interfaces) also allow CGI programming.  Choice of languages: CGI is extremely general, so that programs may be written in nearly any language. Perl is by far the most popular, with the result that many people think that CGI means Perl. But C, C++, Ruby, and Python are also used for CGI programming.  Drawbacks: A separate process is run every time the script is requested. A distinction is made between HTML pages and code.• Other serverside alternatives try to avoid the drawbacks  ServerSide Includes (SSI): Code is embedded in HTML pages, and evaluated on the server while the pages are being served. Add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program.  Active Server Pages (ASP, Microsoft) : The ASP engine is integrated into the web server so it does not require an additional process. It allows programmers to mix code within HTML pages instead of writing separate programs. (Drawback() Must be run on a server using Microsoft server software.)  Java Servlets (Sun): As CGI scripts, they are code that creates documents. These must be compiled as classes which are dynamically loaded by the web server when they are run.  Java Server Pages (JSP): Like ASP, another technology that allows developers to embed Java in web pages.PHP • developed in 1995 by Rasmus Lerdorf (member of the Apache Group)  originally designed as a tool for tracking visitors at Lerdorf's Web site  within 2 years, widely used in conjunction with the Apache server  developed into fullfeatured, scripting language for serverside programming  free, opensource  server plugins exist for various servers  now fully integrated to work with mySQL databases • PHP is similar to JavaScript, only it’s a serverside language  PHP code is embedded in HTML using tags  when a page request arrives, the server recognizes PHP content via the file extension (.php or .phtml)  the server executes the PHP code, substitutes output into the HTML page  the resulting page is then downloaded to the client  user never sees the PHP code, only the output in the pageWhat do You Need • Our server supports PHP • You don't need to do anything special • You don't need to compile anything or install any extra tools • Create some .php files in your web directory and the server will parse them for you. Slightly different rules apply when dealing with an SQL database (as will be explained when we get to that point). • Most servers support PHP • Download PHP for free here: http://www.php.net/downloads.php • Download MySQL for free here: http://www.mysql.com/downloads/index.html • Download Apache for free here: http://httpd.apache.org/download.cgi (Note: All of this is already present on the CS servers, so you need not do any installation yourself to utilize PHP on our machines.)What is PHP • PHP == ‘Hypertext Preprocessor’ • Opensource, serverside scripting language • Used to generate dynamic webpages • PHP scripts reside between reserved PHP tags • This allows the programmer to embed PHP scripts within HTML pages • The acronym PHP means (in a slightly recursive definition)  PHP: Hypertext PreprocessorWhat is PHP (cont’d) • Interpreted language, scripts are parsed at runtime rather than compiled beforehand • Executed on the serverside • Sourcecode not visible by client •‘View Source’ in browsers does not display the PHP code • Various builtin functions allow for fast development • Compatible with many popular databasesWhat does PHP code look like • Structurally similar to C/C++ • Supports procedural and objectoriented paradigm (to some degree) • All PHP statements end with a semicolon • Each PHP script must be enclosed in the reserved PHP tag php … Comments in PHP • Standard C, C++, and shell comment symbols // C++ and Javastyle comment Shellstyle comments / Cstyle comments These can span multiple lines /Variables in PHP • PHP variables must begin with a “” sign • Casesensitive (Foo = foo = fOo) • Global and locallyscoped variables • Global variables can be used anywhere • Local variables restricted to a function or class • Certain variable names reserved by PHP • Form variables (POST, GET) • Server variables (SERVER) • Etc.Constants A constant is an identifier (name) for a simple value. A constant is casesensitive by default. By convention, constant identifiers are always uppercase. php // Valid constant names define("FOO", "something"); define("FOO2", "something else"); define("FOOBAR", "something more"); You can access // Invalid constant names (they shouldn‟t start constants anywhere // with a number) in your script define("2FOO", "something"); without regard to scope. // This is valid, but should be avoided: // PHP may one day provide a “magical” constant // that will break your script define("FOO", "something"); Operators Example Is the same as • Arithmetic Operators: +, , ,/ , , ++, x+=y x=x+y x=y x=xy • Assignment Operators: =, +=, =, =, /=, = x=y x=xy x/=y x=x/y x=y x=xy • Comparison Operators: ==, =, , , =, = • Logical Operators: , , • String Operators: . and .= (for string concatenation) a = "Hello "; b = a . "World"; // now b contains "Hello World" a = "Hello "; a .= "World";Variable usage php foo = 25; // Numerical variable bar = “Hello”; // String variable foo = (foo 7); // Multiplies foo by 7 bar = (bar 7); // Invalid expression Basic PHP syntax A PHP scripting block always starts with php and ends with . A PHP scripting block can be placed (almost) anywhere in an HTML document. html print and echo hello.php headtitleHello World/title/head for output body pThis is going to be ignored by the PHP interpreter./p php echo „pWhile this is going to be parsed./p„; a semicolon (;) at the end of each pThis will also be ignored by the PHP preprocessor./p statement php print(„pHello and welcome to imy/i page/p'); php // for a singleline comment //This is a comment / and / for a large / This is comment block. a comment block / /body /html The server executes the print and echo statements, substitutes output.Scalars All variables in PHP start with a sign symbol. A variable's type is determined by the context in which that variable is used (i.e. there is no strongtyping in PHP). htmlhead/head scalars.php body p php foo = true; if (foo) echo "It is TRUE br / \n"; Four scalar types: txt='1234'; echo "txt br / \n"; a = 1234; echo "a br / \n"; boolean a = 123; true or false echo "a br / \n"; a = 1.234; integer, echo "a br / \n"; a = 1.2e3; float, echo "a br / \n"; floating point numbers a = 7E10; echo "a br / \n"; string echo 'Arnold once said: "I\'ll be back"', "br / \n"; beer = 'Heineken'; single quoted echo "beer's taste is great br / \n"; double quoted str = EOD Example of string spanning multiple lines using “heredoc” syntax. EOD; echo str; /p /body /htmlEcho • The PHP command „echo‟ is used to output the parameters passed to it • The typical usage for this is to send data to the client‟s webbrowser • Syntax • void echo (string arg1 , string argn...) • In practice, arguments are not passed in parentheses since echo is a language construct rather than an actual functionEcho example php foo = 25; // Numerical variable bar = “Hello”; // String variable echo bar; // Outputs Hello echo foo,bar; // Outputs 25Hello echo “5x5=”,foo; // Outputs 5x5=25 echo “5x5=foo”; // Outputs 5x5=25 echo „5x5=foo‟; // Outputs 5x5=foo • Notice how echo „5x5=foo‟ outputs foo rather than replacing it with 25 • Strings in single quotes („ ‟) are not interpreted or evaluated by PHP • This is true for both variables and character escapesequences (such as “\n” or “\\”)Arithmetic Operations php a=15; b=30; total=a+b; Print total; Print “ph1total/h1”; // total is 45 • a b // subtraction • a b // multiplication • a / b // division • a += 5 // a = a+5 Also works for = and /=Concatenation • Use a period to join strings into one. php string1=“Hello”; string2=“PHP”; string3=string1 . “ ” . string2; Print string3; Hello PHPEscaping the Character • If the string has a set of double quotation marks that must remain visible, use the \ backslash before the quotation marks to ignore and display them. php heading=“\”Computer Science\””; Print heading; “Computer Science”PHP Control Structures  Control Structures: Are the structures within a language that allow us to control the flow of execution through a program or script.  Grouped into conditional (branching) structures (e.g. if/else) and repetition structures (e.g. while loops).  Example if/else if/else statement: if (foo == 0) echo „The variable foo is equal to 0‟; else if ((foo 0) (foo = 5)) echo „The variable foo is between 1 and 5‟; else echo „The variable foo is equal to „.foo; If ... Else... • If (condition) php If(user==“John”) Statements; Print “Hello John.”; Else Else Print “You are not John.”; Statement; No THEN in PHPConditionals: if else Can execute a set of code depending on a condition htmlhead/head if (condition) ifcond.php code to be executed if condition body is true; php else d=date("D"); echo d, “br/”; code to be executed if condition if (d=="Fri") is false; echo "Have a nice weekend br/"; else echo "Have a nice day br/"; date() is a builtin PHP function that x=10; can be called with many different if (x==10) parameters to return the date echo "Hellobr /"; (and/or local time) in various formats echo "Good morningbr /"; In this case we get a three letter string for the day of the week. /body /htmlWhile Loops php • While (condition) count=0; While(count3) Statements; Print “hello PHP. ”; count += 1; // count = count + 1; // or // count++; hello PHP. hello PHP. hello PHP.Looping: for and foreach Can loop depending on a "counter" php php for (i=1; i=5; i++) aarray = array(1, 2, 3, 4); foreach (aarray as value) echo "Hello Worldbr /"; value = value 2; echo “value br/ \n”; loops through a block of code a php specified number of times aarray=array("a","b","c"); foreach (aarray as key = value) echo key." = ".value."\n"; loops through a block of code for each element in an arrayCan select one of many sets of lines to execute Conditionals: switch htmlhead/head body – switchcond.php php x = rand(1,5); // random integer switch (expression) echo “x = x br/br/”; switch (x) case label1: code to be executed if case 1: expression = label1; echo "Number 1"; break; break; case label2: case 2: code to be executed if echo "Number 2"; expression = label2; break; break; case 3: default: echo "Number 3"; code to be executed break; if expression is different default: from both label1 and label2; echo "No number between 1 and 3"; break; break; /body /htmlDate Display datedisplay=date(“yyyy/m/d”); 2012/25/6 Print datedisplay; If the date is June 25th, 2012 It would display as 2012/25/6 datedisplay=date(“l, F m, Y”); Monday, June 25, 2012 Print datedisplay; th If the date is June 25 ,2012 th Monday, June 25 ,2012Arrays An array in PHP is actually an ordered map. A map is a type that maps values to keys. array() = creates arrays php arr = array("foo" = "bar", 12 = true); echo arr"foo"; // bar key = either an integer or a string. echo arr12; // 1 value = any PHP type. if no key given (as in example), the PHP php interpreter uses (maximum of the integer array(5 = 43, 32, 56, "b" = 12); indices + 1). array(5 = 43, 6 = 32, 7 = 56, "b" = 12); if an existing key, its value will be overwritten. php arr = array(5 = 1, 12 = 2); can set values in an array foreach (arr as key = value) echo key, „=‟, value); unset() removes a arr = 56; // the same as arr13 = 56; key/value pair arr"x" = 42; // adds a new element unset(arr5); // removes the element arrayvalues() makes unset(arr); // deletes the whole array reindexing effect (indexing numerically) a = array(1 = 'one', 2 = 'two', 3 = 'three'); unset(a2); b = arrayvalues(a); Find more on arrays Month, Day Date Format Symbols M Jan F January m 01 n 1 Day of Month d 01 Day of Month J 1 Day of Week l Monday Day of Week D MonFunctions • Functions MUST be defined before then can be called • Function headers are of the format • N fu on tc e titha on fu t n nc oti r oe nturn Nam e ty ( p ae rgis 1 specifi , arged 2, …, argn) • Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…))Functions example php // This is a function function foo(arg1, arg2) arg2 = arg1 arg2; return arg2; result1 = foo(12, 3); // Store the function echo result1; // Outputs 36 echo foo(12, 3); // Outputs 36 User Defined Functions Can define a function using syntax such as the following: php function foo(arg1, arg2, / ..., / argn) Can also define conditional echo "Example function.\n"; functions, functions within functions, return retval; and recursive functions. Can return a value of any type php php function square(num) function smallnumbers() return num num; return array (0, 1, 2); echo square(4); list (zero, one, two) = smallnumbers(); echo zero, one, two; php function takesarray(input) echo "input0 + input1 = ", input0+input1; takesarray(array(1,2)); Variable Scope The scope of a variable is the context within which it is defined. php a = 1; / limited variable scope / function Test() echo a; The scope is local within functions, / reference to local scope variable / and hence the value of a is Test(); undefined in the “echo” statement. php php a = 1; function Test() b = 2; global static function Sum() static a = 0; echo a; refers to its does not lose global a, b; a++; b = a + b; global its value. Test1(); version. Sum(); Test1(); echo b; Test1(); Including Files The include() statement includes and evaluates the specified file. vars.php php php function foo() color = 'green'; fruit = 'apple'; global color; include ('vars.php„); test.php echo "A color fruit"; php echo "A color fruit"; // A / vars.php is in the scope of foo() so fruit is NOT available outside of this include 'vars.php'; scope. color is because we declared it as global. / echo "A color fruit"; // A green apple foo(); // A green apple echo "A color fruit"; // A green The scope of variables in “included” files depends on where the “include” file is added You can use the includeonce, require, and requireonce statements in similar ways. Include Files Include “opendb.php”; Include “closedb.php”; This inserts files; the code in files will be inserted into current code. This will provide useful and protective means once you connect to a database, as well as for other repeated functions. Include (“footer.php”); The file footer.php might look like: hr SIZE=11 NOSHADE WIDTH=“100” iCopyright © 20012012 gsu/i/fontbr iALL RIGHTS RESERVED/i/fontbr iURL: http://www.gsu.edu.edu/i/fontbrPHP Forms •Access to the HTTP POST and GET data is simple in PHP •The global variables POST and GET contain the request data php if (POST"submit") echo "h2You clicked Submit/h2"; else if (POST"cancel") echo "h2You clicked Cancel/h2"; form action="form.php" method="post" input type="submit" name="submit" value="Submit" input type="submit" name="cancel" value="Cancel" /formWHY PHP – Sessions Whenever you want to create a website that allows you to store and display information about a user, determine which user groups a person belongs to, utilize permissions on your website or you just want to do something cool on your site, PHP's Sessions are vital to each of these features. Cookies are about 30 unreliable right now and it's getting worse every day. More and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they do not want stored there. PHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user's computer. PHP Sessions store the information on the web server in a location that you chose in special files. These files are connected to the user's web browser via the server and a special ID called a "Session ID". This is nearly 99 flawless in operation and it is virtually invisible to the user.PHP Sessions •Sessions store their identifier in a cookie in the client‟s browser •Every page that uses session data must be proceeded by the sessionstart() function •Session variables are then set and retrieved by accessing the global SESSION •Save it as session.php php sessionstart(); if (SESSION"count") SESSION"count" = 0; if (GET"count" == "yes") SESSION"count" = SESSION"count" + 1; echo "h1".SESSION"count"."/h1"; a href="session.phpcount=yes"Click here to count/aAvoid Error PHP Sessions PHP Example: php echo "Look at this nasty error below:br /"; sessionstart(); Error Warning: Cannot send session cookie headers already sent by (output started at sessionheadererror/sessionerror.php:2) in sessionheadererror/sessionerror.php on line 3 Warning: Cannot send session cache limiter headers already sent (output started at sessionheadererror/sessionerror.php:2) in sessionheadererror/sessionerror.php on line 3 PHP Example: php sessionstart(); echo "Look at this nasty error below:"; CorrectDestroy PHP Sessions Destroying a Session why it is necessary to destroy a session when the session will get destroyed when the user closes their browser. Well, imagine that you had a session registered called "accessgranted" and you were using that to determine if the user was logged into your site based upon a username and password. Anytime you have a login feature, to make the users feel better, you should have a logout feature as well. That's where this cool function called sessiondestroy() comes in handy. sessiondestroy() will completely demolish your session (no, the computer won't blow up or self destruct) but it just deletes the session files and clears any trace of that session. NOTE: If you are using the SESSION superglobal array, you must clear the array values first, then run sessiondestroy. Here's how we use sessiondestroy():Destroy PHP Sessions php // start the session sessionstart(); header("Cachecontrol: private"); //IE 6 Fix SESSION = array(); sessiondestroy(); echo "strongStep 5 Destroy This Session /strongbr /"; if(SESSION'name') echo "The session is still active"; else echo "Ok, the session is no longer active br /"; echo "a href=\"page1.php\" Go Back Step 1/a"; PHP Overview • Easy learning • Syntax Perl and Clike syntax. Relatively easy to learn. • Large function library • Embedded directly into HTML • Interpreted, no need to compile • Open Source serverside scripting language designed specifically for the web.PHP Overview (cont.) • Conceived in 1994, now used on +10 million web sites. • Outputs not only HTML but can output XML, images (JPG PNG), PDF files and even Flash movies all generated on the fly. Can write these files to the file system. • Supports a widerange of databases (20+ODBC). • PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP.First PHP script • Save as sample.php: – sample.php htmlbody strongHello World/strongbr / php echo “h2Hello, World/h2”; php myvar = "Hello World"; echo myvar; /body/htmlExample of parameter reading • Call with form: • Consider: • contents of phpexec/form01.txt... • contents of phpexec/form.php... form action='phpexec/form.php' • htmlbody method='post' ul li input • h1Hi there/h1 type='checkbox' name='foo' • if (isset(POST'foo')): value='raisins' raisins. li input • h1'foo' is not set/h1 type='checkbox' name='foo' value='cranberries' cranberries. li • elseif (isarray(POST'foo')) : input type='checkbox' name='foo' value='plums' plums. /ul input • h1'foo' has one value = type='submit' /form ...end of POST'foo' /h1 phpexec/form01.txt • else: • Here is what it looks like: • h1'foo' has multiple values = • raisins. join(',',POST'foo') /h1 • cranberries. • endif • plums. • /body/html • ...end of phpexec/form.phpExample – show data in the tables • Function: list all tables in your database. Users can select one of tables, and show all contents in this table. • second.php • showtable.phpsecond.php htmlheadtitleMySQL Table Viewer/title/headbody php // change the value of dbuser and dbpass to your username and password dbhost = ‘ codd.cs…….. '; dbuser = 'nruan'; dbpass = ‘’; dbname = dbuser; table = 'account'; conn = mysqlconnect(dbhost, dbuser, dbpass); if (conn) die('Could not connect: ' . mysqlerror()); if (mysqlselectdb(dbname)) die("Can't select database");second.php (cont.) result = mysqlquery("SHOW TABLES"); if (result) die("Query to show fields from table failed"); numrow = mysqlnumrows(result); echo "h1Choose one table:h1"; echo "form action=\"showtable.php\" method=\"POST\""; echo "select name=\"table\" size=\"1\" Font size=\"+2\""; for(i=0; inumrow; i++) tablename=mysqlfetchrow(result); echo "option value=\"tablename0\" tablename0/option"; echo "/select"; echo "divinput type=\"submit\" value=\"submit\"/div"; echo "/form"; mysqlfreeresult(result); mysqlclose(conn); /body/htmlshowtable.php htmlhead titleMySQL Table Viewer/title /head body php dbhost = 'hercules.cs.kent.edu:3306'; dbuser = 'nruan'; dbpass = ‘’; dbname = 'nruan'; table = POST“table”+; conn = mysqlconnect(dbhost, dbuser, dbpass); if (conn) die('Could not connect: ' . mysqlerror()); if (mysqlselectdb(dbname)) die("Can't select database"); result = mysqlquery("SELECT FROM table"); if (result) die("Query to show fields from table failed" . mysqlerror());showtable.php (cont.) fieldsnum = mysqlnumfields(result); echo "h1Table: table/h1"; echo "table border='1'tr"; // printing table headers for(i=0; ifieldsnum; i++) field = mysqlfetchfield(result); echo "tdbfieldname/b/td"; echo "/tr\n"; while(row = mysqlfetchrow(result)) echo "tr"; // row is array... foreach( .. ) puts every element // of row to cell variable foreach(row as cell) echo "tdcell/td"; echo "/tr\n"; mysqlfreeresult(result); mysqlclose(conn); /body/htmlFunctions Covered • mysqlconnect() mysqlselectdb() • include() • mysqlquery() mysqlnumrows() • mysqlfetcharray() mysqlclose()PHP Information The phpinfo() function is used to output PHP information about the version installed on the server, parameters selected when installed, etc. INFOGENERAL The configuration line, php.ini location, htmlhead/head build date, – info.php Web Server, body System and more php // Show all PHP information INFOCREDITS PHP 4 credits phpinfo(); INFOCONFIGURATION Local and master values for php directives php // Show only the general information INFOMODULES Loaded modules phpinfo(INFOGENERAL); INFOENVIRONMENT Environment variable /body information /html INFOVARIABLES All predefined variables from EGPCS INFOLICENSE PHP license information INFOALL Shows all of the above (default)Server Variables The SERVER array variable is a reserved variable that contains all server information. htmlhead/head body php echo "Referer: " . SERVER"HTTPREFERER" . "br /"; echo "Browser: " . SERVER"HTTPUSERAGENT" . "br /"; echo "User's IP address: " . SERVER"REMOTEADDR"; php echo "br/br/br/"; echo "h2All information/h2"; foreach (SERVER as key = value) SERVER info on php.net echo key . " = " . value . "br/"; /body /html The SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.File Open The fopen("filename","mode") function is used to open files in PHP. r Read only. r+ Read/Write. w Write only. w+ Read/Write. a Append. a+ Read/Append. x Create and open for write only. x+ Create and open for read/write. For w, and a, if no file exists, it tries to create it php fh=fopen("welcome.txt","r"); (use with caution, i.e. check that this is the case, otherwise you’ll overwrite an existing file). For x if a file exists, this function fails (and php returns 0). if ( (fh=fopen("welcome.txt","r")) ) If the fopen() function is unable to open exit("Unable to open file"); the specified file, it returns 0 (false).File Workings fclose() closes a file. feof() determines if the end is true. fgetc() reads a single character fgets() reads a line of data fwrite(), fputs () file() reads entire file into an array writes a string with and without \n php php myFile = "welcome.txt"; myFile = "welcome.txt"; if ((fh=fopen(myFile,'r'))) fh = fopen(myFile, 'r'); exit("Unable to open file."); theData = fgets(fh); while (feof(fh)) fclose(fh); echo theData; x=fgetc(fh); echo x; php fclose(fh); myFile = "testFile.txt"; fh = fopen(myFile, 'a') or die("can't open file"); php stringData = "New Stuff 1\n"; lines = file('welcome.txt'); fwrite(fh, stringData); foreach (lines as lnum = line) stringData = "New Stuff 2\n"; fwrite(fh, stringData); echo "Line lnum:“ fclose(fh); .line.”br/”; Form Handling Any form element is automatically available via one of the builtin PHP variables (provided that element has a “name” defined with it). html form.html body form action="welcome.php" method="POST" Enter your name: input type="text" name="name" / br/ Enter your age: input type="text" name="age" / br/ input type="submit" / input type="reset" / /form /body /html html POST – welcome.php body contains all POST data. Welcome php echo POST"name".”.”; br / GET You are php echo POST"age"; years old contains all GET data. /body /htmlCookie Workings setcookie(name,value,expire,path,domain) creates cookies. php setcookie("uname", POST"name", time()+36000); html body NOTE: p Dear php echo POST"name" , a cookie was set on this setcookie() must appear page The cookie will be active when the client has sent the BEFORE html (or cookie back to the server. /p any output) as it’s part /body /html of the header information sent with the page. html body COOKIE php contains all COOKIE data. if ( isset(COOKIE"uname") ) echo "Welcome " . COOKIE"uname" . "br /"; isset() else echo "You are not logged inbr /"; finds out if a cookie is set /body use the cookie name as a /html variableGetting Time and Date date() and time () formats a time or a date. php //Prints something like: Monday echo date("l"); date() returns a string //Like: Monday 15th of January 2003 05:51:38 AM formatted according to the echo date("l jS \of F Y h:i:s A"); specified format. //Like: Monday the 15th echo date("l \\t\h\e jS"); php nextWeek = time() + (7 24 60 60); // 7 days; 24 hours; 60 mins; 60secs time() returns echo 'Now: '. date('Ymd') ."\n"; current Unix echo 'Next Week: '. date('Ymd', nextWeek) ."\n"; timestamp Required Fields in UserEntered Data A multipurpose script which asks users for some basic contact information and then checks to see that the required fields have been entered. html formchecker.php COMP519 head titlePHP Form example/title /head body php /declare some functions/ Print Function function printform(fname, lname, email, os) form action="formchecker.php" method=“POST" First Name: input type="text" name="fname" value="php echo fname“ / br/ Last Name b/b:input type="text" name="lname" value="php echo lname“ / br/ Email Address b/b:input type="text" name="email" value="php echo email“ / br/ Operating System: input type="text" name="os" value="php echo os“ / br/br/ input type="submit" name="submit" value="Submit“ / input type=“reset“ / /form php // end of “printfrom” functionCheck and Confirm Functions function checkform(fname, lname, email, os) if (lnameemail) echo "h3You are missing some required fields/h3"; printform(fname, lname, email, os); else confirmform(fname, lname, email, os); // end of “checkform” function function confirmform(fname, lname, email, os) h2Thanks Below is the information you have sent to us./h2 h3Contact Info/h3 php echo "Name: fname lname br/"; echo "Email: email br/"; echo "OS: os"; // end of “confirmform” functionMain Program /Main Program/ if (POST"submit") h3Please enter your information/h3 pFields with a "b/b" are required./p php printform("","","",""); else checkform(POST"fname",POST"lname",POST"email",POST"os"); /body /htmlRecommended Texts for Learning PHP • Larry Ullman’s books from the Visual Quickpro series • PHP MySQL for Dummies • Beginning PHP 5 and MySQL: From Novice to Professional by W. Jason Gilmore • (This is more advanced and dense than the others, but great to read once you’ve finished the easier books. One of the best definition/description of object oriented programming I’ve read)PHP References http://www.php.net php home page http://www.phpbuilder.com/ http://www.devshed.com/ http://www.phpmyadmin.net/ http://www.hotscripts.com/PHP/ http://geocities.com/stuprojects/ChatroomDescription.htm http://www.academic.marist.edu/kbhkj/chatroom/chatroom.htm http://www.ausetrade.com/Scripts/php.php http://www.codeproject.com/asp/CDIChatSubmit.asp http://www.php.net/downloads php download page http://www.php.net/manual/en/install.windows.php php installation manual http://php.resourceindex.com/ PHP resources like sample programs, text book references, etc. http://www.daniweb.com/techtalkforums/forum17.html  php forums
Website URL
Comment