2.47k likes | 3.6k Views
Short PHP tutorial. About PHP. PHP is an interpreted language. You write a series of statements. Apache hands these statements to the PHP interpreter. The interpreter executes these statements one by one. When it find an error, it stops running and signals the error.
E N D
About PHP • PHP is an interpreted language. • You write a series of statements. • Apache hands these statements to the PHP interpreter. • The interpreter executes these statements one by one. • When it find an error, it stops running and signals the error. • PHP 5.3 is the current version. • Compiled languages are different. They read the whole program before starting to execute it.
PHP • Need a Web server • Need PHP • All PHP files are handled by the server • PHP scripts are parsed and interpreted on the server side of a web application • Resulting output is sent to web browser for display. • Apache and PHP • When a file ends in .php, is not simply sent via an http connection like other files. • Instead, apache sends the file to the PHP processor. • It sends to the client whatever the PHP processor returns. • The PHP processor is a module that lives inside Apache.
Server side • PHP is a Server-side language even though it is embedded in HTML files much like the client-side JavaScript language. • All PHP tags will be replaced by the server before anything is sent to the web browser. • So if the HTML file contains:<html><?phpecho "Hello World"?></html> • What the end user would see with a "view source" in the browser would be: <html>Hello World</html>
PHP tags • PHP code is embedded using start and end tags • There are 4 possible sets of tags you can use: • 1 - <?php echo(“Hi”); ?> ( Long tags, preferred for this course) • 2 - <? echo(“Hi”); ?> (short tags) • 3 - <script language = “php”> (really long tags) echo(“Hi”); </script> • 4 - <% echo(“ASP style”); %> (ASP style tags)
Embedding PHP • The 4 available tag styles • <html><body><? echo 'Short Tags - Most common' ?><br /><?phpecho 'Long Tags - Portable' ?><br /><%= 'ASP Tags' %><br /><script language="php">echo 'Really Long Tags - rarely used';</script><br /></body></html> • Output • Short Tags - Most commonLong Tags - Portable<%= 'ASP Tags' %> Really Long Tags - rarely used
PHP 1st examples • Create a file with the name phpinfo.php, and the following contents <?php phpinfo(); ?> • This will create a page that tells you how PHP is configured. Look at some of the variables. • The section we may be interested in is “PHP Variables”. • These are variables that PHP can understand • from its environment • from the client
Language Basics • Variables and Expressions • <?php $foo= 1;$bar = "Testing";$xyz = 3.14;$foo= $foo+ 1;?> • Arrays • <?php $foo[1] = 1; $foo[2] = 2;$bar[1][2] = 3;?> • Functions • <?phpphpinfo();foo();$len= strlen($foo);?> • Control Structures • if • else • elseif • while • do..while • for • foreach • breakcontinue • switch • declare • return • require() • include() • require_once() • include_once()
Language Basics: Basic Data types • Numbers (integers and real) • <?php $a = 1234;$b = 0777;$c = 0xff;$d = 1.25; echo "$a $b $c $d<br />\n";?> • Output • 1234 511 255 1.25 • Strings • <?php// Single-quoted$name = 'Rasmus $last'; • // Double-quoted$str= "Hi $name\n"; • echo $str;?> • Output • Hi Rasmus $last • Booleans • <?php $greeting = true; if($greeting) { echo "Hi Carl";$greeting = false; }?> • Output • Hi Carl
Functions • Functions generally take some type of input and return some type of output (although, sometimes either input or output can be omitted). • PHP has built in functions and also gives the programmer the ability to create functions. • Example: • phpinfo() is a function. • A function is an expression that does something to something else. • The “something else” is in the parenthesis. • It is called the argument of the function. • The argument of phpinfo() is empty
Statements • Like a normal text is split into sentences, a PHP script is split into statements. • A PHP script contains one or more statements. • Each statements tells the interpreter something. • Each statement is ended by a semicolon. • In our first script there is only one statement. • Each statement is ended with a semicolon! • Think of a statement like a rule in CSS. But never forget the semicolon!
Expressions • The stuff before the semicolon is called an expression. • You can think of an expression as anything anyone may want to write in a computer program. • Expressions follow certain rules that determine the order an expression is evaluated • Ex. Should 2 + 3 * 4 be 5*4 or 2 + 12? • PHP operators have precedence similar to algebra to deal with this • Operators with higher preference are evaluated first • Ex. In the expression 2 + 3*4, the * operator has higher precedence than + so 3*4 is evaluated first to return the value 12, then the expression 2 + 12 is evaluated to return 14 • Use parentheses '( )' to force evaluation for lower precedence • Ex. (2 + 3)*4 • Do not clutter expressions with parentheses when the precedence is correct and obvious
$name $age What is a Variable? 'Dan' 30.3 • A named location to store data • a container for data (like a box or bucket) • It can hold only one type of data at a time • for example only integers, only floating point (real) numbers, or only characters • A variable with a scalar type holds one scalar value • A variable with a compound type holds multiple scalar values, BUT the variable still holds only a single (the compound type itself) value • Syntax for a variable is $<identifier> • Example: $name, $age • Case sensitive!
PHP - Variables • Starts with a $ sign • Variable names are case sensitive • Variable name must start with $ followed by a letter or underscore. They can contain letters, digits and underscores. • The following are examples of illegal names • $2files • $file-content • $file@directory • The variable name "$this" is reserved. • PHP provides a number of predefined variables • It is good to give variables meaningful names.
Assigning Values to Variables • The assignment operator: "=" • "sets" a value for a variable • not the "is equal to" sign; not the same as in algebra • It means -"Assign the value of the expression on the right side to the variable on the left side.“ • Can have the variable on both sides of the equals sign: $count = 10;// initialize counter to ten $count = $count - 1;// decrement counter • new value of count = 10 - 1 = 9
Creating Variables • A variable is declared the first time a value is set for it • A variable declaration associates a name with a storage location in memory and specifies the type of data it will store: • $a = 1.1 ; // declares and sets a real number • $a = true ; // declares and sets a boolean • $a = 'Zip Zap' ; // declares and sets a string
Variable Names: Identifiers Rules(these must be obeyed) • all identifiers must follow the same rules • must not start with a digit • must contain only numbers, letters, underscore (_) and some other special characters • names are case-sensitive (ThisName and thisName are two different variable names) • No spaces! Good Programming Practice(these should be obeyed) • always use meaningful names from the problem domain (for example, eggsPerBasket instead of n, which is meaningless, or count, which is not meaningful enough) • start variable names with lower case • capitalize interior words (use eggsPerBasket instead of eggsperbasket) • use underscore (_) for spaces • CAPITALIZE constants (i.e. variables that do not change values)
Variable Default Values • Variables have default values • $a = $a + 1; // $a=0 by default • $s = $s."Fred"; // default $s="" • IMPORTANT: It is best to not assume the default value is what you want. Alwaysexplicitly set the initial value of a variable!!!! e.g. • $a = 0; $s = ""; $b = false;
PHP - Constants • Constants do not have a dollar sign ($) before them • Case sensitive • Convention: upper case • naming rules: like any label in PHP (same as what follows the $ sign in variables) • You can define a constant by using the define( ) function. • Once a constant is defined, it can never be changed or undefined. <?php define("CONSTANT", "Hello world."); echo CONSTANT; // "Hello world.“ ?>
Strings • A piece of text in PHP is called a string. A string is a sequence of characters • A string is often surrounded by single quotes. print 'I want beer'; $want='beer'; print 'I want $want'; // prints: I want $want • If you want to use the values of variables, use double quotes $want='beer'; print "I want $want"; // prints: I want beer
Single vs. Double Quotes vs. Heredoc • Three ways to declare a string value • Single quotes • 'The sky is blue'; • Double quotes • "How much for the car?"; • Here Documents <<< When_Will_It_End It was a dark and stormy night, my son said, "Dad, tell me a story" so I said, "It was a dark and stormy night, my son said, "Dad, tell me a story" so I said, "It was a dark and stormy night, my son said, "Dad, tell me a story" so I said, When_Will_It_End
Heredoc • Multi-line string constants are easily created with a heredoc expression $variable = 'Here Here!'; $wind = <<< QUOTE Line 1. \n Line 2. " " Line 3. ' ' Line 4. $variable QUOTE; echo $wind; • Variables are expanded, escape characters are recognized
PHP 2nd example • File helloworld.php <html><title>PHP test</title><body> <? echo(“Hi”); ?> </body></html> Commenting // single line comment /* multi line comment */ # a Perl style comment • File helloworld.php <html><title>PHP test</title><body> <? // start PHP code echo(“Hi”); // end PHP code then return to HTML code ?> </body></html>
PHP echo and print • PHP has 2two functions for output: • print and echo • print returns 1 (success) or 0 (failure) • Also printf and sprintf • For reserved characters, use \ to escape them • echo “She said: \”Hi!\” ”; • ‘\n’ will insert a newline into the source view of your script • ‘<br/>’ will visually display a newline
PHP echo and print • Use echo for simple output • echo 'hello'; • echo 'hello', ' goodbye'; • echo ('hello'); • print is more or less the same • print 'hello'; • You can use ()'s • echo('hello'); • print('hello'); • New line for console output • echo "line1\nline2"; • New line for HTML output • echo 'line1<br>line2';
Printf() • Use printf() for more complex formatted output printf('This prints 2 decimal places %.2f', 3.1415927); This prints 2 decimal places 3.14 • Printf() is a function whose first argument is a string that describes the desired format and the remaining arguments are the values to substitute into the type specifications (anything that starts with %)
Single and Double quotes • You can use single quotes to quote double quotes • print 'She wrote: "I want beer." and sighed.'; • // prints: She wrote: "I want beer." and sighed. • and vice versa • print "She wrote: 'I want beer.' and sighed"; • // prints: She wrote: 'I want beer.' and sighed. • Sometimes it is not obvious when to put single quotes, double quotes, and when to leave them out. If one thing does not work, try something else.
Using the Backslash to Escape characters • The backslash is used to quote characters that otherwise are special. • print 'Don\'t give me bad beer!'; • $kind='sweet'; • $dessert='Apple pie'; • print "<p class=\"$kind\">$dessert</p>"; • // prints: <p class="sweet">Apple pie</p> • The backslash itself is quoted as \\ • print "sweet \\ sour dessert "; • // prints: sweet \ sour dessert
Using the Backslash to Escape characters • More backslash escapes • \n makes the newline character • \r make the carriage return • \t makes the tab • \$ makes the dollar • $amount='1.50'; • print "you owe \$$amount per bottle."; • // prints: you owe $1.50 per bottle. • If the backslash was not there $ would be considered a variable.
PHP 2ndexample modified • In file helloworld.php: • <html><title>PHP test</title><body> • <? • echo(“Hi”); • echo “She said: \”Hi!\””; • echo(“<p>Hi<br/>”); • echo “She said: \”Hi!\”</p>”; • ?> • </body></html> • This script could also be written as: • <?php • echo("<html><title>PHP test</title><body>Hi"); • echo "She said: \"Hi!\""; • echo("<p>Hi<br/>"); • echo "She said: \"Hi!\"</p></body></html>"; • ?>
Concatenation • This is done with the .operator. It puts two strings together, the second one after the first one. $cost='5.23'; $message='This costs ' . $cost; print $message; // prints: This costs 5.23 • Note that you have to remember to include spaces if you want it to look right: $name = “Dani"; $greeting = "Hi, there!“; $greeting . " " . $name . " Welcome"; • causes the following to display on the screen: Hi, there! Dani Welcome
Numbers • Numbers are set without the use of quotes. • You can +, -, * and / for the basic calculations. • There also is the modulus operator %. It gives the remainder of the division of the first number by the second print 10 % 7; // prints 3 • Use parenthesis for complicated calculations $pack=2 * (10 % 7); print "a $pack pack"; // prints: a 6 pack
PHP doesn't make a distinction between numeric and string comparison operators. Numeric test operators Assume $X = 5 *Remember ‘=‘ (one equal sign) is the assignment operator which assigns a value to a variable. • An overview of the numeric test operators: • ==: equal • !=: not equal • <: less than • <=: less than or equal to • >: greater than • >=: greater than or equal to • All these operators can be used for comparing two numeric values in an if condition.
Increment/decrement • Increment/decrement operators, which are essentially shorthand ways of adding or subtracting one from a number: $a = 5; $a++; // $a has been incremented by 1, and now equals 6 $a--; // $a has been decremented by 1, and now equals 5 $b = 5 * $a++; // Note that the incrementing happens after the evaluation: // First, $b is calculated to be 25. Then, $a is incremented to become 6 // If you want $a to be incremented first, put the ++ in front of it // as follows: $b = 5 * ++$a; // $a incremented to 7; $b becomes 35 $c = 100; $c -= ++$b + $a++; // $b becomes 36; $c is calculated to be // 100 - ( 36 + 7 ); finally, $a becomes 8
Booleans • Every expression in PHP has a Boolean value. • It is either 'true' or 'false'. • For example if(expression) is true, Process expression1 otherwise Processexpression2
What is truth? • All strings are true except • the empty string • the string "0“ • All numbers are true except • 0 • 0.0 • Example: $a=5-4-1; // $a is false • Note that variables that you have not assigned contents are false. This includes misspelled variables!!
Useful Tools: print_r(), var_dump() • You can easily output variable types and their values with print_r(), var_dump() • These functions are very useful for debugging your programs • print_r() displays just the value, var_dump() displays the type and value • Note: use the <pre> and </pre> HTML tags to format the output from these functions.
Useful Tools: isset() • isset() is a function that returns true if a variable is set. • Under strict coding rules, the PHP processor will issue a notice when you use a variable that has not been set to a value. • isset($variable) can be used to find out if the variable variable was set before using it.
Comparison operators Expressions that are evaluated in Boolean often use comparison operators. $beer == 'budweiswer' ; // checks for equality Note difference from $beer=' budweiser' ; // this is always true • operators: • ==: equal • !=: not equal • <: less than • <=: less than or equal to • >: greater than • >=: greater than or equal to
Logical operators • ‘and’ is logical AND. ‘or’ is logical OR. if($brand=='Budweiser' or $brand="Sam Adams") { print "Commiserations for buying a lousy beer\n"; } # where is the mistake in this piece of code? • ‘!’ is Boolean NOT • These can be combined. Use parenthesis if((($pints) > 2 and ($vehicle=='car')) or (($pints > 6) and ($vehicle=='bicycle'))) { print "order a cab!\n"; } • Truth expressions • three logical operators: • and: and (alternative: &&) • or: or (alternative: ||) • not: not (alternative: !)
What is "Flow of Control"? • Flow of Control is the execution order of instructions in a program • All programs can be written with three control flow elements: 1. Sequence - just go to the next instruction 2. Selection - a choice of at least two either go to the next instruction or jump to some other instruction 3. Repetition - a loop (repeat a block of code) at the end of the loop either go back and repeat the block of code or continue with the next instruction after the block • Selection and Repetition are called Branching since these are branch points in the flow of control
PHP Flow Control Statements Sequential • the default • PHP automatically executes the next instruction unless you use a branching statement Branching: Selection • if • if-else • if-else if-else if- … - else • switch Branching: Repetition • while • do-while • for • foreach
if( condition ) { } • if( condition ) evaluates an expression condition as Boolean, and executes a block of code surrounded by curly brackets if the expression is true. if($drunk) { print "Don't drive!\n"; } • Note you don't need to indent the block as done above, but it is good for readability . • Simple decisions • Do the next statement if test is true or skip it if false • Syntax: if (Boolean_Expression) Action if true; //execute if true next action; //always executed
if( condition ) {} else {} • if you have an if() you can add an else block of code to execute when the condition is false if($sober) { print "You can drive\n"; } else { print "Check if you are fit to drive\n"; } • Select either one of two options • Either do Action1 or Action2, depending on test value • Syntax: if (Boolean_Expression) { Action1 //execute only if Boolean_Expressiontrue } else { Action2 //execute only if Boolean_Expressionfalse } Action3 //anything here always executed
elseif( condition ) { } • You can build chain of conditions if($pints_drunk==0) { print "You are ok to drive\n"; } elseif($pints_drunk<3) { print "Don't use the car, get on your bike\n"; } elseif($pints_drunk<=6) { print "Take a cab home\n"; } else { print "Call the local hospital!\n"; } • One way to handle situations with more than two possibilities • Syntax: if(Boolean_Expression_1) Action_1 elseif(Boolean_Expression_2) Action_2 . . . elseif(Boolean_Expression_n) Action_n else Default_Action
while( condition ) { } • while( condition ) { } executes a piece of code while the condition conditionis true $count=0; while($count < 100) { print "Incrementing the Count<br/>"; $count=$count+1; # don't forget to increment $count! }
Control structures • Beyond the basic if..else structure, there are loops. Loops bring the power of automation to your script. • #print numbers 1-10 in three different ways • $i = 1; • while ($i<=10) { • print "$i\n"; • $i++; • } • for ($i=1;$i<=10;$i++) { • print "$i\n"; • } • foreach$i (1,2,3,4,5,6,7,8,9,10) { • print "$i\n"; • } switch($profRel) { case "colleague" : $greeting = "Thomas"; break; case "friend" : $greeting = "Tom"; break; case "grad student" : $greeting = "TC"; break; case "undergrad student" : $greeting = "professor"; break; default : $greeting = "Dr. Collins"; break; }
Form Handling • Forms are used to get information from users. HTML contains tags that allow you to create forms, and the Hypertext Transfer Protocol (HTTP) has features that place information obtained from forms into specified variables, for use by PHP programs. Generally, a PHP program will process the form information, perhaps save some of the information in a file, and then output something to the user (e.g., in the simplest case, "Your information was received"). • Form: • <form action="<?=$PHP_SELF?>" method="POST">Your name: <input type=text name=name><br>You age: <input type=text name=age><br><input type=submit></form> • Output • Your name: • Your age:
Form Handling • Receiving Script for the form: • Hi <?echo $name?>. You are <?echo $age?> years old. • or • Hi <?echo $_POST['name'] ?>. You are <?echo $_POST['age'] ?> years old.
Form Field and PHP variable • When the form is passed to the PHP script named with the action= of the the <form> the form fields are accessible as PHP variables. • If name is the name of the field, and if the method is POST, the field is read as the variable$_POST['name']. • If name is the name of the field, and if the method is GET, the field is read as the variable $_GET['name'].