0% found this document useful (0 votes)
4 views51 pages

WS Lec8 PHP Part01 Basics

This document is a lecture on the basics of PHP, covering topics such as server-side scripting, PHP syntax, variables, constants, and arrays. It introduces the concept of server-side programming and provides examples of various server-side scripting languages, including PHP, ASP, Java Servlets, and JSP. The document also includes information on installing PHP and basic PHP syntax for creating dynamic web content.

Uploaded by

ariraghad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views51 pages

WS Lec8 PHP Part01 Basics

This document is a lecture on the basics of PHP, covering topics such as server-side scripting, PHP syntax, variables, constants, and arrays. It introduces the concept of server-side programming and provides examples of various server-side scripting languages, including PHP, ASP, Java Servlets, and JSP. The document also includes information on installing PHP and basic PHP syntax for creating dynamic web content.

Uploaded by

ariraghad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Web Systems - 502315-3

PHP-Part01-Basics
Lecture 8

Dr. Afnan Bukhari


Department of Information Technology

Original slides are prepared by:


Dr. Abdullah Baqasah
Contents
1. Introduction
2. PHP - Installing Server
3. Basic PHP Syntax
4. Variables & Constants
5. Arrays
6. Operators
7. Conditionals
8. Looping
9. Functions
10. Variables Scope
11. Including Files
Web Systems [502315-3] Dr. Afnan Bukhari 2
1. Introduction
Introduction

● Before we begin learning PHP, we must understand Server-Side dynamic web


programming.
● A program running on a web server (server-side scripting), manage user
sessions, and control workflow. Server responses is used to generate the web
content on various web pages be determined by such conditions as data in a
posted HTML form, parameters in the URL, the type of browser being used, the
passage of time, or a database or server state.

Web Systems [502315-3] Dr. Afnan Bukhari 4


Introduction (cont.)
Examples of Server-Side Scripting Languages:

● Server-Side Includes (SSI) - Code is embedded in HTML pages, and evaluated on the
server while the pages are being served. Add dynamically generated content to an existing
HTML page, without having to serve the entire page via a CGI (Common Gateway
Interface) program.
● Active Server Pages (ASP, Microsoft) - The ASP engine is integrated into the web server
so it does not require an additional process. It allows programmers to mix code within
HTML pages instead of writing separate programs. (Drawback(?) Must be run on a server
using Microsoft server software.)
● Java Servlets (Sun) - As CGI scripts, they are code that creates documents. These must be
compiled as classes which are dynamically loaded by the web server when they are run.
● Java Server Pages (JSP) - Like ASP, another technology that allows developers to embed
Java in web pages.

Web Systems [502315-3] Dr. Afnan Bukhari 5


Introduction (cont.)
Server-Side Includes (SSI):
● You might place a directive into an existing HTML page, such as:
Example 1 <!--#echo var="DATE_LOCAL" -->
And, when the page is served, this fragment will be evaluated and replaced with its value:
Tuesday, 15-Jan-2013 19:28:54 EST
OR
Example 2 <!--#config timefmt="%A" --> <!--#echo var="DATE_LOCAL" -->
Save it as an HTML file or SHTML and upload it to your server. You should see the current day
name: Monday, Tuesday, Wednesday ...

More info. and examples:


● https://en.wikipedia.org/wiki/Server_Side_Includes
● http://www.htmlgoodies.com/beyond/webmaster/article.php/3473341/SSI-The-Include-
Command.htm
● https://httpd.apache.org/docs/current/howto/ssi.html

Web Systems [502315-3] Dr. Afnan Bukhari 6


Introduction (cont.)
Active Server Pages (ASP, Microsoft): Example
● What is an ASP File?
<!DOCTYPE html>
○ An ASP file has the file extension ".asp“ <html>
○ An ASP file is just the same as an HTML file <body>
<%
○ An ASP file can contain server scripts in addition to HTML response.write("My first ASP script!")
○ Server scripts in an ASP file are executed on the server %>
</body>
● What can ASP do for you? </html>
○ Edit, change, add content, or customize any web page Show Example »

○ Respond to user queries or data submitted from HTML forms


○ Access databases or other server data and return results to a browser
○ Provide web security since ASP code cannot be viewed in a browser
○ Offer simplicity and speed

● More info. and examples: Result


● https://www.w3schools.com/asp/asp_introduction.asp My first ASP script!

Web Systems [502315-3] Dr. Afnan Bukhari 7


Introduction (cont.)
Java Servlets (Sun):
● Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a request coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
● Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
● Servlets Architecture (see the right figure):
Servlets Architecture
● More info. and examples:
● https://www.tutorialspoint.com/servlets/index.htm

Web Systems [502315-3] Dr. Afnan Bukhari 8


Introduction (cont.)
Java Server Pages (JSP): Example
● What is an JSP File?
<html>
○ JavaServer Pages (JSP) is a technology for developing <head><title>Hello
web pages that support dynamic content which helps World</title></head>
<body>
developers insert java code in HTML pages by making Hello World!<br/>
use of special JSP tags, most of which start with <% and <%
out.println("Your IP address is " +
end with %> request.getRemoteAddr());
%>
</body>
● More info. and examples: </html>
● https://www.tutorialspoint.com/jsp/jsp_overview.htm

Result
Hello World!
Your IP address is 127.0.0.1

Web Systems [502315-3] Dr. Afnan Bukhari 9


Introduction (cont.)
PHP:
● Developed in 1995 by Rasmus Lerdorf (member of the Apache Group)
○ within 2 years, widely used in conjunction with the Apache server
○ developed into full-featured, scripting language for server-side programming
○ free, open-source
○ server plug-ins exist for various servers
○ now fully integrated to work with MySQL databases
● PHP is similar to JavaScript, only it’s a server-side language
○ PHP code is embedded in HTML using tags <?php ... ?>
○ when a page request arrives, the server recognizes PHP content via the file extension (.php)
○ the server executes the PHP code, substitutes output into the HTML page
○ the resulting page is then downloaded to the client
○ user never sees the PHP code, only the output in the page
● The acronym PHP means (in a slightly recursive definition) Hypertext Pre-processor

Web Systems [502315-3] Dr. Afnan Bukhari 10


2. PHP - Installing the
Server
PHP - Installing the Server
● To start using PHP, you can:
○ Option 1: Find a web host with PHP and MySQL support
○ Option 2: Install a web server on your own PC, and then run PHP and MySQL
● If you select option 2, then use one of the free available servers:
○ WampServer http://www.wampserver.com/en/
○ XAMPP https://www.apachefriends.org/index.html
● WAMP runs on Windows, XAMPP is multi-platform.
● From now on, we will work on WampServer.

● You can find more information about php related tools on:
○ Download PHP for free here: http://www.php.net/downloads.php
○ Download MySQL for free here: http://www.mysql.com/downloads/index.html
○ Download Apache for free here: http://httpd.apache.org/download.cgi

Web Systems [502315-3] Dr. Afnan Bukhari 12


3. Basic PHP Syntax
Basic PHP Syntax
<html>
● A PHP scripting block always starts <!-- hello.php -->
with <?php and ends with ?>. <head><title>Hello World</title></head>
<body>
● A PHP scripting block can be placed <p>This is going to be ignored by the PHP interpreter.</p>
<?php echo '<p>While this is going to be parsed.</p>'; ?>
(almost) anywhere in an HTML <p>This will also be ignored by the PHP preprocessor.</p>
<?php
document. print('<p>Hello and welcome to <i>my</i> page!</p>');
● Use print and echo for output. ?>
<?php
● Use semicolon (;) at the end of each // This is a comment
/* This is
statement. a comment block
*/
● Use // for a single-line comment. ?>
● Use /* and */ for a comment block. </body>
</html>

Result (browser):
● The server executes the print and This is going to be ignored by the PHP interpreter.
While this is going to be parsed.
echo statements, substitutes output. This will also be ignored by the PHP preprocessor.
Hello and welcome to my page!

Web Systems [502315-3] Dr. Afnan Bukhari 14


4. Variables &
Constants
Variables
<html><head></head>
● All variables in PHP start with a $ sign <!-- scalars.php -->
<body> <p>
symbol. <?php
● A variable's type is determined by the $foo = true; if ($foo) echo "It is true! <br /> \n";
$txt = '1234'; echo “this is a string: $txt <br /> \n";
context in which that variable is used $a = 1234; echo "$a <br /> \n";
$a = -123; echo "$a <br /> \n";
(i.e., there is no strong-typing in PHP). $a = 1.234; echo "$a <br /> \n";
● PHP’s Data Types: $a = 1.2e3; echo "$a <br /> \n";
$a = 7E-10; echo "$a <br /> \n";
○ Integer—Used for whole numbers
○ Float (also called double)—Used for real echo 'Arnold once said: "I\'ll be back"', "<br />";
$juice= 'Nadek'; echo "$juice's taste is great <br /> \n";
numbers $str = <<<EOD
○ String—Used for strings of characters Example of string Result :
It is true !
spanning multiple lines
(single ' ' or double " " quoted) using “heredoc” syntax.
This is a string: 123 4
123 4
○ Boolean—Used for true or false values EOD; -123
1.234
○ Array—Used to store multiple data items echo $str;
?>
120 0
7.0E-10
(see next slides) </p></body></html> Arn old once said: "I'll be ba ck"
Nadek's taste is g reat
○ Object—Used for storing instances of Example of string

classes (we will see it later) spannin g multiple lines


using here doc synta x.

Web Systems [502315-3] Dr. Afnan Bukhari 16


Constants
<?php
● A constant is an identifier (name) for a
// Valid constant names
simple value. define("FOO", "something");
● A constant value cannot be changed. define("FOO2", "something else");
define("FOO_BAR", "something more");
● A constant is case-sensitive by default.
// Invalid constant names (they shouldn’t start
● By convention, constant identifiers are // with a number!)
always UPPERCASE.
define("2FOO", "something");
● You can access constants anywhere in
// This is valid, but should be avoided:
your script without regard to scope. // PHP may one day provide a "magical" constant
// that will break your script

define("__FOO__", "something");

echo foo;
FOO = "anotherthing";
// will generate error page
?>

Result :
something

Web Systems [502315-3] Dr. Afnan Bukhari 17


5. Arrays
Arrays
<?php
● An array in PHP is an ordered map. $arr = array("Tue" => "Tuesday", 12 => true);
● A map is a type that maps values to echo $arr["Tue"], "<br />";
keys. echo $arr[12] , "<br />";

● Function $arr = array(5 => 43, 32, 56, "b" => 12);
$arr = array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
array(key=>value, key=>value, …)
creates an array foreach ($arr as $key => $value) {
echo $key, '=>', $value, ', ';
● key either an integer or a string }
● value any PHP type ?>

● This type of arrays called associative Result:


array. Tuesday
1
● If no key given (as in example), the PHP
interpreter uses (maximum of the 5=>43, 6=>32, 7=>56, b=>12,
integer indices + 1).
● If an existing key, its value will be
overwritten.
Web Systems [502315-3] Dr. Afnan Bukhari 19
Arrays (cont.)
<?php
● You can set values in an array $arr = array(5 => 1, 12 => 2);
foreach ($arr as $key => $value) {
echo $key, '=>', $value, ', ';
● Function unset() removes a key/value }
$arr[] = 56; // the same as $arr[13] = 56;
pair. // foreach ($arr ...
$arr["x"] = 42; // adds a new element
// foreach ($arr ...
● Function array_values() makes re- unset($arr[5]); // removes the element
// foreach ($arr ...
indexing effect (indexing numerically unset($arr); // deletes the whole array
starting from 0) $a = array(1 => 'one', 2 => 'two', 3 => 'three');
// foreach ($a ...
unset($a[2]); Result:
// foreach ($a ...
$b = array_values($a);
5=>1, 12=>2,
// foreach ($b ... 5=>1, 12=>2, 13=>56,
?> 5=>1, 12=>2, 13=>56, x=>42,
12=>2, 13=>56, x=>42,
1=>one, 2=>two, 3=>three,
1=>one, 3=>three,
0=>one, 1=>three,

Web Systems [502315-3] Dr. Afnan Bukhari 20


Multi-Dimensional Arrays
<?php
● Arrays can be simple but If you want to $products = array(
array( ‘TIR’, ‘Tires’, 100 ),
store more than one piece of data array( ‘OIL’, ‘Oil’, 10 ),
about each product for example, you array( ‘SPK’, ‘Spark Plugs’, 4 )
);
could use a two-dimensional array.
for ($row = 0; $row < 3; $row++) {
for ($column = 0; $column < 3; $column++) {
echo '|'.$products[$row][$column];
}
echo '|<br />';
}
?>

Result:
|TIR|Tires|100|
● You could place a for loop inside |OIL|Oil|10|
another for loop to output the array |SPK|Spark Plugs|4|
elements.
● Note: for loops will be explained in the
next slides
Web Systems [502315-3] Dr. Afnan Bukhari 21
Multi-Dimensional Arrays
<?php
● Or define associative array defining $products = array(
array( ‘Code’ => ‘TIR’,
key=>value for each array ‘Description’ => ‘Tires’,
‘Price’ => 100
element. ),
array( ‘Code’ => ‘OIL’,
‘Description’ => ‘Oil’,
● Then output array elements using ),
‘Price’ => 10

for loop. array( ‘Code’ => ‘SPK’,


‘Description’ => ‘Spark Plugs’,
‘Price’ =>4
)
● Or by using each() and list() );

functions in a while loop. for ( $row = 0; $row < 3; $row++){


echo ‘|’.$products[$row][‘Code’].’|’.$products[$row][‘Description’].
‘|’.$products[$row][‘Price’].’|<br />’;
}

for ( $row = 0; $row < 3; $row++){


while ( list( $key, $value ) = each( $products[$row])){
Result (same output of previous slide): echo “|$value”;
|TIR|Tires|100| }
|OIL|Oil|10| echo ‘|<br />’;
}
|SPK|Spark Plugs|4| ?>

Web Systems [502315-3] Dr. Afnan Bukhari 22


6. Operators
Operators
<?php
● Arithmetic Operators: +, -, *, /, %, ++, --
● Assignment Operators: =, +=, -=, *=, /=, $a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
%= echo $b, "<br /> \n";
● Comparison Operators: ==, !=, >, <, >=, <= $a = "Hello ";
● Logical Operators: &&, ||, ! $a .= "World!";
echo $a, "<br /> \n";
● String Operators: . and .= (for string
?>
concatenation)

Example Is the same as


x+=y x=x+y
x-=y x=x-y Result:
Hello World!
x*=y x=x*y Hello World!
x/=y x=x/y
x%=y x=x%y
a.="text"; a=a."text"
Web Systems [502315-3] Dr. Afnan Bukhari 24
7. Conditionals
Conditionals: if, if..else
<?php
● PHP can execute a set of code depending on a $d = date("D");
condition. echo $d, "<br/>";
if ($d == "Fri" || $d == "Sat")
echo "Have a nice weekend! <br/>";
else
● Syntax: echo "Have a nice day! <br/>";
if (condition)
code to be executed if condition is true; $x = 10;
if ($x == 10) {
else
echo "Hello<br />";
code to be executed if condition is false; echo "Good morning<br />";
}
?>
● date() is a built-in PHP function that can be called
with many different parameters to return the
Result:
current date (and/or local time) in various formats. Sun If the current
● In this case we get a three-letter string for the day Have a nice day! day is
of the week. Hello Sunday
Good morning

Web Systems [502315-3] Dr. Afnan Bukhari 26


Conditionals: if.. elseif
<?php
● Syntax: $mark = 50;
if (condition) echo "student mark: $mark <br/>";
if ($mark >= 90)
code to be executed if condition is true; echo "student grade: A <br/>";
elseif (condition) elseif ($mark >= 80)
code to be executed if condition is false; echo "student grade: B <br/>";
elseif ($mark >= 70)
echo "student grade: C <br/>";
● Here, we can test condition in a group of elseif ($mark >= 60)
echo "student grade: D <br/>";
if..elseif statements as seen in the right else
echo "student grade: F <br/>";
example. ?>

Result:
student mark: 80
student grade: B

Web Systems [502315-3] Dr. Afnan Bukhari 27


Conditionals: switch
● Can check a value of expression and execute a set of <?php
$x = rand(1,5); // random integer
codes. echo "x = $x <br/><br/>";
● Syntax: switch ($x) {
switch (expression) case 1:
echo "Number 1";
{ break;
case label1: case 2:
//code to be executed if expression = label1; echo "Number 2";
break; break;
case label2: case 3:
echo "Number 3";
//code to be executed if expression = label2; break;
break; default:
default: echo "No number between 1 and 3";
//code to be executed break;
}
//if expression is different ?>
//from both label1 and label2;
break; Result could be:
} x=1
● rand is a built-in PHP function that generates a Or could be:
random number given a limit. No number between 1 and 3

Web Systems [502315-3] Dr. Afnan Bukhari 28


8. Looping
Looping: for
<?php
● Can loop depending on a counter. for ($i=1 ; $i<=5 ; $i++) {
echo "Hello World!<br />";
}
● Syntax: ?>
for (expression1; condition; expression2)
Result:
code to be executed once per iteration; Hello World!
Hello World!
Hello World!
● Loops through a block of code a specified
<?php Hello World!
number of times. $arr = array(‘item1’, ‘item2’); Hello World!
for ($i=0 ; $i<2 ; $i++) {
echo $arr[$i] . "<br />";
}
?>

Result:
item1
item2

Web Systems [502315-3] Dr. Afnan Bukhari 30


Looping: foreach
<?php
● PHP use foreach that is designed specifically for $a_array = array(1=>"one", 2=>"two", 3=>"three");
use with arrays. foreach ($a_array as $k => $v) {
echo "$k -> $v <br>";
● Because the indices in an array are not numbers, }
you cannot use a simple counter in a for loop to ?>

work with the array. <?php


$a_array = array(1, 2, 3, 4);
foreach ($a_array as $value) {
● Syntax: $value = $value * 2;
echo "$value <br>";
foreach ($array_name as $value) }
//code to be executed once per iteration; ?>

● Loops through a block of code for each element in Result: Result:


an array. 1 -> one 2
2 -> two 4
3 -> three 6
8

Web Systems [502315-3] Dr. Afnan Bukhari 31


Looping: while
<?php
● Can loop depending on a condition. $i = 1;
while($i <= 5) {
echo "The number is $i <br />";
● Syntax: $i++;
while (condition) }
?>
code to be executed once per iteration;
Result:
● Loops through a block of code if, and as long as, a The number is 1
The number is 2
specified condition is true
The number is 3
The number is 4
The number is 5

Web Systems [502315-3] Dr. Afnan Bukhari 32


Looping: do..while
<?php
● Can loop depending on a condition. $i = 0;
do {
$i++;
● Syntax: echo "The number is $i <br />";
do }
while($i <= 4);
code to be executed; ?>
while (condition);

● Loops through a block of code ONCE, and then


repeats the loop as long as a special condition is
true (so will always execute at least once).
Result:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Web Systems [502315-3] Dr. Afnan Bukhari 33


9. Functions
User Defined Functions
● User can define a function as the following: <?php
function writeMsg() {
● Syntax: echo "Hello world!";
function functionName() {
}
code to be executed; writeMsg(); // call the function
} ?>
Result:
● Can return a value of any type Hello world!

<?php <?php
function square($num) { function takes_array($input) {
return $num * $num; echo "$input[0] + $input[1] = ",
} $input[0]+$input[1];
echo square(2); }
?> $arr = array(1,2);
takes_array($arr);
?>
Result:
4 Result:
1 + 2 = 3

Web Systems [502315-3] Dr. Afnan Bukhari 35


User Defined Functions (cont.)
● Function Arguments: Information can be passed to functions through arguments.
An argument is like a variable. You can add as many arguments as you want, just
separate them with a comma.
<?php <?php
function firstName($fname) { function nameYear($fname, $year) {
echo "$fname<br>"; echo "$fname born in $year <br>";
} }
$name = "Mohammad";
firstName($name); nameYear("Mohammad", 1985);
firstName("Omar"); nameYear("Omar", 1990);
?> ?>
Result: Result:
Mohammad Mohammad born in 1985
Omar Omar born in 1990

Web Systems [502315-3] Dr. Afnan Bukhari 36


User Defined Functions (cont.)
● Default Argument Value: The following example shows how to use a default
parameter. If we call the function setHeight() without arguments it takes the
default value as argument:
<?php <?php
function setHeight($minHeight = 50) { function showUserPage($username = NULL) {
echo "The height is : $minHeight <br>"; if($username == NULL)
} echo "Page not found!";
setHeight(350); else
setHeight(); // will use the default value of 50 echo "User page for: $username <br>";
setHeight(135); }
setHeight(80); showUserPage("Abdullah");
?> showUserPage();
?>
Result:
The height is : 350 Result:
The height is : 50 User page for: Abdullah
The height is : 135 Page not found!
The height is : 80

Web Systems [502315-3] Dr. Afnan Bukhari 37


User Defined Functions (cont.)
● Returning values: To let a function return a value, use the return statement:
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
//echo "2 + y = " . sum(2);
?>
Result:
5 + 10 = 15
7 + 13 = 20
2 + 4 = 6
2 + y = 3

Web Systems [502315-3] Dr. Afnan Bukhari 38


User Defined Functions (cont.)
● Passing Arguments by Reference: In PHP, arguments are usually passed by value,
which means that a copy of the value is used in the function and the variable that was
passed into the function cannot be changed.
● When a function argument is passed by reference, changes to the argument also
change the variable that was passed in. To turn a function argument into a reference,
the & operator is used.
<?php Result:
function add_five(&$value) { 7
$value += 5;
}

$num = 2;
add_five($num);
echo $num;
?>

Web Systems [502315-3] Dr. Afnan Bukhari 39


10. Variables Scope
Variables Scope
● In PHP, variables can be declared anywhere in the script.

● The scope of a variable is the part of the script where the variable can be
referenced/used.

● PHP has three different variable scopes:


○ local
○ global
○ static

Web Systems [502315-3] Dr. Afnan Bukhari 41


Variables Scope (cont.)
● Global and Local Scope
● A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:
<?php
$x = 5; // global scope Result:

function myTest() { Variable x inside function is:


// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>"; Variable x outside function is: 5
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>

Web Systems [502315-3] Dr. Afnan Bukhari 42


Variables Scope (cont.)
● Global and Local Scope
● A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:
<?php
function myTest() { Result:
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>"; Variable x inside function is: 5
}
myTest(); Variable x outside function is:

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

You can have local variables with the same name in different functions, because local
variables are only recognized by the function in which they are declared.

Web Systems [502315-3] Dr. Afnan Bukhari 43


Variables Scope (cont.)
● PHP The global Keyword: the global keyword is used to access a global variable
from within a function.
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y; Result:
$y = $x + $y;
15
}
myTest();
echo $y; // outputs 15
?>

Web Systems [502315-3] Dr. Afnan Bukhari 44


Variables Scope (cont.)
● PHP also stores all global variables in an array called $GLOBALS[index]. The index
holds the name of the variable. This array is also accessible from within functions
and can be used to update global variables directly.
<?php
$x = 5;
$y = 10;

function addition() { Result:


$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
} 15

addition();
echo $z;
?>

Web Systems [502315-3] Dr. Afnan Bukhari 45


Variables Scope (cont.)
● PHP The static Keyword: Normally, when a function is completed/executed, all of
its variables are deleted. However, sometimes we want a local variable NOT to be
deleted. We need it for a further job.

● To do this, use the static keyword when you first declare the variable:
<?php Result:
function myTest() { 10
static $x = 0; 20
$x = $x + 10; 30
echo $x;
}
Then, each time the function is called, that
myTest(); variable will still have the information it
myTest(); contained from the last time the function
myTest(); was called.
?>

Web Systems [502315-3] Dr. Afnan Bukhari 46


11. Including Files
Including Files
● The include (or require) statement takes all the text/code/markup that exists in the specified
file and copies it into the file that uses the include statement.

● Including files is very useful when you want to include the same PHP, HTML, or text on multiple
pages of a website.

● The include and require statements are identical, except upon failure:
○ require will produce a fatal error (E_COMPILE_ERROR) and stop the script
○ include will only produce a warning (E_WARNING) and the script will continue

● Syntax:
include 'filename';
or
require 'filename';

Web Systems [502315-3] Dr. Afnan Bukhari 48


Including Files (cont.)
● Example 1: Assume we have a standard <?php
footer file called "footer.php", that echo "<p>Copyright &copy; 1999-" . date("Y") . "
W3Schools.com</p>";
looks like this: ?>

<html>
● To include the footer file in a page, use <body>
the include statement:
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php'; ?>

</body>
</html>

Web Systems [502315-3] Dr. Afnan Bukhari 49


Including Files (cont.)
● Example 2: Assume we have a standard <?php
menu file called "menu.php": echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript
Tutorial</a> -
<a href="/php/default.asp">PHP Tutorial</a>';
?>
<html><body>
● All pages in the Web site should use <div class="menu">
this menu file. Here is how it can be <?php include 'menu.php'; ?>
done (we are using a <div> element so </div>

that the menu easily can be styled with <h1>Welcome to my home page!</h1>
CSS later): <p>Some text.</p>
<p>Some more text.</p>
</body></html>

Web Systems [502315-3] Dr. Afnan Bukhari 50


Thanks!

Does anyone have any questions?

[email protected]

51

You might also like