Post on 18-Jan-2016
PHP 1
PHPA very brief introduction
PHP 2
PHP
• PHP = PHP: Hypertext Processor• A recursive acronym!
• PHP scripts are executed on the server side• Executed by (a plugin to) an
application server• An HTTP server + more
• We will use the Apache HTTP server
• PHP can help developers make dynamic web pages• As opposed to static web pages
• PHP is open source
• PHP competitors• Microsoft ASP.NET• Oracle JavaServer Faces (JSF)• Python• Ruby on Rails• … many others
PHP 3
Application stacks• Application stack
• Application server + Database + programming language
• AMP stack• Apache, MariaDB/MySQL, PHP• LAMP = Linux + AMP• WAMP = Windows + AMP• XAMP = any OS + Amp
• We will use XAMP
• MEAN stack• MongoDB, Express JS, Angular JS, Node JS
• Microsoft• IIS, Microsoft SQL Server, ASP.NET
PHP 4
PHP basic syntax
• PHP is (small) pieces of code written inside ordinary HTML• …. <body> <?php echo date("r") ?> …</body> …• <?php PHP code ?>• The PHP code is executed by the application server.• The resulting (echo) HTML etc. is sent to the client.• The PHP code is not sent to the client• Browsers cannot execute PHP
• PHP comments• // The rest of the line is a comment• /* multi-line comment …. */
PHP 5
PHP variables• PHP variables start with $
• <?php$txt = "Hello world!";$x = 5;$y = 10.5;?>
• A variable can have a short name (like x and y) or a more descriptive name (age, carName, total_volume).• Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the variable• A variable name must start with a letter or the underscore character• A variable name cannot start with a number• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )• Variable names are case-sensitive ($age and $AGE are two different variables)• Source http://www.w3schools.com/php/php_variables.asp
PHP 6
PHP data types
• Variables can store data of different types, and different data types can do different things.• PHP supports the following data types:
• String “content of the string”• Integer• Float (floating point numbers - also called double)• Boolean: true, false• Array• Object• NULL• Resource• Arrays
PHP 7
Type systems
• Strongly typed language• Each variable, identifier, etc. has a type• Variable etc. do not change type at run-
time• Explicit type conversion• C#, Java
• Weakly typed language• Variables, etc. may have a type• Variables, etc. can change type at run-
time• Type conversion generally not needed• PHP, JavaScript• Example: phpTypes
• Static type checking• Types are checked at compile-time• Bugs are caught early• C#, Java
• Dynamic type checking• Types are checked at run-time• Bugs are caught late
• Help from IDEs• IDES like Visual Studio, NetBeans,
etc. provide more help for programmers of a strongly + statically typed language.
PHP 8
PHP forms
• A form is a place for the user to submit some data to the system.• Usually 2 pages are involved• The page with the input form• Another page to handle the input• Example: firstform
PHP 9
PHP super globals
• PHP offers a number of so-called super globals.• They are defined automatically
• Examples• $_POST: Access to data from forms send with the POST HTTP method
• $name = $_POST[“name”];• $_GET: Access to data from forms send with the GET HTTP method• http://www.w3schools.com/php/php_superglobals.asp
PHP 10
PHP conditions
• If statements• Similar to C#, with an extra elseif• If• If … else• If … elseif• http://www.w3schools.com/php/php_if_else.asp
• Switch statement• Similar to C#• http://www.w3schools.com/php/php_switch.asp
PHP 11
PHP loops
• While and do … while• Similar to C#• While has test at the entry• Do … while has test at the exit
• At least one turn in the loop• http://www.w3schools.com/php/php_looping.asp
• For and foreach• Similar to C#• Foreach element in an arrays• http://www.w3schools.com/php/php_looping.asp
PHP 12
PHP functions
• Comparable to C# methods• Functions can return a value• Many API functions return
• False if there is no proper result• In C# the method would throw an exception
• Something of a different type if there is a proper result
• Functions can have parameters• Functions can have local variables• Only visible inside the function (like C# methods)
• Example: phpTypes
PHP 13
PHP classes
• PHP classes are similar to C# classes• Private + public fields• Private + public functions• Constructors• The syntax for referring to member (field or function) is slightly different
• C# obj.method(param)• PHP obj -> function(param)
• Example: ClassExample
PHP 14
PHP arrays
• Stores multiple values in a single variable• Basic syntax (http://www.w3schools.com/php/php_arrays.asp)
• <?php$cars = array("Volvo", "BMW", "Toyota");echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";?>
• Iteration• foreach ($array as $value) {
code to be executed;}
• Three types of arrays• Indexed arrays: Indexes 0, 1, 2, …• Associative arrays: (key, value)-pairs
• Alias Map alias Dictionary• Multi-dimensional arrays: arrays containing arrays
PHP 15
PHP exception handling
• Syntax• Try { …. }• Catch (Exception ex)
• Throw new Exception(“….”);
• Similar to C#
• Exception classes• Class MyException extends
Exception { … }
PHP 16
Cookies in HTTP
• Cookies are part of the HTTP standard.• Cookies are small pieces of information
• Generated on the server and send to the client in a response
• Stored on the client• Sent back to the same server in sub-
sequent requests
• HTTP state• The server is stateless• The client can store state as cookies
• Cookie content• Name, value, expiration, domain, etc.
• Cookies can be attached to all kinds of documents• Text, CSS, images, even 1x1 pixel
images!
• Usages• To identify users
• ID cookie: Used as a key to a database on the server side
• Users preferences, etc.
• Watch your cookies • Firefox: Options -> Privacy ->
remove individual cookies
PHP 17
Cookies in PHP
• Set cookie• Setcookie(name, value, expiration)• Make a new cookie• Change an existing cookie
• Same name
• Get the value of a cookie• $_COOKIE[$cookie_name]
• Ask if a cookie exists• isset($_COOKIE[$cookie_name])• Useful before you try to get the
value• If you try to get the value of a non-
existing cookie your program fails
• Delete a cookie• Unset($_COOKIE[$cookie_name])
• Example• cookieExample
PHP 18
Sessions in general
• Most application servers are not totally stateless.• Session state is kept on the
server• Each user has a session
• Many users = many sessions
• The session is alive as long a the user is using the web site• In real life there is a timeout,
typically 30 minutes
• The session is like a map / dictionary / associative array• List of (key, value)-pairs• The key is a string• The value might be anything
• Time• Number• Shopping cart
• Sessions are usually implemented using a session cookie• The server finds your session based
on your session cookie
PHP 19
Sessions in PHP
• Set• $_SESSION[“name”] = $value;
• Get• $value = $_SESSION[“name”];
• Ask if there is an entry in the session• If (isset($_SESSION[“name”]) { …}
• Example: sessionExample
• Starting the session• Put this in the top of the PHP file
using sessions• <?php session_start() ?>
• Clean the session• Session_unset()• You are left with an empty session
• Remove the session• Session_destroy()• You are left with no session
PHP 20
PHP consuming SOAP/WSDL web services• The tool wsdl2php reads WSDL file and produces PHP classes
according to the file.• Import the generated PHP file into your PHP file• Require_once $filename.
• Use the generated classes• Example• PhpCurrencySoapConsumer
PHP 21
PHP consuming REST web services• Two stages
1. Make a GET request and get the response body (XML or JSON)2. Read the response body and convert it into a more useful format
• GET request can be send in two ways• With curl
• $client = curl_init($uri);• curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
• // default: false, curl_exec returns true/false• $response = curl_exec($client);• curl_close($client);
• With file_get_contents• $response = file_get_contents($uri);
• Make a useful format: associative arrays• $convertToAssociativeArray = true;• $arr= json_decode($jsondata, $convertToAssociativeArray);• echo $arr['Title'];
• Example• PhpConsumeRestService