Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Web programming - PHP Part I.

Web programming - PHP Part I.

University of Stavanger, DAT310

Krisztian Balog

February 22, 2016
Tweet

More Decks by Krisztian Balog

Other Decks in Programming

Transcript

  1. PHP - Originally stood for Personal Home Page - It

    now stands for PHP: Hypertext Preprocessor - which is a recursive backronym - Used on ~40% of all websites - E.g., large part of Facebook’s front-end is written in PHP
  2. Executed on the server - Client-server architecture Client Server HTTP

    request HTTP response file’s extension must be .php # Web server knows from the extension # that it has to use a PHP interpreter: LoadModule php5_module "c:/php/php5apache2.dll" AddType application/x-httpd-php .php Internet
  3. Local development - Need WAMP/MAMP running - You can also

    use an online try-it editor for today’s exercises - E.g., http://phptester.net/ Both the client and the server run on the same machine. No internet connection needed. Client Server HTTP request HTTP response Your machine http://localhost refers to the web server running on your local machine
  4. Files and editor - The PHP files need to be

    placed under your www root folder - PhpStorm is being installed in the PC room - You can use Atom - https://atom.io/
  5. Mixing with HTML - Code embedded in between <?php …

    ?> - File must have .php extension! - In general, mixing HTML and PHP code is bad practice — use templating engines (coming later) <html> […] Today is: <?php echo date("Y-m-d H:i:s"); ?> […] </html>
  6. Output to screen - We use the echo statement -

    Has no return value - Can be used both with and without parentheses: echo or echo() - Marginally faster than print echo "something";
  7. General syntax - Very similar to C, and Perl (and

    JavaScript) - Reserved words - function, if, this, echo, break, return, … - End lines with ; - Comments - // single line - /*
 multi-line
 */
  8. Control statements - if if ($a > $b) { echo

    "a is greater than b"; } else { echo "b is greater than a"; }
  9. Control statements - switch switch ($color) { case "red": //

    do something break; case "green": // do something else break; default: // default case }
  10. Control statements - loops for ($i = 0; $i <

    10; $i++) { echo $i; } $i = 0; while ($i < 10) { echo $i; $i++; }
  11. Functions - Syntax function functionName() {
 // code to be

    executed
 } - Note: function names are not case-sensitive - Arguments separated with a comma function functionName($arg1, $arg2) { - Arguments can have default values function functionName($arg1, $arg2=50) {
  12. Declaring variables - Always implicitly - PHP has no command

    for declaring a variable - Start with $ - Variable is created the first time it’s used $name = "John"; $age = 28; - Type is determined by the interpreter - Variable names are case-sensitive
  13. Types - Integer - Float - String - Boolean -

    Array - Object - null (reserved word)
  14. Variable scope - declared outside a function => global scope

    - declared within a function => local scope - global keyword is used to access a global variable within a function function myTest() {
 global $x;
 […]
 }
  15. Constants - Once defined, cannot be changed or undefined -

    Constants are automatically global across the entire script - Convention is to use UPPERCASE for constants define("DB_SERVER", "localhost"); define("DB_USERNAME", "balog");
  16. Operators
 http://www.w3schools.com/php/php_operators.asp - Arithmetic operators - +, -, *, /,

    %, ** - Assignment operators - =, +=, -=, *=, .=, … - Comparison operators - ==, <, >, !=, >=, <=, <>, … - Logical operators - &&, ||
  17. Strings
 http://www.w3schools.com/php/php_ref_string.asp - Both single and double quotes can be

    used
 "John" 'August' - Concatenation
 $str = "two " . "words"; - Length
 strlen("two"); // 3 - Interpreted strings — works only with " quotes!
 $name = "John"; 
 $str = "Hello $name";

  18. - Substring
 substr("Hello world!", 1, 2); // el - Searching

    for substring
 strpos("Hello world!", "world"); // 6 - Replacing text within a string
 str_replace("world", "Dolly", "Hello world!"); // Hello Dolly! - Lowercasing/uppercasing
 strtolower("Dolly"); // dolly
 strtoupper("Dolly"); // DOLLY
 Strings
 http://www.w3schools.com/php/php_ref_string.asp
  19. Types of arrays 1. Indexed arrays: Arrays with a numeric

    index 
 $numbers = array(1, 2, 3, 4, 5); echo $numbers[0]; // 1 echo $numbers[4]; // 5
 2. Associative arrays: Arrays with named keys 
 $colors = array( "red" => "#ff0000", "green" => "#00ff00", "blue" => "#0000ff" ); echo $colors["red"]; // #ff0000 echo $colors["blue"]; // #0000ff
  20. Types of arrays (2) 3. Multidimensional arrays: Arrays containing one

    or more arrays $marks = array( "Robert" => array( "math" => "A", "physics" => "B" ), "Sarah" => array( "math" => "C", "chemistry" => "B", "literature" => "A" ), ); echo $marks["Robert"]["math"]; // A echo $marks["Sarah"]["chemistry"]; // B
  21. Working with indexed arrays - Iterating 
 $vect = array(3,

    2, 4, 1);
 for ($i = 0; $i < count($vect); $i++) { echo $vect[$i] . " "; } // Output: 3 2 4 1 - Sorting - From low to high: sort($vect); - From high to low: rsort($vect);
  22. Associative arrays - Iterating 
 $arr = array( "lemon" =>

    3, "orange" => 2, "banana" => 4, "apple" => 1 ); 
 foreach ($arr as $key => $value) { echo "(" . $key . ": " . $value . ") "; } // Output: (lemon: 3) (orange: 2) 
 // (banana: 4) (apple: 1)
  23. Associative arrays (2) - Sorting - By key - From

    low to high: ksort($arr); 
 // apple => 1, banana => 4, lemon => 3, orange => 2 - From high to low: krsort($arr);
 // orange => 2, lemon => 3, banana => 4,,apple => 1 - By value - From low to high: asort($arr); 
 // apple => 1, orange => 2, lemon => 3, banana => 4 - From high to low: arsort($arr);
 // banana => 4, lemon => 3, orange => 2, apple => 1
  24. Objects - Syntax class myClass { const CONSTANT = 'constant

    value'; public $name; public $age; private $_id; function __construct($name, $age) { $this->name = $name; $this->age = $age; $this->_id = 123; } […] }
  25. Objects - Syntax class Person { […] } - Member

    variables and constants (i.e., properties) class Person { const CONSTANT = "beer"; public $name; public $age; private $_id;
  26. Creating objects - Constructor function __construct($name, $age) { $this->name =

    $name; $this->age = $age; $this->_id = 123; } - Creating a new object $c = new Person("John", 32);
  27. Methods - Syntax: $obj->methodName($args);
 class Person { […]
 function getName()

    {
 return $this->name;
 }
 
 $c = new Person("John", 32);
 echo $c->getName(); // John
  28. Static methods - Syntax: ClassName::methodName($args);
 class Person { […]
 static

    function saySomething() { echo self::CONSTANT; }
 
 Person::saySomething(); // echos “beer”
  29. Visibility (variables and methods) - public — can be accessed

    everywhere - Methods declared without explicit visibility are public - Class constants are always public (cannot be made private or protected) - private — can only be accessed by the class that declared it - By convention, variables/methods are prefixed with _ - For example: private $_value; private function _dosomething($param) { … } - protected — an be accessed only within the class itself and by inherited classes
  30. :: vs. ->, self vs. $this - If the variable

    or method being referenced is declared as const or static, then you must use the :: operator, otherwise use -> - If you are accessing a const or static variable or method from within a class, then you must use the self-reference self - If you are accessing a variable or method from within a class that is not const or static, then you must use the self- referencing variable $this
  31. date() function - date() function - Returns date/day/month/year/day-of-week/… as a

    string - If you don’t specify a timestamp, the current date and time will be used - Use the mktime() function to get the Unix timestamp for a date - See - http://php.net/manual/en/function.date.php - http://www.w3schools.com/php/php_date.asp $d = mktime(11, 14, 54, 8, 12, 2014); echo date("Y-m-d h:i:s", $d); // 2014-08-12 11:14:54
  32. More on Date/Time - DateTime class - Represents date and

    time - You can do math on them, e.g., calculate difference - See http://php.net/manual/en/class.datetime.php - Calendar functions - Day of week, number of days in a month, etc. - See http://php.net/manual/en/ref.calendar.php
  33. Remember - These two produce the same <h1>Days: <?php echo

    $days; ?></h1> - and <?php echo"<h1>Days: ". $days; ."</h1>"; ?>
  34. HTTP requests - GET request - Variables are passed in

    the URL - E.g., http://localhost/myscript.php?name=John&age=12 - Works both with links (<a href=…>) and forms - POST request - Variables are passed in the request body - Works only with forms
  35. Form handling in PHP - Global variables $_GET, $_POST and

    $_REQUEST contain the input variables as associative arrays - $_GET is when HTTP method GET is used - $_POST is when HTTP method POST is used - $_REQUEST is for both GET and POST methods - Avoid using $_REQUEST unless you know what you’re doing!
  36. Example <form action="formhandler.php" method="GET"> <label>Name: <input type="text" name="name"></label><br /> <label>Age:

    <input type="text" name="age"></label><br /> […] </form> echo $_GET['name']; // John
 echo $_GET['age']; // 32 <form action="formhandler.php" method="POST"> <label>Name: <input type="text" name="name"></label><br /> <label>Age: <input type="text" name="age"></label><br /> […] </form> echo $_POST['name']; // John
 echo $_POST['age']; // 32
  37. Handling form input - Referencing $_GET['xxx'] or $_POST['xxx'] will raise

    a NOTICE if variable xxx is not provided - echo $_GET['page']; - Notice: Undefined index: page in …/index.php
  38. Handling form input (2) - Solution: use isset() to check

    if $_GET['xxx'] (or $_POST['xxx']) is set $page = ""; if (isset($_GET['page'])) { $page = $_GET['page']; } echo $page; - A more compact solution: $page 
 = isset($_GET['page']) ? $_GET['page'] : "";
  39. Separating PHP code to multiple files - <?php include "time.inc.php";

    ?> - Convention to use .inc.php extensions - Generally means that a file is to be included and does not make a standalone script in itself include vs. require - Included file is executed immediately!
  40. include, require, require_once - include and require are identical, except

    upon failure: - include will only produce a warning (E_WARNING) and the script will continue - require will produce a fatal error (E_COMPILE_ERROR) and stop the script - require_once will check if the file has already been included and, if so, will not require it again - Functions cannot be redeclared - To avoid errors on subsequent inclusion
  41. PHP error levels
 http://php.net/manual/en/errorfunc.constants.php - error_reporting() sets which errors are

    shows - show all errors in dev environment Constant Description E_ERROR Fatal run-time errors, cannot be recovered. Execution of the script is halted. E_WARNING Run-time warnings (non-fatal errors). Execution of the script is not halted. E_PARSE Compile-time parse errors. E_NOTICE Run-time notices. The script encountered something that could be an error. E_ALL All errors and warnings
  42. PHP error levels - error_reporting() sets which errors are shows

    - show all errors in dev environment ini_set("display_errors", 1); error_reporting(E_ALL); - don’t show but log errors in production env. ini_set("display_errors", 0); ini_set("log_errors", 1); // Define where do you want the log to go ini_set("error_log", "syslog");
  43. Remembering form input 
 (pseudo code) - Process input values

    - If the form has been submitted - Check input values - If error - Display form with input values remembered - Else - Process form (confirmation page, save to database, etc.) - Else - Display form for the first time (i.e., empty form)
  44. Exercise #12 skeleton // read in form values
 $name =

    get_value_post("name");
 […]
 
 // check if the form has been submitted
 if ($submitted) {
 // check for errors
 $errors = array(); […] 
 
 if (count($errors) > 0) {
 display_form($name, $email, $year, $month, $day, $sex, $terms, $errors);
 }
 else {
 confirm($name, $email, $year, $month, $day, $sex);
 }
 }
 else {
 // display form for the first time
 display_form();
 }