1 / 93

PHP SETUP AND SAMPLE PROGRAMS By, Nikhil v Jain

PHP SETUP AND SAMPLE PROGRAMS By, Nikhil v Jain.

chin
Download Presentation

PHP SETUP AND SAMPLE PROGRAMS By, Nikhil v Jain

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP SETUP AND SAMPLE PROGRAMS By, Nikhil v Jain

  2. 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. What's PHP?

  3. Downloading PHP To download PHP, go to http://www.php.net/downloads.php and choose the PHP ZIP package listed under the "Windows Binaries" heading. This will take you to a page listing various mirrors containing the file. You can choose any mirror listed on the page but you may get faster downloads from the more local file mirrors (the ones at the top of the list).

  4. Installing PHP Installing PHP on Windows XP from the downloaded PHP zip file is just a matter of extracting the zip file to a directory and altering the Apache configuration file to use the PHP interpreter for PHP scripts.

  5. Instructions 1. Right click on the PHP zip archive (retrieved in step 1 of this guide) and click "Extract All..." and then "Next". 2. Change C:\Downloads\php-4.3.3-Win32 to C:\ and click "Next", followed by "Finish". There should now exist a folder C:\php-4.3.3-Win32 . 3. Rename the this folder from C:\php-4.3.3-Win32 to C:\php.

  6. 4. Open the httpd.conf (C:\Program Files\Apache Group\Apache\conf\httpd.conf) file and find the line: <IfModule mod_alias.c> 5. Immediately under this line insert the following lines: ScriptAlias /php/ "c:/php/" AddType application/x-httpd-php .php .phtml Action application/x-httpd-php "/php/php.exe" 6. Save the file as httpd.conf.

  7. 7. To test that PHP and Apache now work together, create a plain text file and insert the following: <?php phpinfo(); ?> 8. Save this file as test.php in the C:\Program Files\Apache Group\Apache\htdocs folder. 9. Restart the Apache server (Start > Programs > Apache HTTP Server > Control Apache Server > Restart) so Apache will use the altered configuration file.

  8. If you go to http://127.0.0.1/test.php in a web browser you should see a page like this: If “Virtual directory Spport” is marked as enabled, you have successfully installed MySQL and should now have a complete working Apache, MySQL, PHP environment.

  9. SAMPLE PROGRAMS

  10. 1. Displaying the 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>

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

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

  13. <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"; } elseif($today == "Monday") { $bgcolor = "#FFFFFF"; } else { // Since it is not any of the days above it must be Saturday $bgcolor = "#F0F4F1"; } 4. Change background color based on day of the week using if else elseif statements

  14. print("<body bgcolor=\"$bgcolor\">\n"); ?> <br>This just changes the color of the screen based on the day of the week </body> </html> elseif($today == "Tuesday") { $bgcolor = "#FBFFC4"; } elseif($today == "Wednesday") { $bgcolor = "#FFE0DD"; } elseif($today == "Thursday") { $bgcolor = "#E6EDFF"; } elseif($today == "Friday") { $bgcolor = "#E9FFE6"; }

  15. 5. Change background color based on day of the week using array <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>

  16. 6. 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>

  17. 7. 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>"); } ?>

  18. 8. 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"); ?>

  19. 9. 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"); ?>

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

  21. <? 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>"); if($slot[0] == $slot[1] && $slot[0] == $slot[2]) { print("</td></tr>Winner! -- Hit refresh on your browser to play again"); exit; } } ?> 11. PHP simple slot machine - multiple rand number generation

  22. <div align="center"><center> <table border="1" width="50%"> <tr> <? slotnumber(); ?> </td> </tr> <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>

  23. 12. Random text link advertising using predefined arrays <? $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"); $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",

  24. "- 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"); srand(time()); $sizeof = count($random_url); $random = (rand()%$sizeof); print("<center><a href=\"$random_url[$random]\">$url_title[$random]</a> $url_desc[$random]</center>"); ?>

  25. 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 lowercase print(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 capitalized print(ucwords("i bet this will show the first letter of every word capitalized<br>")); ?>

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

  27. 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>"); } ?>

  28. <? $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"); srand(time()); for($i = 0; $i < 52; $i++) { $count = count($cards); $random = (rand()%$count); 16. Shuffling and "cutting" a deck of playing cards

  29. if($cards[$random] == "") { $i--; } else { $deck[] = $cards[$random]; $cards[$random] = ""; } } 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++; } ?>

  30. 17. Admin interface for adding and deleting users using mySQL <? $db = "DATABASE NAME"; $admin = "MYSQL USER NAME"; $adpass = "MYSQL PASSWORD"; $mysql_link = mysql_connect("localhost", $admin, $adpass); mysql_select_db($db, $mysql_link); ?> <HTML> <BODY> <script language="php"> if($react == "delete_user") { if($user) { $query = "DELETE from login WHERE user='$user' "; $result = mysql_query($query, $mysql_link); if(mysql_num_rows($result)) { print("<strong>$user</strong> successfully deleted<p>"); } }

  31. else { print("<strong>no users are available to delete yet, sorry.</strong><p>"); } } elseif ($react == "add_user") { if(($user) and ($pass)) { $query = "INSERT into login VALUES ( "; $query .= "0, SYSDATE(), '$username', '$password' )"; mysql_query($query, $mysql_link); } else { print("<strong>either your user or password field was left blank</strong><p>"); } } else { print("<center>Administration Area - Choose your option</center>"); } </script> <form method="POST" action="admin.php3"><div align="center"><center><p>Delete Users <input type="hidden" name="react" value="delete_user"> <select name="user" size="1">

  32. <script language="php"> $query = "SELECT user FROM login ORDER BY user"; $result = mysql_query($query, $mysql_link); if(mysql_num_rows($result)) { // we have at least one user, so show all users as options in select form while($row = mysql_fetch_row($result)) { print("<option value=\"$row[0]\">$row[0]</option>"); } } else { print("<option value=\"\">No users created yet</option>"); } </script> </select><input type="submit" value="Submit"></p></center></div> </form> <form method="POST" action="admin.php3"> <input type="hidden" name="react" value="add_user"> <div align="center"><center><p>ADD A New User<br> User: <input type="text" name="user" size="20"><br> Pass: <input type="text" name="pass" size="20"><br> <input type="submit" value="Submit"></p></center></div> </form> </BODY> </HTML>

  33. 18. 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> <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>

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

  35. print("<td width=\"11%\" bgcolor=\"$color\"><center><small>"); $url = $row[2] . ".php3"; 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></td>"); $rank++; } } </script> </table> </BODY> </HTML>

  36. 19. 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)    )";

  37. 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>");?>

  38. 20. MySQL based counter script for multiple pages <? $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]");   }}?>

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

  40. 21. Classify Email as Bounce (DSN) or Automated Reply // 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; }

  41. 21. Classify Email as Bounce (DSN) or Automated Reply $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"; }

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

  43. 21. Classify Email as Bounce (DSN) or Automated Reply 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"; }

  44. 21. Classify Email as Bounce (DSN) or Automated Reply 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"; }

  45. 21. Classify Email as Bounce (DSN) or Automated Reply 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 // support@chilkatsoft.com regarding emails having this // bounce type. print 'Suspected Bounce!' . "\n";} ?>

  46. 22. program to print a message <html> <h3>My first PHP Program</h3> <? echo "Hello world!"; ?> </html>

  47. 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]; ?>

  48. 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'];

  49. 24.File Upload Script 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>

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

More Related