You are on page 1of 15

Lab 1 - PHP Basics Syntax Operators Variables Constants Control Structures Language Constructs and Functions

Lab 2 - Strings and Arrays Quoting Matching Extracting Searching Replacing Formatting HEREDOC and NOWDOC Enumerated Arrays Associative Arrays Multi-dimensional Arrays Array Iteration Array Functions Lab 3 - Functions, GET & POST Data, Forms and Errors Syntax Arguments References Returns Variable Scope Anonymous Functions (Closures) GET and POST Data HTML Forms Error and Exception Handling

Lab 4 - Object Oriented Programming Instance Methods & Properties Class Definition Instantiation Modifiers / Inheritance Abstracts Interfaces Exceptions Static Methods & Properties Autoload Type Hinting Class Constants Magic Methods Exceptions Class

Lab 5 - Date, Time and Filesystem Functions Date and Time Functions Filesystem Functions Reading and Writing Handling File Uploads

Lab 6 - Databases and PDO SQL Joins Analyzing Queries Prepared Statements Transactions PDO

Lab 7 - Sessions and Cookies Sessions Cookies HTTP Headers and Codes HTTP Authentication

Lab 8 - XML and Web Services XML Basics XML Extension SimpleXML Xpath DOM Web Services Basics

Lab 9 Security PHP Configuration (php.ini) Session Security Cross-Site Scripting Cross-Site Request Forgeries SQL Injection Remote Code Injection Input Filtering Escape Output Encryption, Hashing Algorithms

1. 1.1 1.2 1.3

Php basic Syntax Escaping from HTML Instruction separation Comments

1.1 Escaping from HTML When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the time you will see PHP embedded in HTML documents, as in this example. <p>This is going to be ignored.</p> <?php echo 'While this is going to be parsed.'; ?> <p>This will also be ignored.</p> You can also use more advanced structures: <?php if ($expression) { ?> <strong>This is true.</strong> <?php } else { ?> <strong>This is false.</strong> <?php This works as expected, because when PHP hits the ?> closing tags, it simply } starts outputting whatever it finds (except for an immediately following newline - see instruction ?> separation ) until it hits another opening tag. The example given here is contrived, of course, but for outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo() or print(). There are four different pairs of opening and closing tags which can be used in PHP. Two of those, <?php ?> and <script language="php"> </script>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended. Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards. 1. <?php echo 'if you want to serve XHTML or XML documents, do it like this'; ?> 2. <script language="php"> echo 'some editors (like FrontPage) don\'t like processing instructions'; </script> 3. <? echo 'this is the simplest, an SGML processing instruction'; ?> <?= expression ?> This is a shortcut for "<? echo expression ?>" 4. <% echo 'You may optionally use ASP-style tags'; %> <%= $variable; # This is a shortcut for "<% echo . . ." %>

While the tags seen in examples one and two are both always available, example one is the most commonly used, and recommended, of the two. Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if PHP was configured with the -enable-short-tags option. ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini configuration file directive. 1.2 Instruction separation As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present. <?php echo 'This is a test'; ?> <?php echo 'This is a test' ?> <?php echo 'We omitted the last closing tag';

Note: The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files. 1.3 Comments PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example: <?php echo 'This is a test'; // This is a one-line c++ style comment /* This is a multi line comment yet another line of comment */ echo 'This is yet another test'; echo 'One Final Test'; # This is a one-line shell-style comment ?> The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn't break out of PHP mode in a one-line comment. <h1>This is an <?php # echo 'simple';?> example</h1> <p>The header above will say 'This is an example'.</p>

'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.

<?php /* echo 'This is a test'; /* This comment will cause a problem */ */ ?>

2. Php basic Operators

2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12

Operator Precedence Arithmetic Operators Assignment Operators Bitwise Operators Comparison Operators Error Control Operators Execution Operators Incrementing/Decrementing Operators Logical Operators String Operators Array Operators Type Operators

An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression). Operators can be grouped according to the number of values they take. Unary operators take only one value, for example ! (the logical not operator) or ++ (the increment operator). Binary operators take two values, such as the familiar arithmetical operators+ (plus) and - (minus), and the majority of PHP operators fall into this category. Finally, there is a single ternary operator, ? :, which takes three values; this is usually referred to simply as "the ternary operator" (although it could perhaps more properly be called the conditional operator). A full list of PHP operators follows in the section Operator Precedence. This also explains operator Presedence and Associativity, which govern exactly how expressions containing several different operators are evaluated.

2.1

Operator Precedence

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+")

operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. When operators have equal precedence, their associativity decides whether they are evaluated starting from the right, or starting from the left - see the examples below. The following table lists the operators in order of precedence, with the highestprecedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides the order of evaluation. Operator Precedence Operators clone new [ ++ -~ - (int) (float) (string) (array) (object) (bool) @ instanceof ! */% +-. << >> < <= > >= <> == != === !==

Associativity nonassociative left nonassociative right nonassociative right left left left nonassociative nonassociative left left left left left left right left left left left For left

Additional Information clone and new array() increment/decrement types types logical arithmetic arithmetic and string bitwise comparison comparison bitwise and references bitwise bitwise logical logical ternary assignment logical logical logical many uses evaluation proceeds from

& ^ | && || ?: = += -= *= /= .= %= &= |= ^= <<= >>= => and xor or , operators of equal precedence, left associativity means that to right, and right associativity means the opposite.

<?php $a = 3 * 3 % 5; // (3 * 3) % 5 = 4 $a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2 $a = 1; $b = 2; $a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5 // mixing ++ and + produces undefined behavior $a = 1; echo ++$a + $a++; // may print 4 or 5 ?>

Use of parentheses, even when not strictly necessary, can often increase readability of the code. Note: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is2.2 into $a. put Arithmetic Operators Remember basic arithmetic from school? These work just like those. Arithmetic Operators Name Result Negation Opposite of $a. Addition Sum of $a and $b. Subtraction Difference of $a and $b. Multiplication Product of $a and $b. Division Quotient of $a and $b. Modulus Remainder of $a divided by $b.

Example -$a $a + $b $a - $b $a * $b $a / $b $a % $b

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned. Operands of modulus are converted to integers (by stripping the decimal part) before processing. The result of the modulus operator % has the same sign as the dividend that is, the result of $a % $b will have the same sign as $a. For example: <?php echo echo echo echo ?> (5 % 3)."\n"; // prints 2 (5 % -3)."\n"; // prints 2 (-5 % 3)."\n"; // prints -2 (-5 % -3)."\n"; // prints -2

2.3

Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to"). The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things: <?php $a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4. ?>

For arrays, assigning a value to a named key is performed using the "=>" operator. The precedence of this operator is the same as other assignment operators. In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example: <?php $a $a $b $b ?> Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword. Assignment by Reference Assignment by reference is also supported, using the "$var = &$othervar;" syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere. Example #1 Assigning by reference <?php $a = 3; $b = &$a; // $b is a reference to $a print "$a\n"; // prints 3 print "$b\n"; // prints 3 $a = 4; // change $a print "$a\n"; // prints 4 print "$b\n"; // prints 4 as well, since $b is a reference to $a, which has // been changed ?> As of PHP 5, the new operator returns a reference automatically, so assigning the result of new by reference results in an E_DEPRECATED message in PHP 5.3 and later, and an E_STRICT message in earlier versions. For example, this code will result in a warning: <?php class C {} /* The following line generates the following error message: * Deprecated: Assigning the return value of new by reference is deprecated in... */ $o = &new C; ?> = 3; += 5; // sets $a to 8, as if we had said: $a = $a + 5; = "Hello "; .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

2.4

Bitwise Operators

Bitwise operators allow evaluation and manipulation of specific bits within an integer.
Bitwise Operators Example $a & $b $a | $b $a ^ $b ~ $a $a << $b $a >> $b Name And Or (inclusive or) Xor (exclusive or) Not Shift left Shift right Bits that are set in Bits that are set in Bits that are set in Bits that are set in Shift the bits of $a "multiply by two") Shift the bits of $a "divide by two") Result both $a and $b are set. either $a or $b are set. $a or $b but not both are set. $a are not set, and vice versa. $b steps to the left (each step means $b steps to the right (each step means

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved. Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency. Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.

PHP's error_reporting ini setting uses bitwise values, providing a real-world demonstration of turning bits off. To show all errors, except for notices, the php.ini file instructions say to use: E_ALL & ~E_NOTICE

This works by starting with E_ALL: 00000000000000000111011111111111 Then taking the value of E_NOTICE... 00000000000000000000000000001000 ... and inverting it via ~: 11111111111111111111111111110111 Finally, it uses AND (&) to find the bits turned on in both values: 00000000000000000111011111110111

Another way to accomplish that is using XOR (^) to find bits that are on in only one value or the other: E_ALL ^ E_NOTICE error_reporting can also be used to demonstrate turning bits on. The way to show just errors and recoverable errors is: E_ERROR | E_RECOVERABLE_ERROR

This process combines E_ERROR 00000000000000000000000000000001 and 00000000000000000001000000000000 using the OR (|) operator to get the bits turned on in either value: 00000000000000000001000000000001

Example #1 Bitwise AND, OR and XOR operations on integers


<?php /* * Ignore the top section, * it is just formatting to make output clearer. */ $format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)' . ' %3$s (%4$2d = %4$04b)' . "\n"; echo <<<EOH --------- --------- -- --------result value op test --------- --------- -- --------EOH; /* * Here are the examples. */ $values = array(0, 1, 2, 4, 8); $test = 1 + 4;

echo "\n Bitwise AND \n"; foreach ($values as $value) { $result = $value & $test; printf($format, $result, $value, '&', $test); } echo "\n Bitwise Inclusive OR \n"; foreach ($values as $value) { $result = $value | $test; printf($format, $result, $value, '|', $test); } echo "\n Bitwise Exclusive OR (XOR) \n"; foreach ($values as $value) { $result = $value ^ $test; printf($format, $result, $value, '^', $test); } ?>

--------result --------Bitwise AND ( 0 = 0000) = ( 1 = 0001) = ( 0 = 0000) = ( 4 = 0100) = ( 0 = 0000) =

--------- -- --------value op test --------- -- --------( ( ( ( ( 0 1 2 4 8 = = = = = 0000) 0001) 0010) 0100) 1000) & & & & & ( ( ( ( ( 5 5 5 5 5 = = = = = 0101) 0101) 0101) 0101) 0101)

Bitwise Inclusive OR ( 5 = 0101) = ( 0 = 0000) ( 5 = 0101) = ( 1 = 0001) ( 7 = 0111) = ( 2 = 0010) ( 5 = 0101) = ( 4 = 0100) (13 = 1101) = ( 8 = 1000)

| | | | |

( ( ( ( (

5 5 5 5 5

= = = = =

0101) 0101) 0101) 0101) 0101)

Bitwise Exclusive OR (XOR) ( 5 = 0101) = ( 0 = 0000) ^ ( 4 = 0100) = ( 1 = 0001) ^ ( 7 = 0111) = ( 2 = 0010) ^ ( 1 = 0001) = ( 4 = 0100) ^ (13 = 1101) = ( 8 = 1000) ^

( ( ( ( (

5 5 5 5 5

= = = = =

0101) 0101) 0101) 0101) 0101)

Example #2 Bitwise XOR operations on strings <?php echo 12 ^ 9; // Outputs '5' echo "12" ^ "9"; // Outputs the Backspace character (ascii 8) // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8 echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0 // 'a' ^ 'e' = #4 echo 2 ^ "3"; // Outputs 1 // 2 ^ ((int)"3") == 1 echo "2" ^ 3; // Outputs 1 // ((int)"2") ^ 3 == 1 ?>

2.1

Comparison Operators

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons. Comparison Operators Example $a == $b $a === $b $a != $b $a <> $b $a !== $b $a $a $a $a < $b > $b <= $b >= $b Name Equal Identical Not equal Not equal Not identical Less than Greater than Less than or equal to Greater than or equal to TRUE if $a is TRUE if $a is type. TRUE if $a is TRUE if $a is TRUE if $a is same type. TRUE if $a is TRUE if $a is TRUE if $a is TRUE if $a is Result equal to $b after type juggling. equal to $b, and they are of the same not equal to $b after type juggling. not equal to $b after type juggling. not equal to $b, or they are not of the strictly less than $b. strictly greater than $b. less than or equal to $b. greater than or equal to $b.

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

<?php var_dump(0 == "a"); // 0 == 0 -> true var_dump("1" == "01"); // 1 == 1 -> true var_dump("10" == "1e1"); // 10 == 10 -> true var_dump(100 == "1e2"); // 100 == 100 -> true switch ("a") { case 0: echo "0"; break; case "a": // never reached because "a" is already matched with 0 echo "a"; break; } ?>

For various types, comparison is done according to the following table (in order).
Type of Operand 1 null or string bool or null object string, resource or number array array object Type of Operand 2 string anything object string, resource or number array anything anything Comparison with Various Types Result Convert NULL to "", numerical or lexical comparison Convert to bool, FALSE < TRUE Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation Translate strings and resources to numbers, usual math Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example) array is always greater object is always greater

Example #1 Transcription of standard array comparison <?php // Arrays are compared like this with standard comparison operators function standard_array_compare($op1, $op2) { if (count($op1) < count($op2)) { return -1; // $op1 < $op2 } elseif (count($op1) > count($op2)) { return 1; // $op1 > $op2 } foreach ($op1 as $key => $val) { if (!array_key_exists($key, $op2)) { return null; // uncomparable } elseif ($val < $op2[$key]) { return -1; } elseif ($val > $op2[$key]) { return 1; } } return 0; // $op1 == $op2 } ?>

Ternary Operator
Another conditional operator is the "?:" (or ternary) operator. Example #2 Assigning a default value <?php // Example usage for: Ternary Operator $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; // The above is identical to this if/else statement if (empty($_POST['action'])) { $action = 'default'; } else { $action = $_POST['action']; } ?>

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE. Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. Not: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a returnby-reference function will therefore not work and a warning is issued in later PHP versions. Not: It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious: Example #3 Non-obvious Ternary Behaviour <?php // on first glance, the following appears to output 'true' echo (true?'true':false?'t':'f'); // however, the actual output of the above is 't' // this is because ternary expressions are evaluated from left to right // the following is a more obvious version of the same code as above echo ((true ? 'true' : false) ? 't' : 'f'); // here, you can see that the first expression is evaluated to 'true', which // in turn evaluates to (bool)true, thus returning the true branch of the // second ternary expression. ?>

You might also like