1 / 51

Cosc 4750

Cosc 4750. Beginning PHP. PHP. PHP => "PHP Hypertext Preprocessor" Designed for the web Cross-platform: Runs on both UNIX and windows (with everything installed correctly) PHP is mix of PHP langauge and HTML code Runs on the Sever-side, specifically on the web server

declan
Download Presentation

Cosc 4750

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. Cosc 4750 Beginning PHP

  2. PHP • PHP => "PHP Hypertext Preprocessor" • Designed for the web • Cross-platform: Runs on both UNIX and windows (with everything installed correctly) • PHP is mix of PHP langauge and HTML code • Runs on the Sever-side, specifically on the web server • Light weight compared to PERL, since it runs inside the web-server itself. • In many ways PHP is perl, but stripped down with most of the "web" modules already installed.

  3. NOTE • I'm assuming you know several things: • HTML • SQL • PERL • I'll use PERL to explain PHP. • Also, all files are saved with the .php extension on them, instead of .html

  4. file: helloworld.php <html> <head> <title>PHP Test</title> </head> <body> <?php echo "<p>Hello World</p>"; ?> </body> </html> Output to browser <html> <head> <title>PHP Test</title> </head> <body> <p>Hello World</p> </body> </html> Example PHP code

  5. Comments • PHP has single line comments like C++ uses the // to start a comment // This is a comment $var = 10; //bah… bah…

  6. variables • like PERL • All variables start with a $ • Unlike PERL • Variables can be typed or typeless • types: • String String data is always in double quotes • integer, double, array (numeric and hash index), object, and unknown type • Boolean (value: true or false) • Displaying variables • echo $variablename;

  7. Using Variables • Remember this is inside html code! <html><body> <? php $CarType = "Ford" $enginesize = "3.0"; $car = $cartype . " " . $enginesize; echo $car; ?> </body> </html>

  8. Constants • Don't use $, instead use a special keyword to create them • define(constantname, value); • Examples • define("FREEZING", 0); • define(INDEPENCEDAY, "4th of July"); • echo "Independence Day is ". INDEPENDENCEDAY;

  9. Variables and operators • Same as with PERL • With typed variables • numeric operators for numeric data types • string operators for string data types • such as the dot is used for concatenation with strings • can not $str = $str1 + $str2

  10. Getting data from forms <form action="test.php" method=GET> <!– Example input box--> <input NAME="var1" Type="text"> </form> • OR <form action="test.php" method=POST> <input NAME="var1" Type="text"> <!– Example input box--> </form> • The name comes into the PHP script as a variable <?php echo $var1; ?> NOTE: The name must be the same including case!

  11. Radio buttons and Check Box • <input name="choice" type="Checkbox"> • check boxes have the value of on or off • unless you use the value tag • <input name="choice" type="Checkbox" value="Computers"> • Same with Radio buttons.

  12. Filling arrays from forms <form method=get action="test2.php"> <input name=arr[] type=text> <input name=arr[] type=text> <input type=submit> </form> • In test2.php • $arr[0] has the value of the first input and $arr[1] has the value from the second.

  13. HTML code input • To better "secure" your input you can use a the function HTMLSpecialChars(value); • This convert html codes into text for display. $string = HTMLSpecialChars("<B>hi</B>"); echo $string; • Will display <B>hi</b> to the web browser instead of hi.

  14. Control Structures • If statements • Again like PERL • if (boolean value) { statements } • elseif (boolean value) { statements } • else { statements } • Boolean operators are the same as in PERL, except you don't have to make any distinctions between string and numerical operators • < <= == > => !=, AND, &&, OR, ||, ! (NOT)

  15. Control Structures (2) • switch statement • NOT in perl, just like the C/C++ statement switch (variable) { case value1: statements; break; case value2: statements; break; default: statements; } • like C/C++ you can leave off the break

  16. Control Structures (3) • Loops while (boolean expression) { statements } do { statements } while (boolean expression);

  17. Control Structures (4) • for loops for (set loop counter; test loop counter; increment/decrement loop counter) { statements; }

  18. Arrays structure • foreach structure • similar to PERL foreach ($array As $variable) { statements } foreach ($array As $arrIndex => $var) { statements } • second format makes the array index value available in the loop as well.

  19. More on Arrays • Initialization (with number index values) • $arr[0] = "value1"; • $arr[1] = "value2"; • … • OR allow PHP fill in the numbers • $arr[] = "value1"; • $arr[] = "value2"; • … • OR • $arr = array ("value1", "value2", … , "valueX"); • OR (for hashing) • $arr["v1"] = "value1"; • $arr["v2"] = "vavlue2";

  20. More on Arrays (2) • Iterating through non-sequential arrays and hash arrays. • list and each functions while ( list($indexvalue, $element) = each( $array) ) { echo "The value of element $indexvalue is $element"; }

  21. More on Arrays (3) • sorting (with index as numbers) sort($array); • sorting hash array asort($hasharray); • NOTE you can use sort on hashes, but the keys (string indices) are replaced with numbers. • reverse alphabetical order sort • rsort($array) and arsort($hasharray) • ksort($hasharray) • Sorts based on the keys, instead of the element contents.

  22. More on Arrays (4) • array_push() and array_pop() • Allows you to use an array as a stack. • implode and explode functions • $string = implode("delimiter", $array); • like join statement in PERL • $arr = explode("delimiter", $string); • like split statement in PERL

  23. functions function functionname (parameters) { statements; return; • OR return value; //or variable } • Calling the function functionname(parameters); $variable = functionname(parameters);

  24. functions (2) • pass by value function f1 ($var) { // $var can be altered but won't change the // calling variable } • pass by reference function f2 (&$var) { //$var value will now change the calling variable }

  25. functions (3) • default parameter values function f3 ($var=2) { //f3 can be called with no parameters // and $var will have the value of 2 } • parameter order, since you don't have pass values to the parameters function f4($v1=2, $v2) { statements} f4(12); //$v1 =12, $v2 = 0

  26. Scope of variables Variables "declared" outside of functions are global Variables "declared" inside functions are local variables to the function "declared" is the first occurrence of the variable. creating global variables in functions uses the keyword global global $variable; static variables static $variable the variable will retain it's value between function calls. functions (4)

  27. functions (5) • final notes. • You can nest functions inside functions • the inner function will cause an error (redeclaration error) on the second time the outer function is called. • Recursion • allowed

  28. including files include("filename"); • Execute a separate PHP script at the point in the code • include commonly used PHP functions that can be called by this script. • define variables and/or constants, etc… • Can be text or html that will be displayed.

  29. File I/O • similar to PERL file I/O • open filehandle = fopen("filename", mode); $fp = fopen("data.txt","r"); //read from file data.txt • modes • "r" read only • "w" for writing only • "a" append, create if doesn't exist. • close • fclose (filehandle);

  30. File I/O (2) • reading • $variable = fread(filehandle,bytes); $data = fread($fp, 20); // read 20 bytes from the file • Writing • fwrite(filehandle, data); fwrite($fp, "abc");

  31. File I/O (3) • $c = fgetc($fp) read file one character at a time • feof($fp) returns true if it the end of the file • $arr = file(filename) read in an entire file • Each line is an element in the $arr • copy(filename1,filename2) copy f1 to f2 • rename(f1, f2) rename f1 to f2 • unlink(filename) del filename • may not work in windows • use system or exec function (see PERL for descriptions)

  32. Directory I/O • chdir() change directory • rmdir() delete directory • mkdir() delete directory • opendir() open a directory for "reading" • readdir() read the directory • closedir() close the directory

  33. PHP database connectivity • Using mysql as the database to connect to, since it included with our Redhat installation. • First you need to connect to the database $link_id = mysql_connect("localhost", "username", "password") • like mysql command in unix mysql –u username –p password –h host

  34. PHP database connectivity (2) • Now we need to select the database to use mysql_select_db("database", $link_id); • Where $link_id is from the mysql_connect command • mysql command mysql> use database;

  35. PHP database connectivity (3) • After finishing with the database, you need to close the connection • mysql_close($link_id);

  36. PHP commands For lab 6 <?php // make the connection $link_id = mysql_connect("localhost", "testacc", "csteach"); //choose the database mysql_select_db("webacc", $link_id); … //now ready to retreive,modify, or delete data mysql_close($link_id); ?>

  37. Accessing the database • PHP uses one command to send SQL commands to the database (for mysql) • $result = mysql_query("SQL command"); • Another to retreive results (from say a select), one row of data at a time • $arr = mysql_fetch_row($result); • //gets first row of data • $arr = mysql_fetch_row($result); • //gets next row of data • etc..

  38. With a select $result = mysql_query("Select * from test"); while($query_data = mysql_fetch_row($result)) { echo "$query_data[0] $query_data[1] $queary_data[2] <BR>"; } //prints to the browser the contexts of the table test, with three rows.

  39. With a select (2) • Or can use the field names, for better readablity. $result = mysql_query("Select * from test"); while($query_data = mysql_fetch_row($result)) { echo "$query_data["name"] $query_data["ip"] $queary_data["owner"] <BR>"; } //prints to the browser the contexts of the table test, with three rows.

  40. With an Insert • $sql = "Insert into test values (‘csteach31’,’129.72.218.41’,’cosc’)"; • mysql_query($sql); • NOTE lack of return value. • NOTE: inserting "odd" characters such as ' as in I'm won't work. • There is a function to fix it called addslashes $var = addslashes("I'm"); // result "I\'m" • Removed with the stripslashes() later.

  41. Delete and update • Use the same php command $sql = "delete from test where name ='k2' "; mysql_query($sql); $sql = "update test set ip='129.72.14.123' where name = 'esig' "; mysql_query($sql);

  42. results from insert/update/delete • mysql will tell you how many how many rows were effected by insert, update or delete • There is a function to get that information from mysql • $var = mysql_affected_rows($link_id); • $var contains a the number of effected rows.

  43. example • A php script that displays the contains of a the database on a webpage <?php // make the connection $link_id = mysql_connect("localhost", "testacc", "csteach"); //choose the database mysql_select_db("webacc", $link_id); $result = mysql_query("Select * from test"); while($query_data = mysql_fetch_row($result)) { echo "$query_data["name"] $query_data["ip"] $queary_data["owner"] <BR>"; } mysql_close($link_id); ?>

  44. PHP and e-mail • Sending e-mail in PHP is very simple • On windows you need set a mailer, • command: mail( ) • It takes 4 arguments • The intended recipient • subject line • body of the e-mail • Extra headers (optional) • Example <?php mail("seker@uwyo.edu","test", "this is test message"); ?>

  45. Extra headers field • Add header like • From: • Reply-To: • Cc: • Bcc: • Others you want to create. • You need to include the \r\n between the extra headers.

  46. Example <?php $to = "seker@uwyo.edu"; $subject = "Test message"; $body = "This is a test message"; $headers = "From:seker@uwyo.edu\r\nCc: venkat@uwyo.edu"; mail($to,$subject,$body,$headers); ?>

  47. mail.html <html><body> <form method=post action="e-mail.php"> to: <input name=to size=20> From: <input name=from size=20> subject: <input name=sub size=30> Message: <textarea name=body rows=5 cols=30> </form> e-mail.php <html> <body> <?php $header = "From: ".$from; mail($to,$sub,$body,$headers); ?> You e-mail to $to has been sent. </body> </html> Example with html pages

  48. Attachments • You can also set it up to accept attachments • but we don't have the time to spend on the details.

  49. additional features built in PHP • additional features • sessions • use cookies • Persistence of user data between HTTP requests • PHP and XML • generating graphics • Working with the browser client and getting info. • And many functions I skipped over. • Such as regular expression functions, network functions, etc.

  50. Reference • Information was found from the web and the book Beginning PHP4, Choi ..., WROX, 2003

More Related