PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in...

20
PHP I

Transcript of PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in...

Page 1: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

PHP I

Page 2: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

PHP, or PHP Hypertext Preprocessor is a server-side scripting language.

Originally created in 1994 by Rasmus Lerdorf, to track users at his web site.

Over the last few years, it has rapidly developed into a server-side scripting language, that fully supports (interacts) with a host of relational database systems (MySql in particular), thereby making it extremely useful for generating dynamic page content.

Latest version is version 4, but 5 due to be released soon. In addition, PHP is an open source technology, that is freely

available. It is estimated that over 6 million domains now use PHP.

It is platform independent, with implementations for most Unix, Linux and Windows operating systems.

Page 3: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

Shares some similarity with JavaScript in that it also allows you to embed programs (scripts) inside HTML code.

The distinction is that JavaScript (and other client-side scripting languages) are interpreted by the browser, whilst PHP (and other server-side scripting languages) is processed by the web server.

Once the script is processed, the result of the script (HTML in most cases) replaces the PHP code, and is returned to the client.

Hence the browser sees standard HTML and displays it appropriately.

As the script is processed by the server, the technology is aptly named server-side scripting language

Page 4: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

Sample PHP code<html><head><title>Welcome to the world of PHP</title></head>

<body>

<p>

<?php

echo(“Welcome to the world of PHP, a convenient means of generating dynamic page content.”);

?>

</p>

</body>

</html>

Resultant HTML code<html><head><title>Welcome to the world of PHP</title></head>

<body>

<p> Welcome to the world of PHP, a convenient means of generating dynamic page content.</p>

</body> </html>

Page 5: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

Advantages of Server-side scripting There are no browser incompatibility issues, as the PHP code is

interpreted entirely by the server. Access to server side resources such as data from a relational

database. This is perhaps the most important benefit of PHP. Reduced load on the client: JavaScript may significantly slow

the display of a web page on low memory computers, as the browser has to process the JavaScript code. PHP code is entirely processed by the web server, hence this burden is passed to the server.

Drawbacks of Server-side scripting Multiple server calls: As PHP code is interpreted by the web

server, each time a user interacts with the page, a call has to be made to the web server.

Security issues: Use of PHP could expose the web server, and lead to unwanted access to web server resources.

Page 6: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

Basic Syntax PHP scripts begin with <?PHP and end with ?> delimiters Any code within these 2 delimiters is processed by the web

server as PHP code. PHP code can be embedded directly anywhere within an HTML document.

PHP files are stored with a ‘.php’ extension. Syntactically, PHP is very similar to JavaScript, and supports

similar constructs such as Arrays and Conditional statements. In addition, PHP comes with a lot of built-in functions, that

enable you to perform all sorts of complex tasks such as sending emails, file upload, downloads, etc.

Single line comments begin with ‘//’. Multiple line comments are enclosed between ‘ /* ’ and ‘ */ ’ //this is a single line comment. /* this is a multi-line comment */

Page 7: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

Variables and Operators Variables in PHP are declared with $ symbol. PHP is a loosely typed language, i.e. its variables can contain

any type of data such as integers, strings, etc. They may also change types over its lifetime.

$testvariable = “Hello World”; $testvariable = “3”; In the above example, $testvariable is initially initialized with

a string value, and subsequently assigned an integer value. You may use the settype built-in function to explicitly convert

the type. E.g. settype($testvariable, “integer”); converts the type of $testvariable from string, to integer.

The = is the assignment operator, while = = is the equality operator.

Several comparative, and arithmetic operators (similar) to those in JavaScript exist for performing comparisons, and for computations.

Page 8: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

PHP automatically converts variable types when used for arithmetic computation. E.g

<?PHP $testvariable=“20 students; $testvariable=$testvariable + 20.

The above statement would evaluate to 40. Note that for implicit conversion from string to integer, the

number value must come before other text in the string.

Variable value substitution Variable values can be directly written into HTML code, e.g<html><head><title>PHP Example</title></head><body><p> Hello<?php $testvariable=“Paul Smith”; echo($testvariable);</p></body></html>

Page 9: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

Array Declaration In the simplest form, arrays are declared using the built-in array

function, as shown below: $anarray = array (‘1’,’ten’,’four’); The above code creates an array called anarray, that has 3

values. As in JavaScript and other similar programming languages, array

indices start at 0, i.e. $anarray[0] = = ‘1’, $anarray[1] = = ‘ten’ and $anarray[2] = =

‘four’ It is also possible to assign values to array elements with the

index. E.g. $anotherarray[0] = ‘ten’ If the index is not specified, an array element will be added after

the last existing element of the array, i.e. $anarray[ ] = ‘the fourth element’. The above code automatically creates the 4th element of

$anarray.

Page 10: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

PHP also supports the use of non-numeric arrays (associative arrays).

E.g. $birthdays[‘Kevin’] = ’20-03-1982’; $birthdays[‘James’] = ’21-07-1984’;

Associative arrays are particularly useful for accessing, and processing HTML form elements, as demonstrated later.

Accessing values of array elements: The array followed by its index (in square brackets) translates to

the value of the element. Illustrating with the examples above, <p><?php echo(“$anarray[1]”); ?> would result in <p>ten</p> <p>Kevin’s birthday is <?php echo(“$birthdays[‘Kevin’]”); ?>.

would result in <p>Kevin’s birthday is 20-03-1982.

Page 11: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

User Interaction and Forms Server-side languages such as PHP are limited in their ability to

interact with user input in the sense that a request has to be sent to the server, server processes the PHP code to dynamically generate an HTML response, and sends this back to the client.

Hence user interaction involves back and forth server calls.

Sending information to the web server The simplest method of sending information from a client, to the

web server is by sending it along with the URL string as a query string.

This is accomplished with the use of a ? symbol before the variable that is being passed. In the case of sending multiple variables, they are separated with an ampersand (&)

E.g <a href=“php_script.php?firstname=Paul”>Paul</a>

Page 12: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

The previous example demonstrates a link to a PHP program called php_script.php.

The name variable is passed to the script in URL of the link, as part of the page request.

PHP automatically creates an associative array variable called $_GET that contains any values passed in the URL query string.

Hence the value of the name variable passed in the example would be accessed with $_GET[‘firstname’].

Example:

php_script.php

<? php

$firstname = $_GET[‘firstname’]; //a variable is assigned the value

echo(“Welcome to this website, $firstname”); //of ‘firstname’

?> // sent in the URL query string.

Page 13: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

Passing multiple variable values with the GET method

<a href=“php_script.php?fname=Paul&lname=Smith”>Paul Smith</a>

Within php_script.php, these values would be accessed as $_GET(‘fname’) and $_GET(‘lname’), respectively.

Passing Values from Forms

GET Method: Similar to passing variables in URL query strings as

demonstrated above. PHP generates a $_GET array for each named form element, and

they can then be easily accessed by the PHP program. Due to limitations in the number of characters that can be sent

with the GET method, it is sometimes technically impossible to use this method to pass form data.

Page 14: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

<html><head><title>Passing form element values to PHP</title></head><body><form method=“GET” action=“php_script.php”><input type=“text” name=“fname”></input><input type=“text” name=“lname”></input><input type=“submit”></form></body></html> When the above form is submitted, it will generate an URL

query string similar to href in the link, in the last example.

POST Method The information is invisibly passed, such that it does not form

part of the URL .

Page 15: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

This method enables you to send data containing large values, e.g textarea, to the web server.

The variables passed are placed in another special array called $_POST.

Example: Here the GET method is replaced with POST

<html><head><title>Passing form element values to PHP</title></head><body><form method=“POST” action=“php_script.php”><input type=“text” name=“fname”></input><input type=“text” name=“lname”></input><input type=“submit”></form></body></html>

Page 16: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

The values in the form elements are accessed with the $_POST array.

The php_script.php would have to be modified as shown below:

php_script.php

<? php

$firstname = $_POST[‘fname’];

$lastname = $_POST[‘lname’];

echo(“Welcome to this website,<b> $firstname $lastname!</b>”);

?>

The $_REQUEST array Contains all variables that appear in both $_GET and $_POST So you’re no longer concerned about the method of the form.

Page 17: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

Control Structures PHP, like other programming languages provides facilities that

allow us to control the sequence of actions in a script.

The if-else statement: Most common control structure. Takes the general form:

if (condition)

{ //statements to execute if condition is true }

else { // statement to execute if condition is false } The else statement is optional, i.e if there are no statements to

execute if the condition is false, the else statement can be omitted.

Page 18: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

E.g. $name = $_REQUEST[‘name’];if ($name = = ‘Paul’) { echo (“Welcome to this web site, master creator!”); }else { echo(“Welcome to this website $name”); }

Multiple conditions In practice, you might want to combine more than one condition

within the if construct. This is achieved with the use of the ‘and’ operator (&&) and the

or operator (||). The word ‘and’ is a legal operator in PHP.E.g.$fname = $_REQUEST[‘fname’];$lname = $_REQUEST[‘lname’];if ($fname = = ‘Paul’ && $lname = = ‘Smith’) // the condition evaluates

to { echo (“Welcome to this web site, master creator!”); } // true only if both else { echo(“Welcome to this website $fname $lname”); } //statements are true.

Page 19: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

The While Loop Takes the form:

while (condition)

{ /* execute statements over and over as long as condition remains true */ }

Useful when you’re processing a list of objects, e.g array elements.

E.g

$count = 1;

while ($count <= 10)

{ echo(“This is element $count”);

$count++;

}

Page 20: PHP I. PHP, or PHP Hypertext Preprocessor is a server-side scripting language. Originally created in 1994 by Rasmus Lerdorf, to track users at his web.

The For Loop Takes the form: for (initialize; condition; update) { /* statements to execute in iterations, as long as condition remains true after each update */ } The counter variable is initialized, its condition set, and its value

updated in the first line of the For Loop. E.g. for ($count = 1; $count <= 10; $count++)

{ echo(“This is element $count”); }

References:Build Your Own Database Driven Website Using PHP & MySQL. Kevin

Yank. 2nd Ed. Chapter 3Deitel, Deitel & Nieto Chapter 29.