+ All Categories
Home > Documents > PHP By Jonathan Foss. Summary Dynamic vs Static pages Introduction to PHP PHP Syntax PHP Objects PHP...

PHP By Jonathan Foss. Summary Dynamic vs Static pages Introduction to PHP PHP Syntax PHP Objects PHP...

Date post: 29-Dec-2015
Category:
Upload: polly-blake
View: 233 times
Download: 5 times
Share this document with a friend
30
PHP By Jonathan Foss
Transcript

PHP

By Jonathan Foss

Summary• Dynamic vs Static pages• Introduction to PHP• PHP Syntax• PHP Objects• PHP functions• Security• Session/Cookies• More Information

Static Websites• Use HTML files (.html, .htm)• Content is created and uploaded to the web server

via FTP• Every user sees the same content• Content remains the same until the author uploads a

new version of the page• Can include client-side scripting (such as Javascript)

Dynamic Websites• Generate HTML as each server request is made

• Uses Common Gateway Interface to communicate extra variables between browser and server

• Several popular CGI languages

– PHP .php

– Perl .cgi, .pl

– Active Server Pages .asp

– More multi-purpose languages such as C/C++, Java

• Output HTML can be different for each user

PHP• Scripting language developed especially for the web• Scripts are interpreted by the server every time a

client requests a page from the web server• The output of the script can therefore depend on:

– Parameters set by the user– Variables stored on the server– External data sources such as databases or XML

feeds• Because scripts are executed on the server, the

client never gets to see the actual PHP source code

Uses of PHP• PHP usually used to output HTML code to the

browser• PHP can also be used to generate other content such

as XML, CSS or Javascript files• With extra libraries it can also generate more

complex binary files such as images, zips or PDFs• Can also be used on the command line (without a

web server), and is now popular for off-line scripting.

Popular uses of PHP

PHP Architecture

Server

Web Browser

Apache

PHP file

PHP

MySQL

Client

This is often referred to as a LAMP (or WAMP) stack:

Linux (or Windows) Apache MySQL PHP

PHP Installation• Binaries and source code available from:

http://www.php.net

• Or you can download the whole LAMP stack in one installation package:– XAMPP http://www.apachefriends.org/en/xampp.html– Or EasyPHP (Windows only)

http://www.easyphp.org/index.php

PHP Syntax• The PHP preprocessor only interprets code between

tags <?php and ?>• Any other content is output.• Variables are defined using the $ symbol• Statements must end with a ;• To output text using php, use the command echo• Strings can be concatenated with . character

PHP Syntax• Can use \ to escape special characters such as “<?php

$myvar = 4;

$text = “The value of the variable is “ ;

echo $text . $myvar;

$text = “The value of the variable is \”$myvar\””;

echo $text;

?>

• Will output:

The value of the variable is 4

The value of the variable is “4”

First PHP Script: hello.php<html>

<head><title>Test PHP Program</title></head>

<body>

<?php

echo “<p>Hello</p>”;

?>

</body>

</html>

• Note: this is a very basic PHP script, and generates the same code every time!

http://mot.dcs.warwick.ac.uk/php/hello.php

Arrays in PHP• Arrays (and variables) are assigned without

declaration• Can be declared all at once:

– $myarray = array(1,3,5,7,9);

• Or can be assigned by index:– $myarray[5] = 11;

• Can even use strings as indices:– $myarray[“name”] = “test”;

• Arrays can hold any data type

(including other arrays => multidimensional arrays)

HTML Forms• As you have seen in the HTML lecture, a simple HTML

form might be:<form action=“hello.php” method=“GET”>

<input type=“text” name=“name”>

<input type=“submit” value=“submit”>

</form>

• Assuming I type my name in the box

• When I click the submit button the browser changes the URL to:

– hello.php?name=Jonny

• This is because the GET method is used.

Accessing CGI Variables• GET variables are accessible using $_GET• So if the url says: hello.php?name=Jonny• The name is accessible in $_GET[“name”]

http://mot.dcs.warwick.ac.uk/php/lesson1.php

http://mot.dcs.warwick.ac.uk/php/lesson2.php

• POST is similar to GET, except the data is sent in the body of the request rather than in the header (and is therefore hidden from the user).

• POST variables are stored in $_POST

Environment VariablesVariable Description

$_GET Variables encoded on request header

$_POST Variables sent in request body

$_SERVER Variables about the server and PHP configuration

$_FILES Stores contents of files uploaded by the client

$_REQUEST Contains a combination of both $_GET and $_POST

$_SESSION Temporary data stored within a particular browser session

$_ENV Environment variables from the system

$_COOKIE Variables stored in a cookie

String Functions• strlen($string);

– Returns the number of characters in $string

• sub_str($string,$start, [$len]); – Returns a substring of $string, that starts at $start and is

$len characters long

• explode($delim, $string);– Returns an array of substrings between the delimiters

• md5($string);– Returns an md5sum of $string (useful for storing passwords

in a database)

PHP Conditional Statements<?php

$mark = 70;

if($mark == 100)

echo “You got them all right!”;

if($mark >= 90){

echo “Passed: Grade A”;

}elseif($mark >= 70){

echo “Passed: Grade B”;

}else{

echo “Failed”;

}

?>

PHP Loops<?php

$i = 0;

while($i < 10){

echo “Number is $i”;

$i++;

}

for($i = 0; $i < 10; $i++)

echo “Number is $i”;

?>

In this case, both loops are equivalentIn this case, both loops are equivalent

PHP Loops<?php

$namestr = “Alexandra,Maurice,Fawaz,Jonny,Matthew”;

$names = explode(“,”,$namestr);

for($i = 0; $i < count($names); $i++)

echo “Hello “ . $names[$i] . “\n”;

foreach($names as $name)

echo “Hello $name\n”;

?>

In this case, both loops are equivalentIn this case, both loops are equivalent

http://mot.dcs.warwick.ac.uk/php/lesson3.php

Objects in PHP• Variables are declared without a type• However, objects do exist in PHPclass Square{

protected $size;

public function __construct($size){

$this->size = $size;

}

public function getArea(){

return $size * $size;

}

}

Objects in PHP - PHP5 Only• Can declare functions and variables• Can have a constructor: __construct()• Can have a destructor: __destruct()• Can use public, protected, static and private

keywords before variables/functions – these keywords work in the same way as they do in Java

• Use -> to access functions and variables (even from within the class)

Procedural vs OOP• PHP originally a procedural language

• Object support introduced in PHP3 – completely rewritten in PHP5

• Object type is determined when the variable is assigned

<?php

$var = “test”;

$var = 42;

$var = new Square(2);

?>

$var is now a string$var is now a string

$var is now an integer$var is now an integer

$var is now a square$var is now a square

More PHP Commandsisset() Returns true if the variable has been set – useful for

environment variables (such as isset($_GET[“name”]))

phpinfo() Generates an html page describing the php setup – good for discovering what libraries are installed

include() Includes another php script (see also require())

fopen(),fread(),fclose()

Used for reading local files (on the same server)

system() Execute shell commands on the server

header() Sets header parameters of HTTP response, for exampleheader(“Location: index.php”);Which would redirect the user to index.php

CURL Implements HTTP to get web resources from other sites

libxml Library for XML functions (see also SimpleXML)

Other types of output• Although PHP files usually output HTML, PHP can

output other files• To do this, the appropriate header must be sent – for

instance to output an xml feed:header("Content-type: text/xml");

• Other uses might be to create a dynamic CSS file, or create a picture using the GD library.

Sessions and Cookies• Sessions maintain a unique string as the user

navigates between pages, this string references a file stored on the server, which can contain variables

• Sessions are lost when the browser is closed• Cookies store text files on the client side and are

therefore persistent between browser sessions

Sessions Cookies

session_start()$_SESSION[“views”] = 1;echo “You’ve visited “;echo $_SESSION[“views”] . “times”;

setcookie(“views”,1,$expirydate)echo “You’ve visited “;echo $_COOKIE[“views”] . “times”;

http://mot.dcs.warwick.ac.uk/php/lesson4.php

More Information• http://www.php.net• http://www.tizag.com/phpT/• http://www.hotscripts.com/PHP/

Assignment• Write a guest book application for your website

– Find some PHP hosting (google free php hosting)– Write an HTML form to accept user input (name, comments,

email address, etc.)– Implement a way of interpreting the responses, and storing

them– Make sure there’s a way I can actually see your PHP code

• Deadline: Thursday 26th March 2009

Summary• Dynamic vs Static pages• Introduction to PHP• Uses of PHP• PHP Syntax• PHP Objects• PHP functions• Security• Session/Cookies• More Information

Thank You

Any Questions?


Recommended