06 PHP
06 PHP
Lecture 6: PHP
Taif University
College of Computers and Information Technology
Objectives
PHP Basics:
● Introduction to PHP
• a PHP file, PHP workings, running PHP.
● Basic PHP syntax
• variables, operators, if...else...and switch, while, do while, and for.
● Some useful PHP functions
● How to work with
• HTML forms, cookies, files, time and date.
● How to create a basic checker for user-entered data
Server-Side Dynamic Web Programming
?>
X
Constants
A constant is an identifier (name) for a simple value. A constant is case-sensitive by
default. By convention, constant identifiers are always uppercase.
<?php
define("2FOO", "something");
define("__FOO__", "something");
?>
Operators
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!";
Conditionals: if else
Can execute a set of code depending on a condition
<html><head></head> if (condition)
<!-- if-cond.php -->
<body>
code to be executed if
condition is true;
<?php else
$d=date("D");
echo $d, "<br/>";
code to be executed if
if ($d==“Wed") condition is false;
echo "Have a nice weekend! <br/>";
else
echo "Have a nice day! <br/>";
date() is a built-in PHP
$x=10; function that can be called
if ($x==10) with many different
{
echo "Hello<br />";
parameters to return the date
echo "Good morning<br />"; (and/or local time) in various
} formats
view the output
?>
page In this case we get a three
</body> letter string for the day of the
</html>
week.
Conditionals: switch
Can select one of many sets of lines to execute
<html><head></head>
<body>
<!–- switch-cond.php -->
<?php
$x = rand(1,5); // random integer switch (expression)
echo "x = $x <br/><br/>"; {
switch ($x) case label1:
{ code to be executed if expression = label1;
case 1: break;
echo "Number 1"; case label2:
break; code to be executed if expression = label2;
case 2: break;
echo "Number 2"; default:
break; code to be executed
case 3: if expression is different
echo "Number 3"; from both label1 and label2;
break; break;
default: }
echo "No number between 1 and 3";
break;
}
?> view the output
page
</body>
Looping: while and do-while
Can loop depending on a condition
<html><head></head> <html><head></head>
<body> <body>
<?php <?php
$i=1; $i=0;
while($i <= 5) do
{ {
echo "The number is $i <br />"; $i++;
$i++; echo "The number is $i <br />";
} }
?> view the output page while($i <= 10);
?> view the output page
</body>
</html> </body>
</html>
loops through a block of code if, and
loops through a block of code once,
as long as, a specified condition is
and then repeats the loop as long as
true
a special condition is true (so will
always execute at least once)
Looping: for and foreach
Can loop depending on a "counter"
<?php <?php
$a_array = array(1, 2, 3, 4);
for ($i=1; $i<=5; $i++)
{ foreach ($a_array as $value)
{
echo "Hello World!<br />";
} $value = $value * 2;
echo "$value <br/> \n";
?>
}
loops through a block of code ?>
a specified number of times
<?php
$a_array=array("a","b","c");
foreach ($a_array as $key => $value)
{
view the output page echo $key . " = " . $value . "\n";
}
?>
loops through a block of code for each element in an
array
User Defined Functions
Can define a function using syntax such as the following:
<?php Can also define conditional
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
functions, functions within
{
functions, and recursive functions.
echo "Example function.\n";
return $retval;
}
?>
<?php
Can return a value of any type
function small_numbers(){
<?php return array (0, 1, 2);
function square($num){return $num * $num;} }
echo square(4); list ($zero, $one, $two) = small_numbers();
?> echo $zero, $one, $two;
?>
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
takes_array(array(1,2)); view the output
?> page
X
Variable Scope
The scope of a variable is the context within which it is defined.
<?php
$a = 1; /* limited variable scope */ The scope is local within functions,
function Test() and hence the value of $a is
{ undefined in the “echo” statement.
echo $a; /* reference to local scope variable */
}
Test();
?>
<?php <?php
$a = 1; function Test()
global static
$b = 2; {
function Sum() refers to its static $a = 0; does not lose its
{ global echo $a; value.
global $a, $b; version. $a++;
$b = $a + $b; }
} Test1();
Sum(); Test1();
echo $b; Test1();
view the output page
?> ?>
Including Files
The include() statement includes and evaluates the specified file.
// vars.php <?php
<?php function foo()
$color = 'green'; {
$fruit = 'apple'; global $color;
?> include ('vars.php‘);
echo "A $color $fruit";
// test.php }
<?php
echo "A $color $fruit"; // A /* vars.php is in the scope of foo() so *
include 'vars.php'; * $fruit is NOT available outside of this *
echo "A $color $fruit"; // A green apple * scope. $color is because we declared it *
* as global. */
view the output
?> foo(); // A green apple
page echo "A $color $fruit"; // A green
?> view the output
page
*The scope of variables in “included” files depends on where the “include” file
is added!
You can use the include_once, require, and require_once statements in similar
X
PHP Information
The phpinfo() function is used to output PHP information about the version installed on the server, parameters
selected when installed, etc.
<html><head></head>
<body>
<?php
echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";
echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";
echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];
?>
<?php
echo "<br/><br/><br/>";
echo "<h2>All information</h2>";
foreach ($_SERVER as $key => $value) $_SERVER info on php.net
{
echo $key . " = " . $value . "<br/>";
}
?>
view the output
</body> page
</html>
The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP
script.
X
File Open
The fopen("file_name","mode") function is used to open files in PHP.
r Read only. r+ Read/Write.
w Write only. w+ Read/Write.
a Append. a+ Read/Append.
x Create and open for write only. x+ Create and open for read/write.
fwrite(), fputs () writes a string with and without file() reads entire file into an array
\n
<?php <?php
$myFile = "welcome.txt"; $myFile = "welcome.txt";
if (!($fh=fopen($myFile,'r'))) $fh = fopen($myFile, 'r');
exit("Unable to open file."); $theData = fgets($fh);
while (!feof($fh)) fclose($fh);
{ echo $theData; view the output
$x=fgetc($fh); ?> page
echo $x;
} <?php
fclose($fh); view the output $myFile = "testFile.txt";
?> page $fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
<?php
fwrite($fh, $stringData);
$lines = file('welcome.txt');
$stringData = "New Stuff 2\n";
foreach ($lines as $l_num => $line)
fwrite($fh, $stringData);
{
echo "Line #{$l_num}:“ .$line.”<br/>”;
fclose($fh); view the output
?>
} view the output page
?>
page
Form Handling
Any form element is automatically available via one of the built-in PHP variables
(provided that HTML element has a “name” defined with it).
<html>
<-- form.html -->
<body>
<form action="welcome.php" method="post">
Enter your name: <input type="text" name="name" /> <br/>
Enter your age: <input type="text" name="age" /> <br/>
<input type="submit" /> <input type="reset" />
</form>
</body></html>
<html> $_POST
<!–- welcome.php --> contains all POST data.
<body>
$_GET
Welcome <?php echo $_POST["name"]."."; ?><br /> contains all GET data.
You are <?php echo $_POST["age"]; ?> years old!
$_REQUEST contains all
</body> view the output data (both GET and
</html> page POST)
X
Cookie Workings
setcookie(name,value,expire,path,domain) creates cookies.
<?php
setcookie("uname", $_POST["name"], time()+36000);
?>
NOTE:
<html><body> setcookie() must appear
<p> BEFORE <html> (or any
Dear <?php echo $_POST["name"] ?>, a cookie was set on output) as it’s part of the
this page! The cookie will be active when the client has sent header information sent
the cookie back to the server. with the page.
</p> view the output
</body></html> page
<html>
$_COOKIE
<body> contains all COOKIE data.
<?php
if ( isset($_COOKIE["uname"]) ) isset()
echo "Welcome " . $_COOKIE["uname"] . "!<br />"; finds out if a cookie is set
else
echo "You are not logged in!<br />";
view the output use the cookie name as a
?> page variable
</body></html>
X
Getting Time and Date
date() and time () formats a time or a date.
<?php
//Prints something like: Monday
echo date("l");
date() returns a string
//Like: Monday 15th of January 2003 05:51:38 AM
formatted according to
echo date("l jS \of F Y h:i:s A");
the specified format.
//Like: Monday the 15th
echo date("l \\t\h\e jS");
view the output
?> page
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs time() returns
echo 'Now: '. date('Y-m-d') ."\n"; current Unix
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
?>
timestamp
view the output
page
*Here is more on date/time formats:
http://uk.php.net/manual/en/function.date.php
Required Fields in User-Entered Data
A multipurpose script which asks users for some basic contact information and then checks to
see that the required fields have been entered.
<html>
<!-- form_checker.php -->
<head><title>PHP Form example</title></head><body>
<?php
/*declare some functions*/
function print_form($f_name, $l_name, $email, $os) Print Function
{
?>
<form action="form_checker.php" method="post">
First Name: <input type="text" name="f_name" value="<?php echo $f_name?>" /> <br/>
Last Name <b>*</b>:<input type="text" name="l_name" value="<?php echo $l_name?>"
/> <br/>
Email Address <b>*</b>:<input type="text" name="email" value="<?php echo $email?>"
/> <br/>
Operating System: <input type="text" name="os" value="<?php echo $os?>" /> <br/><br/>
<input type="submit" name="submit" value="Submit" /> <input type="reset" />
</form>
<?php
} //** end of "print_form" function
Check and Confirm Functions
function check_form($f_name, $l_name, $email, $os)
{
if (!$l_name||!$email){
echo "<h3>You are missing some required fields!</h3>";
print_form($f_name, $l_name, $email, $os);
}
else{
confirm_form($f_name, $l_name, $email, $os);
}
} //** end of "check_form" function
if (!$_POST["submit"])
{
?>
<?php
print_form("","","","");
}
else{
check_form($_POST["f_name"],$_POST["l_name"],$_POST["email"],$_POST["os"]);
}
?>
view the output
page
</body>
</html>
Learning Outcomes
In the last lectures you have learned
● What is PHP and what are some of its workings.
● Basic PHP syntax
• variables, operators, if...else...and switch, while, do while, and for.
● Some useful PHP functions
● How to work with
• HTML forms, cookies, files, time and date.
● How to create a basic checker for user-entered data.