114
-By V.Gouthaman

-By V.Gouthaman

  • Upload
    malha

  • View
    16

  • Download
    0

Embed Size (px)

DESCRIPTION

-By V.Gouthaman. INTRODUCTION. - PowerPoint PPT Presentation

Citation preview

Page 1: -By V.Gouthaman

-ByV.Gouthaman

Page 2: -By V.Gouthaman

INTRODUCTION

PHP: Hypertext Preprocessor is a widely used, general-purpose scripting language that was originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document. As a general-purpose programming language, PHP code is processed by an interpreter application in command-line mode performing desired operating system operations and producing program output on its standard output channel.

Page 3: -By V.Gouthaman

It may also function as a graphical application. PHP is available as a processor for most modern web servers and as standalone interpreter on most operating systems and computing platforms.

PHP was originally created by Rasmus Lerdorf in 1995 and has been in continuous development ever

since. The main implementation of PHP is now produced by The PHP Group and serves as the de

facto standard for PHP as there is no formal specification. PHP is free software released under

the PHP License.

Page 4: -By V.Gouthaman

INSTALLATIONAND

CONFIGURATION

Page 5: -By V.Gouthaman

Step 1: Download the latest Windows PHP Binaries (MSI file) from “http://www.php.net/get/php-5.2.4-win32-installer.msi/from/a/mirror” . I choose the eZNetworking mirror because it is the closest one to Malaysia. Choose a mirror that is nearer to your country for a faster file download. The latest PHP version that I downloaded is 5.2.4. Save the file to your Desktop.

Step 2: Right click on the file and click “Install“.

Page 6: -By V.Gouthaman

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

Page 7: -By V.Gouthaman

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

Page 8: -By V.Gouthaman

Step 5: Change your PHP installation path OR just accept the default path - C:\Program

Files\PHP\ and click “Next “.

Page 9: -By V.Gouthaman

Step 6: On the Web Server Setup screen, select the Apache 2.2.x Module and click

“Next “.

select-webserver-to-install-php-on-apache-2

Page 10: -By V.Gouthaman

Step 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.

Page 11: -By V.Gouthaman

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

Page 12: -By V.Gouthaman

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

Page 13: -By V.Gouthaman

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

Page 14: -By V.Gouthaman

Step 11: Start your Apache 2.2 server using the “Monitor Apache Servers” console (Start -> Apache

HTTP Servers 2.2.4 -> Monitor Apache Servers ). You can see that PHP was successfully installed by checking the Apache status at the bottom of the

console.

Page 15: -By V.Gouthaman

Testing PHP 5 Installation

Step 1: Open up your Windows Notepad. Type in “<?php phpinfo(); ?>” inside the file. Save this file as

“info.php” inside your Apache root directory, C:\Program Files\Apache Software Foundation\

Apache2.2\htdocs .

Page 16: -By V.Gouthaman

Step 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: http://www.syahid.com/info.php . You

should get a PHP configuration page just like the one below.

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

Page 17: -By V.Gouthaman

CONFIGURATION

Page 18: -By V.Gouthaman

Configure PHP 5 to Work with MySQL with MySQL PHP Extension

Previously, we have installed PHP with minimal modules / extension. To add MySQL support to PHP, you need to change your PHP installation - by adding the MySQL extension on top of your PHP installation. Please make sure that your original PHP 5 MSI installer still remains at its original place .

Page 19: -By V.Gouthaman

Step 1: Open the Add / Remove Programs console via Windows Control Panel. Find the PHP 5.x.x entry and click “Change “.

Page 20: -By V.Gouthaman

Step 2: Click “Next ” once you are prompted the Welcome page.

Page 21: -By V.Gouthaman

Step 3: Click the “Change ” button to proceed.

Page 22: -By V.Gouthaman

Step 4: Select Apache 2.2.x as shown in the picture below. Click “Next ” once again.

Page 23: -By V.Gouthaman

Step 5: Select your Apache configuration directory (conf) - the directory where your httpd.conf resides.

Click “Next ” once done.

Page 24: -By V.Gouthaman
Page 25: -By V.Gouthaman

Step 6: On the “Choose items to install” screen, click on the plus (+) icon next to Extensions to expand the list.

click-plus-button-to-expand-extensions-part

Page 26: -By V.Gouthaman
Page 27: -By V.Gouthaman

Step 7: Select on the “X” next to “MySQL” and select “Entire feature will be installed on local hard drive”. Click “Next” again

Page 28: -By V.Gouthaman

Step 8: Click the “Change” button to save all the PHP configuration changes.

Page 29: -By V.Gouthaman

Step 9: Finally, restart your Apache 2.2 web server! You can check out that the MySQL extension support for PHP was successfully installed by checking out the info.php / index.php page that was created before.

Page 30: -By V.Gouthaman

PHP SAMPLE PROGRAMS

Page 31: -By V.Gouthaman

Sample 1: current date in an HTML page

<html><head>

<title>Example #1 TDavid's Very First PHP Script ever!</title>

</head><? print(Date("l F d, Y")); ?>

<body></body></html>

Page 32: -By V.Gouthaman

2.current month/day/date format

<html><head>

<title>Example #3 TDavid's Very First PHP Script ever!</title>

</head><? print(Date("m/j/y")); ?>

<body></body></html>

Page 33: -By V.Gouthaman

3. current month/day/date with HTML colors & formatting

<html><head>

<title>PHP Script examples!</title></head>

<font face="Arial" color="#FF00FF"><strong><? print(Date("m/j/y")); ?>

</strong></font><body></body></html>

Page 34: -By V.Gouthaman

4. change background color based on day of the week using if else elseif

statements

<html><head>

<title>Background Colors change based on the day of the week</title>

</head><?

$today = date("l");print("$today");

if($today == "Sunday"){

$bgcolor = "#FEF0C5";}

Page 35: -By V.Gouthaman

elseif($today == "Monday"){

$bgcolor = "#FFFFFF";}

elseif($today == "Tuesday"){

$bgcolor = "#FBFFC4";}

elseif($today == "Wednesday"){

$bgcolor = "#FFE0DD";}

elseif($today == "Thursday"){$bgcolor = "#E6EDFF";}

Page 36: -By V.Gouthaman

elseif($today == "Friday"){

$bgcolor = "#E9FFE6";}

else{

// Since it is not any of the days above it must be Saturday$bgcolor = "#F0F4F1";

}print("<body bgcolor=\"$bgcolor\">\n");

?><br>This just changes the color of the screen based on the day of the

week</body></html>

Page 37: -By V.Gouthaman

<html><head>

<title>Background Colors change based on the day of the week</title></head><?$today = date("w");

$bgcolor = array("#FEF0C5", "#FFFFFF", "#FBFFC4", "#FFE0DD",

"#E6EDFF", "#E9FFE6", "#F0F4F1");

?><body bgcolor="<?print("$bgcolor[$today]");?>">

<br>This just changes the color of the screen based on the day of the week

</body></html>

Page 38: -By V.Gouthaman

5. Add date time stamp "page last updated on.." using filemtime function using forms, cookies, flat file databases, random number generation

<html><head>

<title>Page last updated on month/date/year hour:min PHP Script</title>

</head><?

$last_modified = filemtime("example7.php3");print("Last Modified ");

print(date("m/j/y h:i", $last_modified));?>

</body></html>

Page 39: -By V.Gouthaman

6. Setting and retrieving a cookie

<?$check = "test";

$check .= $filename;if ($test == $check)

{print("<HTML><BODY>You have already voted. Thank you.</BODY></HTML>");

}else{

$rated = "test";$rated .= $filename;

setcookie(test, $rated, time()+86400);print("<HTML><BODY><br>You haven't voted before so I

recorded your vote</BODY></HTML>");}

?>

Page 40: -By V.Gouthaman

7. Getting an average number using PHP

<?$total_ratings = (3+2+3+1+5+2+3);

$total_votes = 7;$average = $total_ratings / $total_votes;print("The Average Rating Is: $average");

?>

Page 41: -By V.Gouthaman

8. showing the surfer average vote statistics, using printf function

<?$path = "/YOUR/PATH/TO/public_html/php_diary/data";

$filename = "122499.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("<br>Total Surfer Votes: $x");

?>

Page 42: -By V.Gouthaman

9. Generating a random number from 0 to 9

<?srand(time());

$random = (rand()%9);print("Random number between 0 and 9 is: $random");

?>

Page 43: -By V.Gouthaman

10. php simple slot machine - multiple random number generation

<?function slotnumber()

{srand(time());

for ($i=0; $i < 3; $i++){

$random = (rand()%3);$slot[] = $random;

}print("<td width=\"33%\"><center>$slot[0]</td>");print("<td width=\"33%\"><center>$slot[1]</td>");print("<td width=\"33%\"><center>$slot[2]</td>");

</tr>

Page 44: -By V.Gouthaman

11. php simple slot machine - multiple random number generation

<tr> <td width="100%" colspan="3"

bgcolor="#008080"><form method="POST" action="example13.php3"><div

align="center"><center><p><input type="submit" value="Spin!"></p> </center></div>

</form> </td> </tr>

</table></center></div>

Page 45: -By V.Gouthaman

12. random text link advertising using predefined arrays

mail, regular expressions, password protection

<?$random_url =

array("http://www.tdscripts.com/linkorg.html", "http://www.tdscripts.com/keno.html",

"http://www.tdscripts.com/ezibill.shtml", "http://www.tdscripts.com/tdforum.shtml", "http://www.tdscripts.com/picofday.html",

"http://www.tdscripts.com/gutsorglory.html");

Page 46: -By V.Gouthaman

$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");

Page 47: -By V.Gouthaman

srand(time());$sizeof = count($random_url);$random = (rand()%$sizeof);

print("<center><a href=\"$random_url[$random]\">$url_title[$rando

m]</a> $url_desc[$random]</center>");?>

Page 48: -By V.Gouthaman

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<br>"));

// force all lowercaseprint(strtolower("I BET THIS WILL SHOW UP AS ALL LETTERS IN

LOWERCASE<br>"));// force the first letter of a string to be capitalized

print(ucfirst("i bet this will show the first letter of the string capitalized<br>"));

// force the first letter of each WORD in a string to be capitalizedprint(ucwords("i bet this will show the first letter of every word

capitalized<br>"));?>

Page 49: -By V.Gouthaman

14. searching through meta tags for a search engine

<HTML><BODY>

<?$all_meta = get_meta_tags("010600.php3");

print($all_meta["description"]);print("<br>");

print($all_meta["keywords"]);?>

</BODY></HTML>

Page 50: -By V.Gouthaman

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]<br>");

}?>

Page 51: -By V.Gouthaman

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");

Page 52: -By V.Gouthaman

srand(time()); for($i = 0; $i < 52; $i++)

{ $count = count($cards);

$random = (rand()%$count); if($cards[$random] == "")

{ $i--;

} else

{ $deck[] = $cards[$random];

$cards[$random] = ""; }

}

Page 53: -By V.Gouthaman

srand(time());$starting_point = (rand()%51);

print("Starting point for cut cards is: $starting_point<p>");

// display shuffled cards (EXAMPLE ONLY) for ($index = 0; $index < 52; $index++)

{ if ($starting_point == 52) { $starting_point = 0; }

print("Uncut Point: <strong>$deck[$index]</strong> "); print("Starting Point:

<strong>$deck[$starting_point]</strong><br>"); $starting_point++;

}?>

Page 54: -By V.Gouthaman

17. Reader rated most useful diary entries in descending order

<HTML><HEAD>

<title>Reader Rated Most Useful Entries</title></HEAD><BODY>

<table border="0" width="100%"><tr>

<td width="6%" bgcolor="#00FFFF"><p align="center"><small><font

face="Verdana">Rank</font></small></td><td width="7%" bgcolor="#00FFFF"><p

align="center"><small><font face="Verdana">Rating</font></small></td>

Page 55: -By V.Gouthaman

<td width="11%" bgcolor="#00FFFF"><p align="center"><small><font

face="Verdana">Diary Date</font></small></td><td width="76%" bgcolor="#00FFFF"><p

align="left"><small><font face="Verdana">Description

of Diary Page</font></small></td>

<script language="php">$db = "DATABASE NAME";

$admin = "MYSQL USER NAME";$adpass = "MYSQL PASSWORD";

$mysql_link = mysql_connect("localhost", $admin, $adpass);

mysql_select_db($db, $mysql_link);

Page 56: -By V.Gouthaman

$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("</tr><tr>"); if($color == "#D8DBFE") {

$color = "#A6ACFD"; } else {

$color = "#D8DBFE"; }

print("<td width=\"6%\" bgcolor=\"$color\"><center><small>"); print("<font face=\"Verdana\">$rank</font></small></center></td>");

print("<td width=\"7%\" bgcolor=\"$color\"><center><small>"); print("<font

face=\"Verdana\"><strong>$row[1]</strong></font></small></center></td>");

print("<td width=\"11%\" bgcolor=\"$color\"><center><small>"); $url = $row[2] . ".php3";

Page 57: -By V.Gouthaman

if(!file_exists($url)) { $url = $row[2] . ".html"; } print("<font face=\"Verdana\"><a

href=\"$url\">$row[2]</a></font></small></center></td>");

print("<td width=\"76%\" bgcolor=\"$color\"><left><small>");

print("<font face=\"Verdana\">$row[3]</font></small></left></t

d>"); $rank++;

}}

</script></table></BODY></HTML>

Page 58: -By V.Gouthaman

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) )";

Page 59: -By V.Gouthaman

19. creating a mySQL table using a PHP script

mysql_query($create_query, $mysql_link);print("Table Creation for <b>tds_counter</b> successful!

<p>");

$insert = "INSERT into tds_counter VALUES ( 0, '/php_diary/021901.php3', 0, SYSDATE()

)";

mysql_query($insert, $mysql_link);print("Inserted new counter successfully for this page:

http://www.php-scripts.com/php_diary/021901.php3<p>");

?>

Page 60: -By V.Gouthaman

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]"); }

}?>

Page 61: -By V.Gouthaman

21. Classify Email 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;}

$email = new COM("Chilkat.Email");

Page 62: -By V.Gouthaman

// Load an email from a .eml file.// (This example loads an Email 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 = $email-

>LoadEml('sampleBounce.eml');if ($success == false) {

print $email->lastErrorText() . "\n"; exit;

}

Page 63: -By V.Gouthaman

$success = $bounce->ExamineMail($email);if ($success == false) {

print $bounce->lastErrorText() . "\n"; exit;

}if ($bounce->BounceType == 1) {

// Hard bounce, log the email address print 'Hard Bounce: ' . $bounce-

>bounceAddress() . "\n";}

if ($bounce->BounceType == 2) { // Soft bounce, log the email address

print 'Soft Bounce: ' . $bounce->bounceAddress() . "\n";

}

Page 64: -By V.Gouthaman

if ($bounce->BounceType == 3) { // General bounce, no email address

available. print 'General Bounce: No email address' . "\

n";}

if ($bounce->BounceType == 4) { // General bounce, log the email address

print 'General Bounce: ' . $bounce->bounceAddress() . "\n";

}if ($bounce->BounceType == 5) {

// Mail blocked, log the email address print 'Mail Blocked: ' . $bounce-

>bounceAddress() . "\n";}

Page 65: -By V.Gouthaman

if ($bounce->BounceType == 6) { // Auto-reply, log the email address

print 'Auto-Reply: ' . $bounce->bounceAddress() . "\n";}

if ($bounce->BounceType == 7) { // Transient (recoverable) Failure, log the email address

print 'Transient Failure: ' . $bounce->bounceAddress() . "\n";}

if ($bounce->BounceType == 8) { // Subscribe request, log the email address

print 'Subscribe Request: ' . $bounce->bounceAddress() . "\n";

}if ($bounce->BounceType == 9) {

// Unsubscribe Request, log the email address print 'Unsubscribe Request: ' . $bounce->bounceAddress()

. "\n";}

Page 66: -By V.Gouthaman

if ($bounce->BounceType == 10) { // Virus Notification, log the email 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 // email, but couldn//t quite recognize everything it

// needed to be 100% sure. Feel free to notify // [email protected] regarding emails having this

// bounce type. print 'Suspected Bounce!' . "\n";}

?>

Page 67: -By V.Gouthaman

22. Program to print a message

<html><h3>My first PHP Program</h3>

<? echo "Hello world!"; ?></html>

Page 68: -By V.Gouthaman

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 "<br>";echo "The second employee's name is ".

$employee_names[1];echo "<br>";

echo "The third employee's name is ".$employee_names[2];

?>

Page 69: -By V.Gouthaman

24.File Upload Script<html> <head>

<title>A File Upload Script</title> </head> <body> <div> <?php

if ( isset( $_FILES['fupload'] ) ) { print "name: ". $_FILES['fupload']['name'] ."<br />"; print "size: ". $_FILES['fupload']['size'] ." bytes<br />";

print "temp name: ".$_FILES['fupload']['tmp_name'] ."<br />"; print "type: ". $_FILES['fupload']['type'] ."<br />"; print "error: ". $_FILES['fupload']['error'] ."<br />";

if ( $_FILES['fupload']['type'] == "image/gif" ) { $source = $_FILES['fupload']['tmp_name'];

$target = "upload/".$_FILES['fupload']['name'];

Page 70: -By V.Gouthaman

move_uploaded_file( $source, $target );// or die ("Couldn't copy");

$size = getImageSize( $target ); $imgstr = "<p><img width=\"$size[0]\" height=\"$size[1]\"

"; $imgstr .= "src=\"$target\" alt=\"uploaded image\" /></p>";

print $imgstr; } } ?> </div>

<form enctype="multipart/form-data" action="<?php print $_SERVER['PHP_SELF']?>"

method="post"> <p>

<input type="hidden" name="MAX_FILE_SIZE" value="102400" />

<input type="file" name="fupload" /><br/> <input type="submit" value="upload!" />

</p> </form> </body> </html>

Page 71: -By V.Gouthaman

25.Simple File Upload Form<html><head>

<title>A Simple File Upload Form</title></head><body>

<form enctype="multipart/form-data" action="<?print $_SERVER['PHP_SELF']?>" method="post">

<p><input type="hidden" name="MAX_FILE_SIZE"

value="102400" /><input type="file" name="fupload" /><br/><input type="submit" value="upload!" />

</p></form></body></html>

Page 72: -By V.Gouthaman

26.Creating an HTML Form That Accepts Mail-Related Information

<html> <head>

<title>Simple Send Mail Form</title> </head><body>

<h1>Mail Form</h1> <form name="form1" method="post" action="SimpleEmail.php">

<table> <tr><td><b>To</b></td><td><input type="text" name="mailto"

size="35"></td></tr> <tr><td><b>Subject</b></td>

<td><input type="text" name="mailsubject" size="35"></td></tr> <tr><td><b>Message</b></td>

<td><textarea name="mailbody" cols="50" rows="7"></textarea></td> </tr>

<tr><td colspan="2"> <input type="submit" name="Submit" value="Send">

</td></tr></table></form></body> </html>

Page 73: -By V.Gouthaman

<!-- SimpleEmail.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 "Email sent successfully!" ;

}else{ echo "Email could not be sent." ;

} ?>

Page 74: -By V.Gouthaman

27.React to Form action

<HTML><BODY>

<FORM METHOD="POST" ACTION="GetFormValue.php"> <H2>Contact List</H2>

<BR>Nickname: <BR><INPUT TYPE="TEXT" NAME="Nickname">

<BR> <BR>Full Name:

<BR><INPUT TYPE="TEXT" NAME="Fullname">

Page 75: -By V.Gouthaman

<BR> <BR>Memo: <BR><TEXTAREA NAME="Memo" ROWS="4" COLS="40"

WRAP="PHYSICAL"> </TEXTAREA> <BR> <BR>

<INPUT TYPE="SUBMIT"></FORM></BODY>

<!-- GetFormValue.php<?php

echo "<BR>Nickname=$Nickname"; echo "<BR>Fullname=$Fullname";

echo "<BR>Memo=$Memo";?>

Page 76: -By V.Gouthaman

28. Build query string based on form input

<?phpif (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);}

Page 77: -By V.Gouthaman

?><form action="<?php echo $_SERVER['PHP_SELF']; ?>"

method="post"> <select name="id">

<option name="">Choose a employee:</option> <option name="1">1</option> <option name="2">2</option> <option name="3">3</option>

</select> <input type="submit" name="submit" value="Submit" />

</form>

Page 78: -By V.Gouthaman

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

}}

?>

Page 79: -By V.Gouthaman

30. Validating a single checkbox

<?php$value = 'yes';

echo "<input type='checkbox' name='subscribe' value='yes'/> Subscribe?";

if (isset($_POST['subscribe'])) { if ($_POST['subscribe'] == $value) {

$subscribed = true; } else {

$subscribed = false;

Page 80: -By V.Gouthaman

print 'Invalid checkbox value submitted.'; }

} else { $subscribed = false;

}if ($subscribed) {

print 'You are subscribed.';} else {

print 'You are not subscribed';}

Page 81: -By V.Gouthaman

31. Deal with Array Form Data

<HTML> <BODY><FORM METHOD="POST" ACTION="DealWithArrayFormData.php">

<H1>Contact Information</H1><TABLE><TR>

<TD>Childrens' Names:</TD></TR><TR>

<TD><INPUT TYPE="TEXT" NAME="children[]"></TD></TR><TR>

<TD><INPUT TYPE="TEXT" NAME="children[]"></TD></TR><TR>

<TD><INPUT TYPE="TEXT" NAME="children[]"></TD></TR>

Page 82: -By V.Gouthaman

<TR> <TD><INPUT TYPE="TEXT" NAME="children[]"></TD>

</TR><TR>

<TD><INPUT TYPE="TEXT" NAME="children[]"></TD></TR>

</TABLE><BR><BR><BR>

<INPUT TYPE="SUBMIT" VALUE="Submit"><BR><BR>

<INPUT TYPE="RESET" VALUE="Clear the Form"></FORM></BODY></HTML>

Page 83: -By V.Gouthaman

<!-- DealWithArrayFormData.php

<?phpforeach ($children as $index => $child){

echo "<BR>child[$index]=$child";}

echo "<BR>";sort($children);

foreach ($children as $index => $child){ echo "<BR>child[$index]=$child";

}?>-->

Page 84: -By V.Gouthaman

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";

} mail("[email protected]", "form submission",

$msg);

}?>

Page 85: -By V.Gouthaman

33. Access widget's form value

<INPUT TYPE="text" NAME="myform.email">

would be accessed in PHP as the following:

<?php echo $_GET['myform_email'];

?>

Page 86: -By V.Gouthaman

34. Accessing multiple submitted values

<form method="POST" action="index.php"><select name="lunch[]" multiple>

<option value="a">A</option><option value="b">B</option><option value="c">C</option><option value="d">D</option><option value="e">E</option>

</select><input type="submit" name="submit">

</form>Selected buns:<br/><?php

foreach ($_POST['lunch'] as $choice) { print "You want a $choice bun. <br/>";

}?>

Page 87: -By V.Gouthaman

35. Forms and PHP

//index.htm<html><body>

<form action="index.php" method="post">Your Name:<br>

<input type="text" name="name" size="20" maxlength="20" value=""><br>

Your Email:<br><input type="text" name="email" size="20"

maxlength="40" value=""><br><input type="submit" value="go!">

</form></body></html>

Page 88: -By V.Gouthaman

//index.php<html><head>

<title></title></head><body>

<? print "Hi, $name!. Your email address is $email";

?></body></html>

Page 89: -By V.Gouthaman

36. Handling Special Characters

<html><body> <?php

if ($_POST['submitted'] == "yes"){ $yourname = $_POST['yourname'];

$yourname = trim ($yourname); $yourname = strip_tags ($yourname);

$yourname = htmlspecialchars ($yourname); $yourname = addslashes ($yourname);

echo $yourname . "<br />"; ?><a href="index.php">Try Again</a><?php

}

Page 90: -By V.Gouthaman

if ($_POST['submitted'] != "yes"){ ?>

<form action="index.php" method="post"> <p>Example:</p>

<input type="hidden" name="submitted" value="yes" />

Your Name: <input type="text" name="yourname" maxlength="150" /><br />

<input type="submit" value="Submit" style="margin-top: 10px;" />

</form> <?php

} ?>

</div></body></html>

Page 91: -By V.Gouthaman

37. Saying "Hello"

<?if (array_key_exists('my_name',$_POST)) {

print "Hello, ". $_POST['my_name'];} else {

print<<<_HTML_<form method="post" action="$_SERVER[PHP_SELF]"> Your name: <input type="text" name="my_name">

<br/><input type="submit" value="Say Hello">

</form>_HTML_;

}?>

Page 92: -By V.Gouthaman

38. An HTML Form That Calls Itself<html><head>

<title>An HTML Form that Calls Itself</title></head><body>

<div><?php

if ( ! empty( $_POST['guess'] ) ) { print "last guess: ".$_POST['guess'];

}?><form method="post" action="<?php print

$_SERVER['PHP_SELF']?>"><p>

Type your guess here: <input type="text" name="guess" /></p></form></div>

</body></html>

Page 93: -By V.Gouthaman

39. Form submitting

<?php if (isset($_POST['submit'])){

echo "Hi ".$_POST['name']."!<br />"; echo "The address ".$_POST['email']." will soon be a

spam-magnet!<br />"; }?>

<form action="index.php" method="post">Name:<input type="text" name="name" size="20"

maxlength="40" value="" />Email Address:

<input type="text" name="email" size="20" maxlength="40" value="" />

<input type="submit" name = "submit" value="Go!" /></form>

Page 94: -By V.Gouthaman

40. One-script form processing

//File: index.php<html><head>

<title></title></head><body>

<?$form = "<form action=\"index.php\" method=\"post\"><input type=\"hidden\" name=\"seenform\" value=\"y\">

<b>Give us some information!</b><br>Your Name:<br>

<input type=\"text\" name=\"name\" size=\"20\" maxlength=\"20\" value=\"\"><br>

Page 95: -By V.Gouthaman

Your Email:<br><input type=\"text\" name=\"email\" size=\"20\"

maxlength=\"40\" value=\"\"><br><input type=\"submit\" value=\"subscribe!\">

</form>";if ($seenform != "y"):

print "$form";else :

print "Hi, $name!. Your email address is $email";endif;

?></body></html>

Page 96: -By V.Gouthaman

41. Preventing Multiple Submissions on the Client Side

<html><script language="javascript" type="text/javascript">

function checkandsubmit() { document.test.submitbut.disabled = true;

document.test.submit(); }

</script><body>

<form action="index.php" method="post" name="test" onsubmit="return checkandsubmit ()">

<input type="hidden" name="submitted" value="yes" /> Your Name: <input

type="text" name="yourname" maxlength="150" />

Page 97: -By V.Gouthaman

<input type="submit" value="Submit" id="submitbut" name"submitbut" /></form>

</body></html><?php

if ($file = fopen ( "test.txt", "w+" )) { fwrite ( $file, "Processing" );

} else { echo "Error opening file.";

}echo $_POST ['yourname'];

?>

Page 98: -By V.Gouthaman

42. Preventing Multiple Submissions on the Server Side

<html><body>

<form action="index.php" method="post"><input type="hidden" name="submitted" value="yes" />

Your Name: <input type="text" name="yourname" maxlength="150" /><br />

<input type="submit" value="Submit" style="margin-top: 10px;" /></form>

</body></html><?php

session_start ();if (! isset ( $_SESSION ['processing'] )) {

$_SESSION ['processing'] = false;}

Page 99: -By V.Gouthaman

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'] );

}?>

Page 100: -By V.Gouthaman

43. Authenticate user: Database based

<?php function authenticate_user() {

header('WWW-Authenticate: Basic realm="Secret Stash"');

header("HTTP/1.0 401 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!");

Page 101: -By V.Gouthaman

$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();

} }?>

Page 102: -By V.Gouthaman

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/1.0 401 Unauthorized'); print('You must provide the proper credentials!');

exit; }?>

Page 103: -By V.Gouthaman

45. Open browser password dialog and authenticate user based on database

<?php function authenticate_user() {

header('WWW-Authenticate: Basic realm="Secret Stash"');

header("HTTP/1.0 401 Unauthorized"); exit;

} if(! isset($_SERVER['PHP_AUTH_USER'])) {

authenticate_user(); }

Page 104: -By V.Gouthaman

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();

}?>

Page 105: -By V.Gouthaman

46. Login ID Options<HTML>

<HEAD> <TITLE>Displaying Login ID Options</TITLE>

</HEAD> <BODY> <Hl><CENTER>Generating Login IDs for Dave</CENTER></Hl>

<?php $loginfo = array ( FirstName => "Joe",

LastName => "Howrod", Sex => "Male",

Location => "Arizona", Age => "24",

MusicChoice => "Pop", Hobby => "Dance",

Occupation => "Author"); echo "<H3>The information entered by JOe:<BR></H3>";

foreach ($loginfo as $key => $val) { echo "<B>$key</B> => $val<BR>"; }

Page 106: -By V.Gouthaman

echo "<BR> "; echo "<H3>The login options are:<BR></H3>";

$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:<BR>"; foreach ($loginone as $optionone) {

echo "<B>$optionone</B>"; } echo "<BR>";

echo "The second login option:<BR>"; foreach ($loginone as $optiontwo) {

echo "<B>$optiontwo</B>"; } echo "<BR>";

Page 107: -By V.Gouthaman

echo "The third login option:<BR>"; foreach ($loginthree as $optionthree) {

echo "<B>$optionthree</B>"; } echo "<BR>";

echo "The fourth login option:<BR>"; foreach ($loginfour as $optionfour) {

echo "<B>$optionfour</B>"; } echo "<BR>";

echo "The fifth login option:<BR>"; foreach ($loginfive as $optionfive) {

echo "<B>$optionfive</B>"; }

echo "<BR>"; ?> </BODY> </HTML>

Page 108: -By V.Gouthaman

47. Get uniqid

<?$id = uniqid("phpuser");

echo "$id";

?>

Page 109: -By V.Gouthaman

48. Use md5 function to encrypt text

<?php $val = "secret";

echo "Pre-hash string: $val <br />"; $hash_val = md5 ($val);

echo "Hashed outcome: $hash_val";?>

Page 110: -By V.Gouthaman

49. md5 and uniqid

<?$id = md5(uniqid(rand()));

echo "$id";

?>

Page 111: -By V.Gouthaman

50. A user registration process

create table user_info (user_id char(18),fname char(15),email char(35));//File: index.php

<? $form = "<form action=\"index.php\" method=\"post\">

<input type=\"hidden\" name=\"seenform\" value=\"y\">Your first name?:<br>

<input type=\"text\" name=\"fname\" value=\"\"><br>Your email?:<br>

<input type=\"text\" name=\"email\" value=\"\"><br><input type=\"submit\" value=\"Register!\">

</form> ";

Page 112: -By V.Gouthaman

if ((! isset ($seenform)) && (! isset ($userid))) : print $form;

elseif (isset ($seenform) && (! isset ($userid))) : $uniq_id = uniqid(rand());

@mysql_pconnect("localhost", "root", "") or die("Could not connect to MySQL server!");

@mysql_select_db("user") or die("Could not select user database!");

$query = "INSERT INTO user_info VALUES('$uniq_id', '$fname', '$email')";

$result = mysql_query($query) or die("Could not insert user information!");

setcookie ("userid", $uniq_id, time()+2592000);

print "Congratulations $fname! You are now registered!.";

Page 113: -By V.Gouthaman

elseif (isset($userid)) : @mysql_pconnect("localhost", "root", "") or die("Could not

connect to MySQL server!"); @mysql_select_db("user") 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"].",<br>";

print "Your email address is ".$row["email"];endif;

?>

Page 114: -By V.Gouthaman