1 / 56

Cosc 4750

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

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

  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. Output to browser <html> <head> <title>PHP Test</title> </head> <body> <p>Hello World</p> </body> </html> Example PHP code • file: helloworld.php <html> <head> <title>PHP Test</title> </head> <body> <?php echo "<p>Hello World</p>"; ?> </body> </html>

  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. Getting Data from forms • The previous example assumes that your php.ini file has • register_globals = On • This is a security risk, so by default it is off • So instead you should use • $var = $_POST['name']; //For post method • Where name is the name of name listed in the html.

  12. Getting Data from forms Example • If ($_SERVER['REQUEST_METHOD'] == 'GET') { • $var = $_GET['var']; • else • $var = $_POST['var']; • } • New version • $_REQUEST['var']; //both get and post method.

  13. Avoid errors • Use the isset function • If (isset($_REQUEST['var'])){ • $var = $_REQUEST['var']; • Else • $var = “”;

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

  15. 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. • Note, filling Arrays won’t work if register_globals is off.

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

  17. 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)

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

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

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

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

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

  23. Hashing array and return values • Many PHP functions will return an array of data, which can be used as either a hash or a “normal” array. • $date1 = localtime(); • $min = $date1["tm_min"]; • $hour = $date1["tm_hour"]; • $year = $date1["tm_year"] + 1900; • $mon = $date1["tm_mon"]+1 ;//$mon ++; • $day = $date1["tm_mday"];

  24. 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"; }

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

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

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

  28. 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 }

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

  30. 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) • 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.

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

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

  33. 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);

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

  35. 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)

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

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

  38. 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;

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

  40. 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); • ?>

  41. Accessing the database • PHP uses one command to send SQL commands to the database (for mysql) • $result = mysql_query("SQL command"); • Another to retrieve 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..

  42. 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 contents of the table test, with three rows.

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

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

  45. 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);

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

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

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

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

  50. 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); • ?>

More Related