Serverside Webscripting [JLW322]

01.php.intro

PHP Introduction

PHP

  • Short for PHP: Hypertext Preprocessor
  • Scripting language
    • Loose syntax
    • Not compiled for distribution (cfr. Java), but interpreted at runtime
      • Therefore it's slower than compiled languages
  • Very popular on the internet
    • One of the first Serverside Scripting Languages (° 1995)
    • PHP plugins exist for nearly all web servers and OSes
    • e.g. Wordpress, Facebook, Wikipedia, etc.
  • Suffers from historical cruft & syntax inconsistencies

PHP Versions

  • Current versions:
    • 5.4.33 (*)
    • 5.5.16
    • 5.6.0 (new since August!)
  • Our code is PHP 5.4+ compliant
(*) Released Sep, 18 2014. The last planned release that contains regular bugfixes. All the consequent 5.4.* releases will contain only security-relevant fixes, for the term of one year.

Obtaining PHP: Combined

  • A preconfigured PHP is included in Wampserver / MAMP
    • Install one of these for this course
    • Follow these instructions afer installation
    • Be sure to add the PHP binary to your system's PATH
      • Windows: Add C:\wamp\bin\php\version\ to PATH via Computer Settings
      • OS X: Paste this on the Terminal: echo 'export PATH=/Applications/MAMP/bin/php/phpversion/bin/:$PATH' >> ~/.bash_profile
  • Shipped with most Unix/Linux distributions

Obtaining PHP: Manual

Configuring PHP

  • PHP can be configured via a file named php.ini
  • We'll take a closer look at this file when it's needed
  • Note: the php.ini shipped with Wampserver/MAMP is configured mostly correctly

Running PHP (1)

  • From the shell
    • Run php -a to get an interative shell at which you can type in PHP statements
      • cfr. the MySQL shell where you type in SQL statements (queries)
      • A ; ends a statement
      • Type quit or exit to leave the shell
      bramus$ php -a
      Interactive shell
      
      php > echo 'hello';
      hello
      php > quit
      bramus$

Running PHP (2)

  • From the shell (continued)
    • Run php -r "one line of PHP code" to run a single line of PHP code
      bramus$ php -r "echo 'hello' . PHP_EOL;"
      hello
      bramus$
    • Run php [-f] file.php to “execute” a file that contains PHP code
      • You must wrap your PHP code between <?php and ?>
      • The closing ?> is optional.
      <?php
      	echo 'hello' . PHP_EOL;
      ?>
      bramus$ php cli-example.php
      hello
      bramus$

Running PHP (3)

  • In a web context
    • Give your file a .php extension and the PHP interpreter will interpret the file
      • The webserver must of course be configured to do so
    • PHP 5.4+ ships with a built-in webserver which can be started from anywhere
      php -S localhost:8080
      • All PHP files in that folder will be served

PHP Variables

Before we dive in

  • Strings are enclosed by ' or "
  • Use echo or print to output something onscreen.
    bramus$ php -a
    Interactive shell
    
    php > echo 'hello';
    hello
    php > echo('hello');
    hello
    php > print 'hello';
    hello
    php > print('hello');
    hello
    • The first example is the preferred syntax
  • Statements end in a ;
    php > echo 'hello'
    php > ;
    hello

Name, Value & Type

  • Variables have a name and a value
    • Variable names start with a $
    php > $a = 3;
    php > echo $a;
    3
  • Variables are of a certain type
    • Primitive types: boolean, integer, float (aka double), string
    • Combined types: Array, Object
    • Special types: resource, NULL
    • Pseudo types: mixed, number, callback

Dynamic & Weak typing

  • PHP is dynamically typed
    • When declaring a variable, you cannot specify the type. PHP will guess the data type when assigning a value
  • PHP is weakly typed
    • PHP will adjust the type of a var when a new value is assigned
      • This phenomenon is known as implicit type conversion or coercion
php > $a = 3;
php > echo gettype($a);
integer
php > $a = 'Hello';
php > echo gettype($a);
string
Note: Dynamic and weak typing are typical properties of scripting languages

Type casting

  • To enforce a variable being of a certain type, you must explicitly cast it to that type
    php > $a = 3;
    php > echo gettype($a);
    integer
    php > $a = (string) $a;
    php > echo gettype($a);
    string

A few pointers

  • PHP is case sensitive
    • $firstName and $firstname are not the same!
      php > $firstName = 'Bramus';
      php > echo $firstName;
      Bramus
      php > echo $firstname;
      
      Notice: Undefined variable: firstname in php shell code on line 1
  • To concatenate strings, you must use a .
    • When using a +, PHP will think you're adding numbers (weak typing!)
      php > $firstName = 'Bramus';
      php > $lastName = 'Van Damme';
      php > echo $firstName + ' ' + $lastName;
      0
      php > echo $firstName . ' ' . $lastName;
      Bramus Van Damme
      

Interpolation

  • Also known as Variable Substitution
  • When enclosed between ", PHP will try to substitute any string that could resemble a variable
    php > $firstName = 'Bramus';
    php > echo "variable: $firstName\n";
    variable: Bramus
    php > echo "variable: \$firstName\n";
    variable: $firstName
    php > echo 'variable: $firstName\n';
    variable: $firstName\n
    php > echo 'variable: \$firstName\n';
    variable: \$firstName\n
    php > echo 'variable: ' . $firstName . '\n';
    variable: Bramus\n
    php > echo 'variable: ' . $firstName . "\n";
    variable: Bramus
    php > echo 'variable: ' . $firstName . PHP_EOL;
    variable: Bramus
    • Course convention: always use ' to prevent interpolation
    • Course convention: always use PHP_EOL instead of "\n"

Arrays (1)

php > $arr = array();
php > $arr[] = 'se7en';
php > $arr[] = 123;
php > $arr[] = true;
php > echo $arr[1];
123
  • Declaration rule isn't mandatory but attests a good coding style
  • Mixing of types forms no problem
  • Automatic indexing
  • Index is numeric and sequential. We call this type of array a sequential array

Arrays (2)

  • It's possible to set the start index
php > $arr = array();
php > $arr[2] = 'se7en';
php > $arr[] = 123;
php > $arr[] = true;
php > echo $arr[3];
123

Arrays (3)

  • It's possible to set the indices/keys yourself
    php > $arr = array();
    php > $arr[2] = 'se7en';
    php > $arr[8] = 123;
    php > $arr[4] = true;
    php > echo $arr[8];
    123
  • Indices/keys can be strings too
    php > $arr = array();
    php > $arr['BE'] = 'Belgium';
    php > $arr['NL'] = 'The Netherlands';
    php > $arr['FR'] = 'France';
    php > echo $arr['BE'];
    Belgium
  • We call these associative arrays

Arrays (4)

  • It's possible to declare and initialize an array in one go
    php > $arr1 = array('Brussels', 'Ghent', 'Antwerp');
    php > $arr2 = array('NL' => 'The Netherlands', 'BE' => 'Belgium');
    php > $arr2 = array(
    php ( 'NL' => 'The Netherlands',
    php ( 'BE' => 'Belgium'
    php ( );
  • Since PHP 5.4 this is also possible
    php > $arr1 = ['Brussels', 'Ghent', 'Antwerp'];

Code Comments

Code Comments

  • Same as in Java
    // Single line comment
    
    /* Multi
    line
    comment
    */
    
    /**
     * Preferred way
     * to layout
     * multi-line
     * comments
     */

Selections, Iterations & Operators

Selections (1)

  • Same as in Java
    <?php
    
    	if ($condition) {
    		// do something
    	}
    
    	if ($condition) {
    		// do something
    	} else {
    		// do something else
    	}
    
    	switch ($var) {
    
    		case $value1:
    			// do something
    			break;
    
    		case $value2:
    			// do something
    			break;
    
    		default:
    			// do something
    
    	}

Selections (2)

  • Example
    <?php
    
    	$a = 7;
    	if ($a < 9) {
    		echo '$a is less than 9';
    	} else {
    		echo '$a is greater than 9';
    	}
    • Course convention: always place curly brackets
    • Course convention: place the curly brackets on the same line
    • Course convention: indent one TAB inside curly brackets

Selections (3)

  • When possible, use the ternary operator
    <?php
    
    	$a = 7;
    	echo (($a < 9) ? '$a is less than 9' : '$a is greater than 9');
  • Since PHP 5.3, the ternary operator has gotten smarter:
    <?php
    
    	echo $nickName ?: $firstName;
    • If $nickName is truthy then it will be outputted. If not $firstName will.

Iterations (1)

  • Again, same as in Java
    <?php
    
    	while ($condition) {
    		// do something
    	}
    
    	do {
    		// do something
    	} while ($condition);
    
    	for ($x = 0; $x < 5; $x++) {
    		// do something
    	}
    
    	foreach ($arr as $value) {
    		// do something
    	}
    
    	foreach ($arr as $key => $value) {
    		// do something
    	}
    • Also possible to use break; and continue;

Iterations (2)

  • Example
    php > for ($x = 1; $x <= 6; $x++) {
    php { echo 'Hello 2ICT' . $x . PHP_EOL;
    php { }
    Hello 2ICT1
    Hello 2ICT2
    Hello 2ICT3
    Hello 2ICT4
    Hello 2ICT5
    Hello 2ICT6
  • Example
    php > $countries = array('BE' => 'Belgium', 'NL' => 'The Netherlands');
    php > foreach ($countries as $key => $value) {
    php { echo $key . ' = ' . $value . PHP_EOL;
    php { }
    BE = Belgium
    NL = The Netherlands

Operators

  • Same as in Java
    • Relational operators: ==, !=, <, >, <=, >=
    • Logical operators: &&, ||, !, &, |
    • Post/pre- in/de-crement: $var--, $var++, --$var, ++$var
    • Math shorthands: +=, *=, …
  • Since PHP4 support for identical operators: check for both type and value to be equal
    php > $a = 13; // integer
    php > $b = 13.0; // double
    php > echo ($a == $b) ? 'equal' : 'not equal';
    equal
    php > echo ($a === $b) ? 'equal' : 'not equal';
    not equal

PHP Functions

Built-in Functions (1)

  • PHP has a lot of functions built-in
  • A few string-related functions
    • addslashes/stripslashessee 04.forms
    • ltrim/rtrim/trim — strips leading/trailing/enclosing whitespace
    • str_replace — replaces a part of a string with an other value
    • strip_tags — strips html from a string
    • strlen — returns the length of a string
    • strtolower/strtoupper — convert a string to uppercase/lowercase
    • substr — extract a part of a string
    • ...
How to use: see http://php.net/nameofthefunction

Built-in Functions (2)

  • A few math-related functions
    • ceil — round numerical values up
    • floor — round numerical values down
    • round — round numerical values mathematically
    • rand/mt_rand — generate a random number
    • sqrt — calculate the square root of a number
    • ...

Built-in Functions (3)

  • A few array-related functions
    • sizeof/count — get the size of an array
    • sort — sort an array
    • asort — sort an associative array
    • explode — split a string on a given delimiter and get an array
    • implode — opposite of explode
    • array_push — push an element onto an array
    • array_pop — get an element off the end of an array
    • array_key_exists — check if a key in an associative array exists
    • ...

Custom functions (1)

  • Same as in Java
    <?php
    
    	// Our chopStringEnd function
    	function chopStringEnd($str, $len, $ending) {
    		if (strlen($str) < $len) {
    			return $str;
    		} else {
    			return substr($str, 0, $len - strlen($str)) . $ending;
    		}
    	}
    
    	// Our variables
    	$origStr = '/Users/bramus/Dropbox/Kaho/Lesactiviteiten/Webscripting1';
    	$cutoffLength = 40;
    	$endStr	= '...';
    
    	// Go!
    	echo chopStringEnd($origStr, $cutoffLength, $endStr);

Custom functions (2)

  • Possible to define default values for function arguments
    <?php
    
    	// Our chopStringEnd function
    	function chopStringEnd($str, $len = 30, $ending = '---') {
    		if (strlen($str) < $len) {
    			return $str;
    		} else {
    			return substr($str, 0, $len - strlen($str)) . $ending;
    		}
    	}
    
    	// Our variables
    	$origStr = '/Users/bramus/Dropbox/Kaho/Lesactiviteiten/Webscripting1';
    	$cutoffLength = 40;
    	$endStr = '...';
    
    	// Go!
    	echo chopStringEnd($origStr, $cutoffLength, $endStr) . PHP_EOL;
    	echo chopStringEnd($origStr, $cutoffLength) . PHP_EOL;
    	echo chopStringEnd($origStr);

Custom functions (3)

  • Provide PHPDoc-style comments
    <?php
    
    	/**
    	 * Chops a string at the given length with the given ending
    	 *
    	 * @param	string 	$str 	The initial String
    	 * @param	int 	$len 	The length to chop off at
    	 * @param	string 	$ending	The ending to add
    	 *
    	 * @return	string 	The circumcised up string
    	 */
    	function chopStringEnd($str, $len = 30, $ending = '---') {
    		if (strlen($str) < $len) {
    			return $str;
    		} else {
    			return substr($str, 0, $len - strlen($str)) . $ending;
    		}
    	}
    
    	...
This way your IDE will tell you which params are needed, what type they need to be, etc.

Scoping

Problem

  • This won't work
    <?php
    
    	$host = 'http://www.myhost.com/';
    
    	function absUrl($relUrl) {
    		return $host.$relUrl;
    	}
    
    	echo absUrl('files/uploads/me.jpg');
  • Result
    Notice: Undefined variable: host in /Users/bramus/Dropbox/Kaho/Lesactiviteiten/.../assets/01/examples/scoping1.php on line 8
    files/uploads/me.jpg

How we would've fixed this in 1995

  • The global keyword to the rescue
    <?php
    
    	$host = 'http://www.myhost.com/';
    
    	function absUrl($relUrl) {
    		global $host;
    		return $host . $relUrl;
    	}
    
    	echo absUrl('files/uploads/me.jpg');
  • Don't ever do this; it's a bad programming style!

How we would've fixed this in 1998

  • Extra function argument
    <?php
    
    	$host = 'http://www.myhost.com/';
    
    	function absUrl($relUrl, $host) {
    		return $host . $relUrl;
    	}
    
    	echo absUrl('files/uploads/me.jpg', $host);
  • Extra function argument, revised
    <?php
    
    	function absUrl($relUrl, $host = 'http://www.myhost.com/') {
    		return $host . $relUrl;
    	}
    
    	echo absUrl('files/uploads/me.jpg');

How to properly fix it (since 2000)

  • Use define(), a function that shipped with PHP4
    <?php
    
    	define('HOST', 'http://www.myhost.com/');
    
    	function absUrl($relUrl) {
    		return HOST . $relUrl;
    	}
    
    	echo absUrl('files/uploads/me.jpg');
  • Course convention: always use define() to define global constants, never use the global keyword

How we can fix this since 2009

  • Since PHP 5.3 it's possible to use the use keyword to inject a variable into a function
    <?php
    
    	$host = 'http://www.myhost.com/';
    
    	$absUrl = function ($relUrl) use ($host) {
    		return $host . $relUrl;
    	};
    
    	echo $absUrl('files/uploads/me.jpg');
  • This syntax is mostly used when working with callback functions. We'll stick to using define() for now.
Note: alternative function definition syntax required!

Errors and debugging

Before we dive in

  • When developing, make sure errors are shown on screen
  • Put this at the very top of your code:
    <?php
    
    	error_reporting(E_ALL); // = Report all errors
    	ini_set('display_errors', 'on'); // = Show the errors on screen
    	
  • These settings can also be set in the php.ini file

Suppress errors with @

  • It's possible, but it's not recommended as the script will continue execution
    <?php
    
    	function divide($numerator, $denominator) {
    		return $numerator / $denominator;
    	}
    
    	echo divide(1, 2) . PHP_EOL;	// 0.5
    	echo divide(1, 0) . PHP_EOL;	// "Warning: Division by zero"
    	echo @divide(1, 0) . PHP_EOL;	// (suppressed)
    	echo divide(1, 2) . PHP_EOL;	// 0.5
  • Later on, we'll learn how to work with Exception

Debugging helper functions

  • This won't work
    php > $arr = array('one', 'two', 'three');
    php > echo $arr;
    Array
  • Use print_r() and var_dump() instead to inspect variables
    php > print_r($arr);
    Array
    (
        [0] => one
        [1] => two
        [2] => three
    )
    php > var_dump($arr);
    array(3) {
      [0]=>
      string(3) "one"
      [1]=>
      string(3) "two"
      [2]=>
      string(5) "three"
    }

Real debugging

  • Using print_r() and var_dump() is no real debugging
  • Real debugging is possible with
    • Built-in IDE debugger
      (eg. Zend Studio/PHPStorm have one, Aptana had one)
    • External debugger, linked to IDE
      (eg. XDebug + Aptana/PHPStorm/Netbeans)

Dates in PHP

Timestamps

  • Epoch time
    • Numerical value: number of seconds since the epoch
      • epoch = Midnight January 1st, 1970 (GMT)
      • Not counting leap seconds
    • Also known as Unix time or Posix time
    • Dates expressed in Unix time are called timestamps
  • Allow one to precisely indicate a given point in time
    • 0 = January 1 1970, 00:00:00 GMT
    • 86400 = Januari 2 1970, 00:00:00 GMT
    • 31536000 = Januari 1 1971, 00:00:00 GMT
    • 440423100 = December 26 1983, 11:45:00 GMT
    • 946684800 = Januari 1 2000, 00:00:00 GMT
    • 1234567890 = February 13 2009, 23:31:30 GMT

Dates and PHP

  • Timestampfunctions in PHP
    • time() returns the number of seconds since the epoch
    • mktime() allows you to build a timestamp for a given hour, minute, second, month, day and year
  • Converting between dates and timestamps
    • strtotime(string $time, [int $now])
      • Convert a given date to a timestamp
      • $time is something like 2012-24-09 but can also be next friday
      • Second (optional) param used to calculate an offset
    • date(string $format, [int $timestamp])
      • Convert a given timestamp to a date
      • If $timestamp is empty, the current one is used

Date Format

  • The $format param needs to be built manually
    format character Description Example returned values
    d Day of the month, 2 digits with leading zeros 01 to 31
    D A textual representation of a day, three letters Mon through Sun
    l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
    w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
    F A full textual representation of a month, such as January or March January through December
    m Numeric representation of a month, with leading zeros 01 through 12
    M A short textual representation of a month, three letters Jan through Dec
    Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
    y A two digit representation of a year Examples: 99 or 03
    H 24-hour format of an hour with leading zeros 00 through 23
    i Minutes with leading zeros 00 to 59
    s Seconds, with leading zeros 00 through 59

Date Examples

  • Example 1
    <?php
    	echo date('l');
    	echo date('l jS \of F Y h:i:s A');
    	echo 'July 1, 2000 is on a ' . date('l', mktime(0, 0, 0, 7, 1, 2000));
  • Example 2
    <?php
    	// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
    	// Mountain Standard Time (MST) Time Zone
    	$today = mktime(17,16,18,3,10,2001);
    	date_default_timezone_set('America/Phoenix');
    
    	echo date('F j, Y, g:i a'); // March 10, 2001, 5:16 pm
    	echo date('m.d.y'); // 03.10.01
    	echo date('j, n, Y'); // 10, 3, 2001
    	echo date('Ymd'); // 20010310
    	echo date('h-i-s, j-m-y, it is'); // 05-16-18, 10-03-01, 1631 1618
    	echo date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
    	echo date('D M j G:i:s T Y'); // Sat Mar 10 17:16:18 MST 2001
    	echo date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
    	echo date('H:i:s'); // 17:16:18

Dates sidenote

CLI input/output

CLI Arguments

  • The CLI allows arguments being passed in
  • PHP automatically populates two vars: $argc and $argv
    <?php
    	echo 'Number of arguments ' . $argc . PHP_EOL;
    	foreach ($argv as $key => $value) {
    		echo 'Argument #' . $key . ' : ' . $value . PHP_EOL;
    	}
    bramus$ php cli-args1.php foo bar baz
    Number of arguments 4
    Argument #0 : args1.php
    Argument #1 : foo
    Argument #2 : bar
    Argument #3 : baz
Beware: $argc and $argv only available in CLI mode!

Named CLI Arguments (1)

  • You can also use named arguments if you want, but it gets a bit tricky
  • Version 1
    <?php
    	$args = getopt('ab:c::');
    	# nothing = don't accept any value (why? WHYYYY?)
    	# trailing : = required
    	# trailing :: = optional
    	var_dump($args);
    bramus$ php cli-args2.php -a -b 2 -c3
    array(3) {
      ["a"]=>
      bool(false)
      ["b"]=>
      string(1) "2"
      ["c"]=>
      string(1) "3"
    }

Named CLI Arguments (2)

  • Version 2
    <?php
    	$args = getopt('', array('a', 'b:', 'c::'));
    	# nothing = don't accept any value (why? WHYYYY?)
    	# trailing : = required
    	# trailing :: = optional
    	var_dump($args);
    bramus$ php cli-args3.php --a --b "2" --c=3
    array(3) {
      ["a"]=>
      bool(false)
      ["b"]=>
      string(1) "2"
      ["c"]=>
      string(1) "3"
    }

Interactive scripts

  • Use readline() to ask for input whilst the script is runnning
    <?php
    	$name = readline('What is your name? ');
    	$city = readline('Where do you live? ');
    	echo 'Hello ' . $name . ' from ' . $city . PHP_EOL;
    bramus$ php cli-interactive.php
    What is your name? Bramus
    Where do you live? Vinkt
    Hello Bramus from Vinkt

STDIN/STDOUT/STDERR (1)

  • PHP (in CLI mode) automatically opens some io streams
  • STDIN = input
    <?php
    	while(!feof(STDIN)) {
    		$line = trim(fgets(STDIN));
    		if(strlen($line) > 0) {
    			echo strrev($line).PHP_EOL;
    		}
    	}
    bramus$ cat cli-stdin-input.txt
    monkey
    elephant
    cow
    giraffe
    
    bramus$ cat cli-stdin-input.txt | php cli-stdin.php
    yeknom
    tnahpele
    woc
    effarig

STDIN/STDOUT/STDERR (2)

  • STDOUT/STDERR = output
    bramus$ php -r "fwrite(STDOUT, 'hello world');"
    hello world
    bramus$ php -r "fwrite(STDERR, 'hello world');"
    hello world
  • Difference between STDOUT and STDERR?
    bramus$ php -r "fwrite(STDOUT, 'stdout world') . fwrite(STDERR, 'stderr world');" > /dev/null
    stderr world

Interactive scripts, Revisited

  • Unfortunately readline() isn't available everywhere
    • On Unix PHP needs to be compiled with it enabled
    • On Windows it's not available at all
  • Fortunately we can knock up an alternative for that platform, using STDIN
    function getInput($question = '') {
    	if (!function_exists('readline')) {
    		echo $question . ' ';
    		return stream_get_line(STDIN, 1024, PHP_EOL);
    	} else {
    		return readline($question . ' ');
    	}
    }
    
    $name = getInput('What is your name?');
    $city = getInput('Where do you live?');
    echo 'Hello ' . $name . ' from ' . $city . PHP_EOL;

More CLI goodness

Check a file syntax

  • Check a file for syntax errors with php -l faulty.php
    <?php
    	echo $foo;
    	for ($x = 0; $x < 5; x++) {
    		echo $x;
    	}
  • PHP will tell you what went wrong and where
    bramus$ php -l faulty.php
    
    Parse error: parse error, expecting `')'' in faulty.php on line 4
    Errors parsing faulty.php
  • Handy if you link this to a precommit hook in Git to prevent you from committing faulty code

Check your PHP config

  • Check your PHP config by running php -i
    bramus$ php -i
    phpinfo()
    PHP Version => 5.4.24
    
    System => Darwin brm.local 13.3.0 Darwin Kernel Version 13.3.0: Tue Jun  3 21:27:35 PDT 2014; root:xnu-2422.110.17~1/RELEASE_X86_64 x86_64
    Build Date => Jan 19 2014 21:18:21
    Configure Command =>  '/private/var/tmp/apache_mod_php/apache_mod_php-87.2~1/php/configure'  '--prefix=/usr' '--mandir=/usr/share/man' '--infodir=/usr/share/info'...
  • If you don't have access to the shell of the machine, upload a file with these contents to it and load it via the browser
    <?php
    	phpinfo();

Other command options

  • Know your PHP version by running php -v
    bramus$ php -v
    PHP 5.4.24 (cli) (built: Jan 19 2014 21:32:15)
    Copyright (c) 1997-2013 The PHP Group
    Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
  • Convert a PHP file to a syntax highlighted HTML file with php -s file.php

Closing note: course conventions

Course conventions (1)

  • Code in English
  • Use the full PHP open tag <?php. The closing tag may be omitted
  • Develop with error_reporting() set to E_ALL and display_errors set to On
  • Develop without the XDebug extension (for now)
  • Correctly indent code
    • Within if-else,do-while,for/foreach, switch,...
    • Indent with a TAB, not a few spaces
  • Comment your code properly
    • Think of the code checking your code afterwards
    • Use PHPDoc-compliant comments

Course conventions (2)

  • Never use global but preferably use a constant/define
  • Use single quotes to delimit strings
  • Give variables and functions a clear name and use camelCasing
    • e.g. $numArticles, $firstName, calculateDistance(), etc.
    • Exception: counters in loops such as $x, $y
  • Curly braces always go on the same line as the keyword
  • Use identical operators when comparing variables/values with booleans or null
  • When necessary cast variables to prevent stupid errors
  • Never use $_REQUEST (see 04.forms)
  • When in doubt: check the domestic conventions or ask your lecturer

Questions?

Sources

ikdoeict.be