Php Official site at . About php Php is server-side code. Php typically sits in a php tag inside an...

Post on 24-Jan-2016

223 views 0 download

Transcript of Php Official site at . About php Php is server-side code. Php typically sits in a php tag inside an...

php

Official site at

http://www.php.net/

About php

• Php is server-side code.

• Php typically sits in a php tag inside an html doc, so we refer to it as a script.

• The server executes the php code as it delivers the html to the client.

• Php provides a way for the serv er to dynamically render an html page.

PHP available at instant rails or xampp

• http://www.apachefriends.org/en/xampp.html

Xampp site has downloads for exe, zip and install formats of apache (server), php, mysql, perl and filezilla.

Instant Rails comes with mysql, php, and ruby.

Either way, remember to start your apache server to serve php documents.

This semester we will use InstantRails, available at

http://instantrails.rubyforge.org/wiki/wiki.pl

After download of xampp/install- run control panel:C:\xampp\xampp\xampp-control.exe

Xampp Control panel running

Instant Rails also has a control panel to start apache and mysql servers – the I thingy

Control panel running with both apache and mysql started.

Running a php – notice the URL

For xampp, put php here: xampp\apache\htdocs

In instant rails, put php scripts in www dir

The extension: .php

• .php tells the (server) to run the php interpreter for the embedded script.

• You can use the usual script tag but the

<?php ?>

notation is less typing.

Test1.php – note simple variable definition… type is dynamically allocated

<html>

<?php $myvar="message string"; echo $myvar;

?>

other stuff

<html>

Php running in instant rails: navigate to http://localhost/appname.php (even

though it has html tags)

Calling predefined Phpinfo()

Script to call phpinfo()

<html>

<?php

phpinfo()

?>

<html>

Trivial.php<html><head> <title> today.php </title></head><body><p><?php print "<b>Welcome to my home page <br /> <br />"; print "Today is:</b> "; print date("l, F jS"); print "<br />";?></p></body></html>

Trivial.php

Control structures… note variables get $

<html><?php

$myvar="message string"; $times = 5; $x = 0; while ($x < $times) {echo "Hello World<br/>"; ++$x; }

?><html>

browser

Create a long long webpage

<html><?php$number = 1000;$current = 0;while ($current < $number) {++$current;echo "$current<br/>";}?>

Numbers 1..1000

Powers.php text example<html><head> <title> powers.php </title></head><body><table border = "border"><caption> Powers table </caption><tr><th> Number </th><th> Square Root </th><th> Square </th><th> Cube </th><th> Quad </th></tr><?phpfor ($number = 1; $number <=10; $number++) {$root = sqrt($number);$square = pow($number, 2);$cube = pow($number, 3);$quad = pow($number, 4);print("<tr align = 'center'> <td> $number </td>");print("<td> $root </td> <td> $square </td>");print("<td> $cube </td> <td> $quad </td> </tr>");}?></table></body></html>

A table of powers

Just the php part

<?phpfor ($number = 1; $number <=10; $number++) {$root = sqrt($number);$square = pow($number, 2);$cube = pow($number, 3);$quad = pow($number, 4);print("<tr align = 'center'> <td> $number </td>");print("<td> $root </td> <td> $square </td>");print("<td> $cube </td> <td> $quad </td> </tr>");}?>

arrays

• Arrays have similarities to arrays and hashes (from perl)

Using an array<html><?php$names[0] = 'John';$names[1] = 'Paul';$names[2] = 'Steven';$names[3] = 'George';$names[4] = 'David';$number = 5;$x = 0;while ($x < $number) {$namenumber = $x + 1;echo "Name $namenumber is $names[$x]<br>";++$x;}?><html>

Using an array

Another array as html list

The script<html><body>The list<ul><?php$family=array('keely','shanny','tisha','mom','dad');foreach($family as $member){echo "<li>$member";}?></ul></body></html>

Different output from an array

Script from previous slide

<?php

$family=array('keely','shanny','tisha','mom','dad');

print_r($family);

?>

A hash (array): key-value pairs

The script for previous slide<html><body><ul><?php$family=array('Keely'=>'daughter','Patricia'=>'daughter','Siobhan'=>'da

ughter','Katie'=>'mom','Dennis'=>'dad');foreach($family as $key=>$person){echo "<li>$key is a $person";}?></ul></body></html>

Sorting an array: text example

<?php$original = array("Fred" => 31, "Al" => 27, "Gandalf" => "wizzard", "Betty" => 42, "Frodo" => "hobbit");?><h4> Original Array </h4><?phpforeach ($original as $key => $value) print("[$key] => $value <br />");

$new = $original;sort($new);?><h4> Array sorted with sort </h4><?phpforeach ($new as $key => $value) print("[$key] = $value <br />");

$new = $original;sort($new, SORT_NUMERIC);?>

Sorting an array: text example<h4> Array sorted with sort and SORT_NUMERIC </h4><?phpforeach ($new as $key => $value) print("[$key] = $value <br />");$new = $original;rsort($new);?><h4> Array sorted with rsort </h4><?phpforeach ($new as $key => $value) print("[$key] = $value <br />");$new = $original;asort($new);?><h4> Array sorted with asort </h4><?phpforeach ($new as $key => $value) print("[$key] = $value <br />");$new = $original;arsort($new);?><h4> Array sorted with arsort </h4><?phpforeach ($new as $key => $value) print("[$key] = $value <br />");?>

Sorting an array: text example

Sorting an array: text example

Sorting an array: text example

Function example 1

Function example 1: local var $sum

<?phpfunction summer ($list){$sum=0;foreach($list as $value) $sum +=$value; return $sum; } $sum=10; $nums=array(1,3,5,7,9); $ans=summer($nums); print("sum of values in \$nums is $ans<br/>"); print("value of var \$sum is still $sum<br/>");?>

Function example 2: global var $xsum

Function example 2: global var $xsum<?php$xsum=0;function summer ($list){

global $xsum;//access the global varforeach($list as $value) $sum +=$value;$xsum +=$sum;return $sum; } $nums=array(1,3,5,7,9); $others=array(2,4,6,8,10); $ans=summer($nums); print("sum of values in \$nums is $ans<br/>"); $ans=summer($others); print("sum of values in \$others is $ans<br/>"); print("value of var \$xsum is $xsum<br/>");?>

Static function variables

Static function variables<?phpfunction summer ($list){

static $xsum=0;//static varstatic $callcount=0;//static var$callcount++;print("call count is $callcount<br/>");print("function start...current values of \$xsum is $xsum<br/>");foreach($list as $value) $sum +=$value;$xsum +=$sum;print("function ending...current values of \$xsum is $xsum<br/>");return $sum; } $nums=array(1,3,5,7,9); $others=array(2,4,6,8,10); $more=array(1,1,1,1,1,1); $ans=summer($nums); $ans=summer($others); summer($more);?>

Counting word frequencies<?phpfunction splitter($str){$freq=array();$words=preg_split("/[ .;:!,?]\s*/",$str);foreach($words as $word){$keys=array_keys($freq);if(in_array($word,$keys)) $freq[$word]++; else $freq[$word]=1; } return $freq; }//end fn $str="here is some long sentence... a a a a punctuation ... other words,,, apples pears peaches oranges it if x x x"; $tbl=splitter($str); print "<br/>frequencies<br/>"; $sorted_keys=array_keys($tbl); sort($sorted_keys); foreach($sorted_keys as $word) print "$word $tbl[$word] <br/>"; ?>

Output…not sure about 1st line

An html form whose post goes to action.php

<form action="action.php" method="post">

<p>Your name: <input type="text" name="name" /></p>

<p>Your age: <input type="text" name="age" /></p>

<p><input type="submit" /></p>

</form>

Html form

Action.php output

Action.php

Hi <?php echo $_POST['name']; ?>.

You are <?php echo $_POST['age']; ?> years old.

Processing a form

• entire html form is in your text

• Php is in text

Popcorn form

Processed via php

Process form values: html is in slide notes<?php$unpop=$_POST["unpop"];$caramel=$_POST["caramel"];$caramelnut=$_POST["caramelnut"];$toffeynut=$_POST["toffeynut"];$name=$_POST["name"];$street=$_POST["street"];$city=$_POST["city"];$payment=$_POST["payment"];// If any of the quantities are blank, set them to zeroif ($unpop == "") $unpop = 0;if ($caramel == "") $caramel = 0;if ($caramelnut == "") $caramelnut = 0;if (toffeynut == "") $toffeynut = 0;// Compute the item costs and total cost$unpop_cost = 3.0 * $unpop;$caramel_cost = 3.5 * $caramel;$caramelnut_cost = 4.5 * $caramelnut;$toffeynut_cost = 5.0 * $toffeynut;$total_price = $unpop_cost + $caramel_cost + $caramelnut_cost + $toffeynut_cost;$total_items = $unpop + $caramel + $caramelnut + $toffeynut;// Return the results to the browser in a table

Handling file data

Data file

23231name frm filestreet from filecity from filezip from file

A few modified lines in popcorn php to read from a file

//getting data via file reads$file=fopen("popcorn.txt","r") or die ("file error");$unpop=fgets($file,50);$caramel=fgets($file,50);$caramelnut=fgets($file,50);$toffeynut=fgets($file,50);$name=fgets($file,50);$street=fgets($file,50);$city=fgets($file,50);$payment=fgets($file,50);

Writing to a file

Open a file for output, too

$readfile=fopen("popcorn.txt","r") or die ("read file error");

$writefile=fopen("popcornbill.txt","w") or die ("write file error");

Write to the file$bytes=fwrite($writefile,$name);$bytes=fwrite($writefile,$street);$bytes=fwrite($writefile,$city);$bytes=fwrite($writefile,$payment);$bytes=fwrite($writefile,$unpop);$bytes=fwrite($writefile,$unpop_cost);$bytes=fwrite($writefile,$caramel);$bytes=fwrite($writefile,$caramel_cost);$bytes=fwrite($writefile,$caramelnut);$bytes=fwrite($writefile,$caramelnut_cost);$bytes=fwrite($writefile,$toffeynut);$bytes=fwrite($writefile,$toffeynut_cost);$bytes=fwrite($writefile,$total_price);$bytes=fwrite($writefile,$total_items);print ("popcornbill.txt has been written<br/>");

File contents after execution (would need to be prettied up)

name frm file

street from file

city from filezip from file236927313.515$94.529

Solution to 1st php lab: add new user<?php$readfile=fopen("users.txt","r+") or die ("read file error");$ctr=0;while($user[$ctr]=trim(fgets($readfile))){$pw[$ctr]=trim(fgets($readfile));//print ("while loop $user[$ctr] $pw[$ctr]<br/>");$ctr++;}$name=$_POST["name"];$pass=$_POST["pw"];$name= $name . "\n";$pass=$pass . "\n";$bytes=fwrite($readfile,$name);$bytes=fwrite($readfile,$pass);print ("new user added");?>

New user html page

<html><body><h1> new user account page</h1><form action="adduser.php" method="post"> <p>Your name: <input type="text" name="name" /></p> <p>Your password: <input type="password" name="pw"

/></p> <p>enter password again</p> <p>Your password: <input type="password"

name="pw2" /></p> <p><input type="submit" /></p></form>

Login page

<html><body><h1> user login page</h1><form action="checkpw.php" method="post"> <p>Your name: <input type="text" name="name" /></p> <p>Your password: <input type="password" name="pw"

/></p> <p><input type="submit" /></p></form></body></html>

Check the pw<?php$name=$_POST["name"];$pass=$_POST["pw"];//print("$name $pass<br/>");$readfile=fopen("users.txt","r") or die ("read file error");$ctr=0;while($user[$ctr]=trim(fgets($readfile))){$pw[$ctr]=trim(fgets($readfile));//print ("while loop $user[$ctr] $pw[$ctr]<br/>");$ctr++;}$found=false;for($i=0;$i<$ctr&&!$found;$i++)if($name==$user[$i]){$j=$i;$found=true;}if($found )print("found at $j<br/>");if($found && $pass==$pw[$j])print("pw ok");else print ("pw failure");?>

Add new user

Logging in

Same user wrong pw

• User is found in position 8 but the pw is wrong.

• I did not complete the part with a cookie and a link to another page.

regular expressions

• php supports pattern matching/regular expressions the same way javascript and perl do

Php site links

• http://us3.php.net/ -- the official site

• http://us3.php.net/manual/en/language.variables.external.php -- referencing http post variables as per precious slides

• http://us3.php.net/manual/en/faq.html.php --faq

Javascript & php

• Javascript to get an ip calling php

<html>

<body>

<script type="text/javascript" src="http:\\localhost\ip.php"></script>

</body>

</html>

The php

<?//"ip.php" example- display user IP address on any pageHeader("content-type: application/x-javascript");$serverIP=$_SERVER['REMOTE_ADDR'];echo "document.write(\"Your IP address is: <b>" .

$serverIP . "</b>\")";?>

Php-javascript example2

• Javascript

<html>

<body>

<script type="text/javascript" src="phpmessage.php"></script>

</body>

</html>

The php

<?//Header("content-type: application/x-javascript");

$myvar="a var value";echo "document.write(\"Your var is: <b>" .

$myvar . "</b>\")";

?>