PHP INSTALLATION & SAMPLES -BY H. ANKUSH. JAIN. WHAT IS PHP? Hypertext Preprocessor widely used, general-purpose scripting language a server side scripting.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
PHP I.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
PHP Hypertext Preprocessor Information Systems 337 Prof. Harry Plantinga.
XP Browser and Basics1. XP Browser and Basics2 Learn about Web browser software and Web pages The Web is a collection of files that reside.
1 CS428 Web Engineering Lecture 23 MySQL Basics (PHP - VI)
15. User Authentication, Form Validation, Paging. M. Udin Harun Al Rasyid, S.Kom, Ph.D
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Login Screen This is the Sign In page for the Dashboard Enter Id and Password to sign In New User Registration.
Chapter 9 Collecting Data with Forms. A form on a web page consists of form objects such as text boxes or radio buttons into which users type information.
PHP SETUP AND SAMPLE PROGRAMS By, Nikhil v Jain. What's PHP? PHP: Hypertext Preprocessor is a widely used, general-purpose scripting language that was.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
Advance Database Management Systems Lab no. 5 PHP Web Pages.
Web forms in PHP Forms Recap  Way of allowing user interaction  Allows users to input data that can then be processed by a program / stored in a back-end.
Programming with php By: Seth Larson. A little bit about PHP  PHP stands for PHP:  Hypertext Preprocessor  PHP is a widely-used general-purpose server-side.
Application Development Description and exemplification of server-side scripting language for server connection, database selection, execution of SQL queries.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
Website Security ISYS 475. Authentication Authentication is the process that determines the identity of a user.
Class 8Intro to Databases Authentication and Security Note: What we discuss in class today covers moderate to low security. Before you involve yourself.
INTERNET APPLICATION DEVELOPMENT For More visit:
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
Create an online booking system (login/registration)
PHP Hypertext PreProcessor. Documentation Available SAMS books O’Reilly Books.
Getting Started with Moodle Getting Started Logging In Entering Your Address Viewing a Course Navigating Your Course’s Homepage Personalizing Your.
Welcome message. The background image would be an image of Electronic Circuit And have a flash action script to animate 0 and 1. This site would be for.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
XP New Perspectives on Browser and Basics Tutorial 1 1 Browser and Basics Tutorial 1.
Creating a Web Site to Gather Data and Conduct Research.
Python CGI programming
PHP meets MySQL.
1.Getting Started 2.Modifying Design 3.Page 4.News 5.Events 6.Photo Gallery 7.Newsletter Index Training 15 th Mar., 2011.
Installing and Using MySQL and phpMyAdmin. Last Time... Installing Apache server Installing PHP Running basic PHP scripts on the server Not necessary.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and Database.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
Multifarious Project A personal -system Team Members Abdullah Alghamdi Metaib Alenzai Mohammed Alshehri Hamd Alshamsi.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Chapter 6: Authentications. Training Course, CS, NCTU 2 Overview  Getting Username and Password  Verifying Username and Password  Keeping The Verification.
Downloading and Installing Autodesk Revit 2016
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Dynamic web content HTTP and HTML: Berners-Lee’s Basics.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
Downloading and Installing Autodesk Inventor Professional 2015 This is a 4 step process 1.Register with the Autodesk Student Community 2.Downloading the.
Controlling Web Site Access Using Logins CS 320. Basic Approach HTML form a php page that collects the username and password  Sends them to second PHP.
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
PHP Secure Communications Web Technologies Computing Science Thompson Rivers University.
IT ELECTIVE 2.  Web server Can refer to either the hardware (the computer) or the software (the computer application) that helps to deliver content that.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Web Page Design Forms! Website Design. Objectives What forms can do The Attributes of the form tag Using Textboxes Textareas Checkboxes Radio buttons.
Since you’ll need a place for the user to enter a search query. Every form must have these basic components: – The submission type defined with the method.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
1 PHP HTTP After this lecture, you should be able to know: How to create and process web forms with HTML and PHP. How to create and process web forms with.
PHP Form Processing * referenced from
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
1.Switch on the computer and wait for loading. 2.Select the Windows 7 OS at the end of the list. 3.Click on the link ‘Administrator’ 4.Enter the administrator.
1.Switch on the computer and wait for loading. 2.Select the Windows 7 OS at the end of the list. 3.Click on the link ‘Administrator’ 4.Enter the administrator.
How to use Drupal Awdhesh Kumar (Team Leader) Presentation Topic.
2440: 141 Web Site Administration Web Forms Instructor: Joseph Nattey.
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
BASIC PHP and MYSQL Edward S. Flores.
To the ETS – Encumbrance Online Training Course
To the ETS – Encumbrance Online Training Course
PHP By Prof. B.A.Khivsara Note: The material to prepare this presentation has been taken from internet and are generated only for students reference and.
Presentation transcript:

PHP INSTALLATION & SAMPLES -BY H. ANKUSH. JAIN

WHAT IS PHP? Hypertext Preprocessor widely used, general-purpose scripting language a server side scripting language used on the Internet to create dynamic web pages.

INSTALLATION

Install PHP 5 on Windows 1- Download the latest Windows PHP Binaries (MSI file)

2- Right click on the file and click “Install“.

3- Click “Next ” once the Welcome page is displayed.

4- Select “I accept the license agreement” and click “Next “.

5- Change your PHP installation path OR just accept the default path - C:\Program Files\PHP\ and click “Next

6- On the Web Server Setup screen, select the Apache 2.2.x Module and click “Next

7-On the Apache Configuration Directory screen, browse for the Apache configuration directory (conf) OR just enter C:\Program Files\Apache Software Foundation\Apache2.2\conf\ and click “Next ” to proceed with the installation. select-apache-webserver-configuration-directory

8- For now, accept the default selection and click “Next”.

9-Click “Install ” to install PHP 5 on Windows.

10- Click “Finish ” once completed. PHP 5 is successfully installed.

11- Start your Apache 2.2 server using the “Monitor Apache Servers” console (Start - > Apache HTTP Servers > Monitor Apache Servers ). You can see that PHP was successfully installed by checking the Apache status at the bottom of the console.

Test your PHP 5 Installation

1- Open up your Windows Notepad. Type in “ ” inside the file. Save this file as “info.php” inside your Apache root directory, C:\Program Files\Apache Software Foundation\Apache2.2\htdocs.

2- Open up your web browser. In the address bar, type in your web server domain name plus info.php as the file name. Example: You should get a PHP configuration page just like the one below.

Congratulations! You have successfully installed and test PHP 5 on Windows!

PHP SAMPLES

Sample 1: current date in an HTML page Example #1 TDavid's Very First PHP Script ever!

2.current month/day/date format Example #3 TDavid's Very First PHP Script ever!

3. current month/day/date with HTML colors & formatting PHP Script examples!

4. change background color based on day of the week using if else elseif statements Background Colors change based on the day of the week <? $today = date("l"); print("$today"); if($today == "Sunday") { $bgcolor = "#FEF0C5"; }

4. change background color based on day of the week using if else elseif statements elseif($today == "Monday") { $bgcolor = "#FFFFFF"; } elseif($today == "Tuesday") { $bgcolor = "#FBFFC4"; } elseif($today == "Wednesday") { $bgcolor = "#FFE0DD"; } elseif($today == "Thursday"){ $bgcolor = "#E6EDFF";}

4. change background color based on day of the week using if else elseif statements elseif($today == "Friday") { $bgcolor = "#E9FFE6"; } else { // Since it is not any of the days above it must be Saturday $bgcolor = "#F0F4F1"; } print(" \n"); ?> This just changes the color of the screen based on the day of the week

4. change background color based on day of the week using array Background Colors change based on the day of the week <?$today = date("w"); $bgcolor = array( "#FEF0C5", "#FFFFFF", "#FBFFC4", "#FFE0DD", "#E6EDFF", "#E9FFE6", "#F0F4F1" ); ?> "> This just changes the color of the screen based on the day of the week

5. add date time stamp "page last updated on.." using filemtime function using forms, cookies, flat file databases, random number generation Page last updated on month/date/year hour:min PHP Script <? $last_modified = filemtime("example7.php3"); print("Last Modified "); print(date("m/j/y h:i", $last_modified)); ?>

6. setting and retrieving a cookie <? $check = "test"; $check.= $filename; if ($test == $check) {print(" You have already voted. Thank you. "); } else{ $rated = "test"; $rated.= $filename; setcookie(test, $rated, time()+86400); print(" You haven't voted before so I recorded your vote "); } ?>

7. getting an average number using PHP <? $total_ratings = ( ); $total_votes = 7; $average = $total_ratings / $total_votes; print("The Average Rating Is: $average"); ?>

8. showing the surfer average vote statistics, using printf function <? $path = "/YOUR/PATH/TO/public_html/php_diary/data"; $filename = " dat"; $x= -1; if($file = fopen("$path/$filename", "r")) { while(!feof($file)) { $therate = fgetss($file, 255); $x++; $count = $count + $therate; } fclose($file); } $average = ($count / $x); print("Surfer Average Rating for 12/24/99: "); printf("%.2f", $average); print(" Total Surfer Votes: $x"); ?>

9. generating a rand number from 0 to 9 <? srand(time()); $random = (rand()%9); print("Random number between 0 and 9 is: $random"); ?>

10. php simple slot machine - multiple rand number generation <? function slotnumber() { srand(time()); for ($i=0; $i < 3; $i++) { $random = (rand()%3); $slot[] = $random; } print(" $slot[0] "); print(" $slot[1] "); print(" $slot[2] ");

11. php simple slot machine - multiple rand number generation <form method="POST" action="example13.php3">

12. random text link advertising using predefined arrays mail, regular expressions, password protection <? $random_url = array(" " " " " "

random text link advertising using predefined arrays mail, regular expressions, password protection $url_title = array("Link Organizer", "TD Keno", "eziBill *Free Promotion!", "TD Forum", "TD Pic of Day PHP", "Guts or Glory Poker PHP"); $url_desc = array("- A comprehensive link list organizer", "- Offer your site visitors an engaging Keno game without the monetary risk", "- Sell access to and protect your membership area using iBill and our eziBill script", "- An unthreaded messageboard script to exchange ideas with your site visitors", "- Run your own picture of the day script from any site anywhere with this handy script", "- A casino-style card game written entirely in PHP");

random text link advertising using predefined arrays mail, regular expressions, password protection srand(time()); $sizeof = count($random_url); $random = (rand()%$sizeof); print(" $url_title[$r andom] $url_desc[$random] "); ?>

13. forcing the text in a string to be all upper or lowercase <? // force all uppercase print(strtoupper("i bet this will show up as all letters capitalized ")); // force all lowercase print(strtolower("I BET THIS WILL SHOW UP AS ALL LETTERS IN LOWERCASE ")); // force the first letter of a string to be capitalized print(ucfirst("i bet this will show the first letter of the string capitalized ")); // force the first letter of each WORD in a string to be capitalized print(ucwords("i bet this will show the first letter of every word capitalized ")); ?>

14. searching through meta tags for a search engine <? $all_meta = get_meta_tags(" php3"); print($all_meta["description"]); print(" "); print($all_meta["keywords"]); ?>

15. searching through a directory and picking out files using a regular expression <? $diary_directory = opendir("."); while($filename = readdir($diary_directory)) { $filesplit = explode(".", $filename); $check_filename = $filesplit[0]; if(ereg("[0-9]{6}", $check_filename)) { $check_filename.= ".$filesplit[1]"; $valid_filename[] = $check_filename; } closedir($diary_directory); for($index = 0; $index < count($valid_filename); $index++) { print("$valid_filename[$index] "); } ?>

16. shuffling and "cutting" a deck of playing cards <? $cards = array("ah", "ac", "ad", "as", "2h", "2c", "2d", "2s", "3h", "3c", "3d", "3s", "4h", "4c", "4d", "4s", "5h", "5c", "5d", "5s", "6h", "6c", "6d", "6s", "7h", "7c", "7d", "7s", "8h", "8c", "8d", "8s", "9h", "9c", "9d", "9s", "th", "tc", "td", "ts", "jh", "jc", "jd", "js", "qh", "qc", "qd", "qs", "kh", "kc", "kd", "ks");

shuffling and "cutting" a deck of playing cards srand(time()); for($i = 0; $i < 52; $i++) { $count = count($cards); $random = (rand()%$count); if($cards[$random] == "") { $i--; } else { $deck[] = $cards[$random]; $cards[$random] = ""; }

shuffling and "cutting" a deck of playing cards srand(time()); $starting_point = (rand()%51); print("Starting point for cut cards is: $starting_point "); // display shuffled cards (EXAMPLE ONLY) for ($index = 0; $index < 52; $index++) { if ($starting_point == 52) { $starting_point = 0; } print("Uncut Point: $deck[$index] "); print("Starting Point: $deck[$starting_point] "); $starting_point++; } ?>

17. Reader rated most useful diary entries in descending order Reader Rated Most Useful Entries Rank Rating

Reader rated most useful diary entries in descending order Diary Date Description of Diary Page $db = "DATABASE NAME"; $admin = "MYSQL USER NAME"; $adpass = "MYSQL PASSWORD"; $mysql_link = mysql_connect("localhost", $admin, $adpass); mysql_select_db($db, $mysql_link);

Reader rated most useful diary entries in descending order $query = "SELECT * FROM avg_tally ORDER BY average DESC"; $result = mysql_query($query, $mysql_link); if(mysql_num_rows($result)) { $rank = 1; while($row = mysql_fetch_row($result)) { print(" "); if($color == "#D8DBFE") { $color = "#A6ACFD"; } else { $color = "#D8DBFE"; } print(" "); print(" $rank "); print(" "); print(" $row[1] "); print(" "); $url = $row[2]. ".php3";

Reader rated most useful diary entries in descending order if(!file_exists($url)) { $url = $row[2]. ".html"; } print(" $row[2] "); print(" "); print(" $row[3] "); $rank++; }

18. creating a mySQL table using a PHP script <? $mysql_db = "DATABASE NAME"; $mysql_user = "YOUR MYSQL USERNAME"; $mysql_pass = "YOUR MYSQL PASSWORD"; $mysql_link = mysql_connect("localhost", $mysql_user, $mysql_pass); mysql_select_db($mysql_db, $mysql_link); $create_query = "CREATE TABLE tds_counter ( COUNT_ID INT NOT NULL AUTO_INCREMENT, pagepath VARCHAR(250), impressions INT, reset_counter DATETIME, PRIMARY KEY (COUNT_ID) )";

19. creating a mySQL table using a PHP script mysql_query($create_query, $mysql_link); print("Table Creation for tds_counter successful! "); $insert = "INSERT into tds_counter VALUES ( 0, '/php_diary/ php3', 0, SYSDATE() )"; mysql_query($insert, $mysql_link); print("Inserted new counter successfully for this page: "); ?>

20. mySQL based counter script for multiple pagesAutomating manual tasks, date sorting, mktime() <? $db = "DATABASE NAME"; $admin = "MYSQL USER NAME"; $adpass = "MYSQL PASSWORD"; $mysql_link = mysql_connect("localhost", $admin, $adpass); mysql_select_db($db, $mysql_link); $result = mysql_query("SELECT impressions from tds_counter where COUNT_ID='$cid'", $mysql_link); if(mysql_num_rows($result)) { mysql_query("UPDATE tds_counter set impressions=impressions+1 where COUNT_ID='$cid'", $mysql_link); $row = mysql_fetch_row($result); if($inv != 1) { print("$row[0]"); } }?>

21. Classify as Bounce (DSN) or Automated Reply <?php $bounce = new COM("Chilkat.Bounce"); $success = $bounce->UnlockComponent('Anything for 30-day trial'); if ($success == false) { print 'Failed to unlock component'. "\n"; exit; } $ = new COM("Chilkat. ");

21. Classify as Bounce (DSN) or Automated Reply // Load an from a.eml file. // (This example loads an object from a.eml file, // but the object could have been read // directly from a POP3 or IMAP mail server using // Chilkat's POP3 or IMAP implementations.) $success = $ ->LoadEml('sampleBounce.eml'); if ($success == false) { print $ ->lastErrorText(). "\n"; exit; }

21. Classify as Bounce (DSN) or Automated Reply $success = $bounce->Examin ($ ); if ($success == false) { print $bounce->lastErrorText(). "\n"; exit; } if ($bounce->BounceType == 1) { // Hard bounce, log the address print 'Hard Bounce: '. $bounce->bounceAddress(). "\n"; } if ($bounce->BounceType == 2) { // Soft bounce, log the address print 'Soft Bounce: '. $bounce->bounceAddress(). "\n"; }

21. Classify as Bounce (DSN) or Automated Reply if ($bounce->BounceType == 3) { // General bounce, no address available. print 'General Bounce: No address'. "\n"; } if ($bounce->BounceType == 4) { // General bounce, log the address print 'General Bounce: '. $bounce->bounceAddress(). "\n"; } if ($bounce->BounceType == 5) { // Mail blocked, log the address print 'Mail Blocked: '. $bounce->bounceAddress(). "\n"; }

21. Classify as Bounce (DSN) or Automated Reply if ($bounce->BounceType == 6) { // Auto-reply, log the address print 'Auto-Reply: '. $bounce->bounceAddress(). "\n"; } if ($bounce->BounceType == 7) { // Transient (recoverable) Failure, log the address print 'Transient Failure: '. $bounce->bounceAddress(). "\n"; } if ($bounce->BounceType == 8) { // Subscribe request, log the address print 'Subscribe Request: '. $bounce->bounceAddress(). "\n"; } if ($bounce->BounceType == 9) { // Unsubscribe Request, log the address print 'Unsubscribe Request: '. $bounce->bounceAddress(). "\n"; }

21. Classify as Bounce (DSN) or Automated Reply if ($bounce->BounceType == 10) { // Virus Notification, log the address print 'Virus Notification: '. $bounce->bounceAddress(). "\n"; } if ($bounce->BounceType == 11) { // Suspected bounce. // This should be rare. It indicates that the Bounce // component found strong evidence that this is a bounced // , but couldn//t quite recognize everything it // needed to be 100% sure. Feel free to notify // regarding s having this // bounce type. print 'Suspected Bounce!'. "\n";} ?>

22. program to print a message My first PHP Program

23. PHP Array <?php $employee_names[0] = "Dana"; $employee_names[1] = "Matt"; $employee_names[2] = "Susan"; echo "The first employee's name is ".$employee_names[0]; echo " "; echo "The second employee's name is ".$employee_names[1]; echo " "; echo "The third employee's name is ".$employee_names[2]; ?>

24.File Upload Script A File Upload Script <?php if ( isset( $_FILES['fupload'] ) ) { print "name: ". $_FILES['fupload']['name']." "; print "size: ". $_FILES['fupload']['size']." bytes "; print "temp name: ".$_FILES['fupload']['tmp_name']." "; print "type: ". $_FILES['fupload']['type']." "; print "error: ". $_FILES['fupload']['error']." "; if ( $_FILES['fupload']['type'] == "image/gif" ) { $source = $_FILES['fupload']['tmp_name']; $target = "upload/".$_FILES['fupload']['name'];

24.File Upload Script move_uploaded_file( $source, $target );// or die ("Couldn't copy"); $size = getImageSize( $target ); $imgstr = " <img width=\"$size[0]\" height=\"$size[1]\" "; $imgstr.= "src=\"$target\" alt=\"uploaded image\" /> "; print $imgstr; } } ?> <form enctype="multipart/form-data" action=" " method="post">

25.Simple File Upload Form A Simple File Upload Form <form enctype="multipart/form-data" action=" " method="post">

26.Creating an HTML Form That Accepts Mail-Related Information Simple Send Mail Form Mail Form To Subject Message

26.Creating an HTML Form That Accepts Mail-Related Information <!-- Simple .php <?php if (empty ($mailto) ) { die ( "Recipient is blank! ") ; } if (empty ($mailsubject) ){ $mailsubject=" " ; } if (empty ($mailbody) ) { $mailbody=" " ; } $result = mail ($mailto, $mailsubject, $mailbody) ; if ($result) { echo " sent successfully!" ; }else{ echo " could not be sent." ; } ?>

27.React to Form action Contact List Nickname: Full Name:

27.React to Form action Memo: <!-- GetFormValue.php <?php echo " Nickname=$Nickname"; echo " Fullname=$Fullname"; echo " Memo=$Memo"; ?>

28. Build query string based on form input <?php if (isset($_POST['submit'])) { $rowID = $_POST['id']; mysql_connect("mysql153.secureserver.net","java2s","password"); mysql_select_db("java2s"); $query = "SELECT * FROM Employee WHERE ID='$id'"; $result = mysql_query($query); list($name,$productid,$price,$description) = mysql_fetch_row($result); }

28. Build query string based on form input ?> " method="post"> Choose a employee: 1 2 3

29. Checking input from a checkbox or a multiple select <?php $options = array('option 1', 'option 2', 'option 3'); $valid = true; if (is_array($_GET['input'])) { $valid = true; foreach($_GET['input'] as $input) { if (!in_array($input, $options)) { $valid = false; } } if ($valid) { //process input } ?>

30. Validating a single checkbox <?php $value = 'yes'; echo " Subscribe?"; if (isset($_POST['subscribe'])) { if ($_POST['subscribe'] == $value) { $subscribed = true; } else { $subscribed = false;

30. Validating a single checkbox print 'Invalid checkbox value submitted.'; } } else { $subscribed = false; } if ($subscribed) { print 'You are subscribed.'; } else { print 'You are not subscribed'; }

31. Deal with Array Form Data Contact Information Childrens' Names:

31. Deal with Array Form Data

31. Deal with Array Form Data <!-- DealWithArrayFormData.php <?php foreach ($children as $index => $child){ echo " child[$index]=$child"; } echo " "; sort($children); foreach ($children as $index => $child){ echo " child[$index]=$child"; } ?> -->

32. A process_form() Function <?php function process_form($data) { $msg = "The form at {$_SERVER['PHP_SELF']} was submitted with these values: \n\n"; foreach($data as $key=>$val) { $msg.= "$key => $val\n"; } "form submission", $msg); } ?>

33. Access widget's form value would be accessed in PHP as the following: <?php echo $_GET['myform_ ']; ?>

34. Accessing multiple submitted values A B C D E Selected buns: <?php foreach ($_POST['lunch'] as $choice) { print "You want a $choice bun. "; } ?>

35. Forms and PHP //index.htm Your Name: Your

35. Forms and PHP //index.php <? print "Hi, $name!. Your address is $ "; ?>

36. Handling Special Characters <?php if ($_POST['submitted'] == "yes"){ $yourname = $_POST['yourname']; $yourname = trim ($yourname); $yourname = strip_tags ($yourname); $yourname = htmlspecialchars ($yourname); $yourname = addslashes ($yourname); echo $yourname. " "; ?> Try Again <?php }

36. Handling Special Characters if ($_POST['submitted'] != "yes"){ ?> Example: Your Name: <?php } ?>

37. Saying "Hello" <? if (array_key_exists('my_name',$_POST)) { print "Hello, ". $_POST['my_name']; } else { print<<<_HTML_ Your name: _HTML_; } ?>

38. An HTML Form That Calls Itself An HTML Form that Calls Itself <?php if ( ! empty( $_POST['guess'] ) ) { print "last guess: ".$_POST['guess']; }?> "> Type your guess here:

39. Form submitting <?php if (isset($_POST['submit'])){ echo "Hi ".$_POST['name']."! "; echo "The address ".$_POST[' ']." will soon be a spam-magnet! "; } ?> Name: Address:

40. One-script form processing //File: index.php <? $form = " Give us some information! Your Name:

40. One-script form processing Your "; if ($seenform != "y"): print "$form"; else : print "Hi, $name!. Your address is $ "; endif; ?>

41. Preventing Multiple Submissions on the Client Side function checkandsubmit() { document.test.submitbut.disabled = true; document.test.submit(); } Your Name: <input type="text" name="yourname" maxlength="150" />

41. Preventing Multiple Submissions on the Client Side <?php if ($file = fopen ( "test.txt", "w+" )) { fwrite ( $file, "Processing" ); } else { echo "Error opening file."; } echo $_POST ['yourname']; ?>

42. Preventing Multiple Submissions on the Server Side Your Name: <input type="text" name="yourname" maxlength="150" /> <?php session_start (); if (! isset ( $_SESSION ['processing'] )) { $_SESSION ['processing'] = false;}

42. Preventing Multiple Submissions on the Server Side if ($_SESSION ['processing'] == false) { $_SESSION ['processing'] = true; //validation if ($file = fopen ( "test.txt", "w+" )) { fwrite ( $file, "Processing" ); } else { echo "Error opening file."; } echo $_POST ['yourname']; unset ( $_SESSION ['processing'] ); } ?>

43. Authenticate user: Database based <?php function authenticate_user() { header('WWW-Authenticate: Basic realm="Secret Stash"'); header("HTTP/ Unauthorized"); exit; } if (! isset($_SERVER['PHP_AUTH_USER'])) { authenticate_user(); } else { mysql_pconnect("localhost","authenticator","secret") or die("Can't connect to database server!"); mysql_select_db("java2s") or die("Can't select authentication database!");

43. Authenticate user: Database based $query = "SELECT username, pswd FROM user WHERE username='$_SERVER[PHP_AUTH_USER]' AND pswd=MD5('$_SERVER[PHP_AUTH_PW]')"; $result = mysql_query($query); // If nothing was found, reprompt the user for the login information. if (mysql_num_rows($result) == 0) { authenticate_user(); } ?>

44. Prompt Browser password dialog <?php if (($_SERVER['PHP_AUTH_USER'] != 'specialuser') || ($_SERVER['PHP_AUTH_PW'] != 'secretpassword')) { header('WWW-Authenticate: Basic Realm="Secret Stash"'); header('HTTP/ Unauthorized'); print('You must provide the proper credentials!'); exit; } ?>

45. Open browser password dialog and authenticate user based on database <?php function authenticate_user() { header('WWW-Authenticate: Basic realm="Secret Stash"'); header("HTTP/ Unauthorized"); exit; } if(! isset($_SERVER['PHP_AUTH_USER'])) { authenticate_user(); }

45. Open browser password dialog and authenticate user based on database else { mysql_connect("localhost","authenticator","secret") or die("Can't connect to database server!"); mysql_select_db("gilmorebook") or die("Can't select authentication database!"); $query = "SELECT username, pswd FROM user WHERE username='$_SERVER[PHP_AUTH_USER]' AND pswd=MD5('$_SERVER[PHP_AUTH_PW]') AND ipAddress='$_SERVER[REMOTE_ADDR]'"; $result = mysql_query($query); if (mysql_num_rows($result) == 0) authenticate_user(); mysql_close(); }?>

46. Login ID Options Displaying Login ID Options Generating Login IDs for Dave <?php $loginfo = array ( FirstName => "Joe", LastName => "Howrod", Sex => "Male", Location => "Arizona", Age => "24", MusicChoice => "Pop", Hobby => "Dance", Occupation => "Author"); echo " The information entered by JOe: "; foreach ($loginfo as $key => $val) { echo " $key => $val "; }

46. Login ID Options echo " "; echo " The login options are: "; $loginone = array_slice ($loginfo, 0, 2); $logintwo = array_slice ($loginfo, 3, 2); $loginthree = array_slice ($loginfo, 5, 2); $loginfour = array_slice ($loginfo, 6, 2); $loginfive = array_merge ($loginfour, "2001"); echo "The first login option: "; foreach ($loginone as $optionone) { echo " $optionone "; } echo " "; echo "The second login option: "; foreach ($loginone as $optiontwo) { echo " $optiontwo "; } echo " ";

46. Login ID Optionsn echo "The third login option: "; foreach ($loginthree as $optionthree) { echo " $optionthree "; } echo " "; echo "The fourth login option: "; foreach ($loginfour as $optionfour) { echo " $optionfour "; } echo " "; echo "The fifth login option: "; foreach ($loginfive as $optionfive) { echo " $optionfive "; } echo " "; ?>

47. Get uniqid <? $id = uniqid("phpuser"); echo "$id"; ?>

48. Use md5 function to encrypt text <?php $val = "secret"; echo "Pre-hash string: $val "; $hash_val = md5 ($val); echo "Hashed outcome: $hash_val"; ?>

49. md5 and uniqid <? $id = md5(uniqid(rand())); echo "$id"; ?>

50. A user registration process create table user_info ( user_id char(18), fname char(15), char(35)); //File: index.php <? $form = " Your first name?: Your ?: ";

50. A user registration process if ((! isset ($seenform)) && (! isset ($userid))) : print $form; elseif (isset ($seenform) && (! isset ($userid))) : $uniq_id = "root", "") or die("Could not connect to MySQL or die("Could not select user database!"); $query = "INSERT INTO user_info VALUES('$uniq_id', '$fname', '$ ')"; $result = mysql_query($query) or die("Could not insert user information!"); setcookie ("userid", $uniq_id, time() ); print "Congratulations $fname! You are now registered!.";

50. A user registration process elseif (isset($userid)) "root", "") or die("Could not connect to MySQL or die("Could not select user database!"); $query = "SELECT * FROM user_info WHERE user_id = '$userid'"; $result = mysql_query($query) or die("Could not extract user information!"); $row = mysql_fetch_array($result); print "Hi ".$row["fname"].", "; print "Your address is ".$row[" "]; endif; ?>

THANK YOU