cosc 4750

56
Cosc 4750 Beginning PHP

Upload: pierce

Post on 08-Jan-2016

25 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Cosc 4750

Cosc 4750

Beginning PHP

Page 2: 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

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

Page 3: Cosc 4750

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

Page 4: Cosc 4750

Example PHP code

• 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>

Page 5: Cosc 4750

Comments

• PHP has single line comments like C++

uses the // to start a comment

// This is a comment

$var = 10; //bah… bah…

Page 6: Cosc 4750

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;

Page 7: Cosc 4750

Using Variables

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

Page 8: Cosc 4750

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;

Page 9: Cosc 4750

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

Page 10: Cosc 4750

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<?phpecho $var1;?>NOTE: The name must be the same including case!

Page 11: Cosc 4750

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.

Page 12: Cosc 4750

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.

Page 13: Cosc 4750

Avoid errors

• Use the isset function• If (isset($_REQUEST['var'])){

– $var = $_REQUEST['var'];

• Else– $var = “”;

Page 14: Cosc 4750

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.

Page 15: Cosc 4750

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.

Page 16: Cosc 4750

HTML code input

• To better sanitize 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.

Page 17: Cosc 4750

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)

Page 18: Cosc 4750

Control Structures (2)

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

Page 19: Cosc 4750

Control Structures (3)

• Loopswhile (boolean expression) { statements}

do {statements} while (boolean expression);

Page 20: Cosc 4750

Control Structures (4)

• for loops

for (set loop counter; test loop counter; increment/decrement loop counter) {

statements;

}

Page 21: Cosc 4750

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.

Page 22: Cosc 4750

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

Page 23: Cosc 4750

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

Page 24: Cosc 4750

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

}

Page 25: Cosc 4750

More on Arrays (3)

• sorting (with index as numbers)sort($array);• sorting hash arrayasort($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.

Page 26: Cosc 4750

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

Page 27: Cosc 4750

functions

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

Page 28: Cosc 4750

functions (2)

• pass by valuefunction f1 ($var) { // $var can be altered but won't change the // calling variable}• pass by referencefunction f2 (&$var) { //$var value will now change the calling variable}

Page 29: Cosc 4750

functions (3)

• default parameter valuesfunction 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 parametersfunction f4($v1=2, $v2) { statements}f4(12); //$v1 =12, $v2 = 0

Page 30: Cosc 4750

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.

• creating global variables in functions uses the keyword global

global $variable;• static variablesstatic $variable

– the variable will retain it's value between function calls.

Page 31: Cosc 4750

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

Page 32: Cosc 4750

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.

Page 33: Cosc 4750

File I/O

• similar to PERL file I/O• openfilehandle = 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);

Page 34: Cosc 4750

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

Page 35: Cosc 4750

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)

Page 36: Cosc 4750

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

Page 37: Cosc 4750

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

Page 38: Cosc 4750

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;

Page 39: Cosc 4750

PHP database connectivity (3)

• After finishing with the database, you need to close the connection

• mysql_close($link_id);

Page 40: Cosc 4750

PHP commands For lab 6

<?php// make the connection$link_id = mysql_connect("localhost", "testacc",

"csteach");//choose the databasemysql_select_db("webacc", $link_id);… //now ready to retreive,modify, or delete datamysql_close($link_id);?>

Page 41: Cosc 4750

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

Page 42: Cosc 4750

With a select

$result = mysql_query("Select * from test");

while($query_data = mysql_fetch_row($result)) {

echo $query_data[0], $query_data[1], $query_data[2], "<BR>";

}

//prints to the browser the contents of the table test, with three rows.

Page 43: Cosc 4750

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"], $query_data["owner"], "<BR>";

}

//prints to the browser the contents of the table test, with three rows.

Page 44: Cosc 4750

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.

Page 45: Cosc 4750

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

Page 46: Cosc 4750

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.

Page 47: Cosc 4750

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 databasemysql_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);?>

Page 48: Cosc 4750

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<?phpmail("[email protected]","test", "this is test message");?>

Page 49: Cosc 4750

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.

Page 50: Cosc 4750

Example

<?php$to = "[email protected]";$subject = "Test message";$body = "This is a test message";$headers = "From:[email protected]\r\nCc:

[email protected]";mail($to,$subject,$body,$headers);?>

Page 51: Cosc 4750

Example with html pages

• 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>

Page 52: Cosc 4750

Attachments

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

details.– It deals with PHP and file uploads, another

setting in the php.ini

Page 53: Cosc 4750

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.

Page 54: Cosc 4750

php.ini

• This file contains all the setting that php will use when it executes.– max_execution_time = 30

• Maximum execution time of each script, in seconds

– memory_limit = 8M• Max amount of memory the script can use

– File uploads and max size• file_uploads = On• upload_max_filesize = 2M

• And many more options, make sure you read the comments about each option.

Page 55: Cosc 4750

Reference

• Information was found from the web and the book– Beginning PHP4, Choi ..., WROX, 2003– Programming PHP, Lerdorf & Taroe, O’Reilly,

2002– PHP and MYSQL, Williams & Lane, O’Reilly,

2004

Page 56: Cosc 4750

QA&