Web API Introduction
Web API Introduction
Web API
Principle
WEB Client
of server WEB
side script
SERVER
html document
SCRIPT
HTTP
SCRIPT
Script engine
• Pages are generated by a program
• A html document at the server side includes the code to be
executed (script)
• The code is delimited via special escape characters
• The web server extracts the script part from the document
• A script engine runs the code
• Web server replaces the script with the output of the execution
• Client sees pure html (no way to access the code)
Access to Cloud computing
Web URL
(standard HTTP methods)
web brower
Service HTTP
Rest,XML-RPC,etc
IaaS
HTTP
PaaS
SaaS
Application
• Scripting language
Every time the PHP interpreter reaches a PHP open tag <?php,it runs
the enclosed code up to the delimiting ?>marker.
Can be changed, see short_open_tags INI option;
PHP code embedding
<HTML> <HTML>
<HEAD>Sample PHP <HEAD>Sample PHP Script</HEAD>
Script</HEAD> <BODY>
<BODY> The following prints "Hello, World":
The following prints "Hello, World": Hello, World
<?php </BODY>
print "Hello, World" </HTML>
?>
</BODY>
</HTML>
Every time the PHP interpreter reaches a PHP open tag <?php,it runs
the enclosed code up to the delimiting ?>marker.
Variables
• A variable always starts with the dollar sign $
• $a
• $A
• $1 (not allowed)
• Identifiers are case sensitive (not when referring to function)
• Variable and function can have the same name!
Types
$a = “fine” // $a is a string
$a = 10; // $a is an integer
$b = 6.3;
$c = $a + $b; /* $c is a float */
$d = (int)$c; // type casting ($d integer)
gettype($d);
settype($d, double); // $d is now double
<?php
$name = "John";
$$name = "Registered user";
print $John; //display “Registered user”
?>
• isset ()
• determines whether a certain variable has already been declared by
PHP.
• unset()
• “undeclares” a previously set variable, and frees any memory that
was used by it if no other variable references its value.
• empty ()
• empty() may be used to check if a variable has not been declared or
its value is false.
Variable’s scope
• Names inside a function has local scope
• Script level names can be accessed through the special built-in
array $GLOBALS
$m main script
function Af
$a $a is only visible in the function Af’s scope
$m can be seen via $GLOBALS[m]
function Bf
$b $b is only visible in the function Bf’s scope
$a is not visible
$m can be seen via $GLOBALS[m]
Predefined System "Superglobals"
<?php
define('MYCONST',100);
define('NAME',"My Name");
?>
<?php
print_r($_SERVER);
?>
Example
<?php
$user = (isset($_GET[‘user’]) ? $_GET[‘user’]:”” );
…
?>
Comments
• Multi-line comments
/* This is a multi-line comment */
• Single line comments
// This single line is commented
# So is this single line
• PHP comments are distinct from HTML comments in that PHP comments are
not sent to the client browser.
Operators
• Key elements:
• Input fields must be contained inside a form tag.
• All input fields must have a name.
• Names cannot have spaces in them. Fields should be named well for clear
identification.
• Form action should be URL to PHP processing script.
• Appropriate form transmission method selected:
• GET or POST.
GET vs POST
• Name/value pairs appended in clear text to the URL of the receiving
page/script.
• Each name/value pair separated by '&'. Value data automatically URL
encoded.
• Names are taken from the form field names.
• GET URLs can be saved, bookmarked, etc. and used to recall the script
with the same data.
• GET strings provide 'transparency' that may/may not be desired.
• Data available into the $_GET superglobal
GET vs POST
</body>
</html>
An example
<html> method
<head><title>Register</title></head> Processing
<body> script
<h1>Registration</h1>
<form method="get" action="register.php">
<table>
<tr> <td>E-mail address:</td> <td> <input type='text' name='email'/></td> </tr>
<tr> <td>First name:</td> <td><input type='text' name='first_name'/></td> </tr>
<tr> <td>Last name:</td> <td><input type='text' name='last_name'/></td></tr>
<tr> <td>Password:</td> <td> <input type='password' name='password'/> </td></tr>
<tr> <td colspan='2'> <input type='submit' name='register' value='Register'/> </td> </tr>
</table>
</form>
</body>
</html>
Input tags
key value
http://localhost/register.php?email=PSD&first_name=Piattaforme&last_name=SW&password=Pippo®ister=Register
Conditional control structures
if (expr) if (expr):
statement { statement1; statement list
elseif (expr) statement 2;
elseif (expr) :
statement }
elseif (expr) statement list
statement ...
... else :
else statement list
statement endif;
Traditional loop control structures
while (expr) while (expr) : do
statement list statement
statement endwhile; while (expr);
$count = count($array);
for ($i = 0; $i <= $count; $i++) {
}
Array
array([key =>] value, [key =>] value, ...)
• The key is optional, and when it’s not specified, the key is
automatically assigned one more than the largest previous
integer key (starting with 0).
json_encode
…
Lab: simpe Shopping cart
methodName=list List
json
• Any valid PHP code may appear inside a user-defined function, even
other function…
• Functions need not be defined before they are referenced
• Call-by-reference, call-by-value, default value, variable-length
argument, lambda-style function
Parameter passing
function function_name (arg1, arg2, arg3, …)
{
statement list
}
parameter by-value
function square(&$n)
{ function square($n)
$n = $n*$n; {
} $n = $n*$n;
}
… by-reference
Default value
function makeAcoffee ($type=“espresso”)
{
return “Making a cup of $type”;
}
echo makeAcoffee();
echo MakeAcoffee(“French”)
foo(1, 2, 3);
Variable function
• If a variable name has parentheses appended to it, PHP looks for a
function with that name and executes it
$func = ‘foo’;
$func(); #call foo()
Static variables
function do_something()
{
static $first_time = true;
if ($first_time) {
// Execute this code only the first time the function is called
...
$first_time=false;
}
// Execute the function's main logic every time the function is called
...
}
Array_map
• Applies a callback function to the elements of the given arrays
<?php
function Double($a){return 2*$a;};
$in = range(1,5);
$out = array_map("Double",$in);
print_r($out);
?>
• Other interesting functions (see manual):
• array_walk
• array_reduce
• …
Code inclusion control structures
include file_name;
require_once file_name;
include "http://www.example.org/example.php";
<?php <?php
if ($db = sqlite_open("SIMPLE.DB",0666,&$error)) $db = new SQLiteDatabase("SIMPLE.DB", &$error);
print("DB OPENED...."."\n"); if ($db)
else echo “DB OPENED....";
die($error); else
?> die($error);
?>
SIMPLE.DB
Create a table
bool queryExec ( string $query [, string &$error_msg ] )
Executes a result-less query against a given database
PRODUCTS
db id description quantity
Insert a row
$query = "INSERT INTO PRODUCTS (id,description,quantity) VALUES (1,'DVD',1)";
$db->queryExec($query);
id Description quantity
1 DVD 1
PRODUCTS
db
Update/delete
$db->queryexec('DELETE FROM PRODUCTS WHERE id=2');
SQLiteResult
unbufferedquery
SQLiteUnbuffered
1 DVD 1
OO Model
class MyClass {
function __construct() {
echo "Inside constructor";
}
}
Destructor
• __destruct() class MyClass {
function __destruct()
• Called when an object is {
destroyed (no more print "An object of type MyClass is being
destroyed\n";
reference) }
}
class MyClass {
public $var = 1;
}
obj1 object
$obj1 = new MyClass();
$obj2 = clone $obj1;
obj2 object $obj2->var = 2;
print $obj1->var; //print 1
Access protection of member
variables
class MyDbConnectionClass {
public $queryResult;
protected $dbHostname = "localhost";
private $connectionHandle;
// ...
}
function setName($name)
{
$this->name = $name;
}
function getName()
{
return $this->name;
}
};
$judy = new Person();
$judy->setName("Judy");
$joe = new Person();
$joe->setName("Joe");
print $judy->getName() . "\n"; //print Judy
print $joe->getName(). "\n"; //print Joe
Static properties
class MyUniqueIdClass {
static $idCounter = 0;
public $uniqueId;
function __construct()
{
self: refer to the current class
self::$idCounter++;
$this->uniqueId = self::$idCounter;
}
}
<?php
…
class C { - Constants [0] { }
function F() - Static properties [0] { }
{ - Static methods [0] { }
print "Hello, World\n"; - Properties [0] { }
} - Methods [1] {
} Method [ public method F ]
…
ReflectionClass::export("C");
?>
PHP Communication
string file_get_contents ( string $filename [ …])
<?php
/* Identical to above, explicitly naming FILE scheme */
$localfile = file_get_contents("file:///home/bar/foo.txt");
end-point-type
http://api.flickr.com/services/rest/?method=...&name=value...
CLIENT SERVER
PHP_Serial
Example of API call
flickr.photos.getInfo
In Parameters:
api_key (Mandatory)
Your API application key.
photo_id (Mandatory)
The id of the photo to get information for.
secret (optional)
The secret for the photo.
If the correct secret is passed then permissions checking is skipped, unless photo is shared.
Out Parameters:
info with different format…
Example of reply
An example:
invoking a REST end-point from PHP code
$param = array(
'api_key' => 'e568d81ac2ac47e943673641e037be8 c',
'method' => 'flickr.photos.getInfo', Parameters
'photo_id' => '11111',
'format' => 'php_serial', •Reply in php serial format
);
$encoded_params = array(); urlencode
$url
http://api.flickr.com/services/rest/?api_key=e568d81ac2ac47e943673641e037be8&method=flickr.photos.getInfo&photo_id=11111&format=php_serial
Serialization
string serialize ( mixed $value ) mixed unserialize ( string $str )
Generates a storable
Creates a PHP value from
representation of a value
a stored representation
Invoke method $ans = file_get_contents($url);
echo $ans_obj['photo']['id'].'<br>';
echo $ans_obj['photo']['description']['_content'];
echo $ans_obj['photo']['dates']['taken'];
}