Lec 5.1-PHP
Lec 5.1-PHP
1
Content
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
2
Introduction to PHP
3
Introduction to PHP
• Developed in 1995 by Rasmus Lerdorf (member of the Apache Group)
▪ originally designed as a tool for tracking visitors at Lerdorf's Web site
▪ within 2 years, widely used in conjunction with the Apache server
▪ free, open-source
▪ 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
▪ when a page request arrives, the server recognizes PHP content via the file extension (.php or .phtml)
▪ 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)
▪ PHP: Hypertext Preprocessor
4
Basic PHP syntax
<html>
<!-- hello.php CS443 -->
<head><title>Hello World</title></head> A PHP scripting block always starts with <?php
<body> and ends with ?>. A PHP scripting block can be
<p>This is going to be ignored by the PHP interpreter.</p>
placed (almost) anywhere in an HTML document.
<?php echo '<p>While this is going to be parsed.</p>';
?>
print and echo
<p>This will also be ignored by the PHP preprocessor.</p>
<?php print('<p>Hello and welcome to <i>my</i> for output
page!</p>');
?>
<?php a semicolon (;)
//This is a comment at the end of each
/* statement
This is
a comment
block
*/ // for a single-line comment
?>
</body> /* and */ for a large
</html> comment block.
view the output page
The server executes the print and echo statements, substitutes output.
Scalars
<html><head></head>
<!-- scalars.php CS443 -->
<body> <p>
<?php
$foo = true; if ($foo) echo "It is TRUE! <br /> \n";
$txt='1234'; echo "$txt <br /> \n"; All variables in PHP start with a $ sign
$a = 1234; echo "$a <br /> \n";
$a = -123; symbol. A variable's type is
echo "$a <br /> \n";
$a = 1.234;
determined by the context in which
echo "$a <br /> \n"; that variable is used (i.e. there is no
$a = 1.2e3;
echo "$a <br /> \n"; strong-typing in PHP).
$a = 7E-10;
echo "$a <br /> \n";
echo 'Arnold once said: "I\'ll be back"', "<br /> \n";
$beer = 'Heineken'; Four scalar types:
echo "$beer's taste is great <br /> \n";
$str = <<<EOD boolean
Example of string
spanning multiple lines
true or false
using “heredoc” syntax. integer,
EOD;
echo $str; float,
?>
</p> floating point numbers
</body>
</html>
string
single quoted
view the output page double quoted
Arrays
<?php array() = creates arrays
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar key = either an integer or a string.
echo $arr[12]; // 1
?> value = any PHP type.
if no key given (as in example), the PHP
<?php
array(5 => 43, 32, 56, "b" => 12);
interpreter uses (maximum of the integer
array(5 => 43, 6 => 32, 7 => 56, "b" => 12); indices + 1).
?> if an existing key, its value will be overwritten.
<?php can set values in an array
$arr = array(5 => 1, 12 => 2);
foreach ($arr as $key => $value) { echo $key, '=>',
$value); } unset() removes a
$arr[] = 56; // the same as $arr[13] = 56; key/value pair
$arr["x"] = 42; // adds a new element
unset($arr[5]); // removes the element array_values()
unset($arr); // deletes the whole array makes reindexing effect
$a = array(1 => 'one', 2 => 'two', 3 => 'three'); (indexing numerically)
unset($a[2]);
$b = array_values($a);
?>
view the output page *Find more on arrays
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("__FOO__", "something");
?>
Operators
Example Is the same as
• Arithmetic Operators: +, -, *,/ , %, ++, -- x+=y x=x+y
x-=y x=x-y
• Assignment Operators: =, +=, -=, *=, /=, %= x*=y
x/=y
x=x*y
x=x/y
x%=y x=x%y
$a = "Hello ";
$a .= "World!";
Conditionals: if else
Can execute a set of code depending on a condition
<html><head></head>
<!-- if-cond.php CS443 -->
if (condition)
<body> code to be executed if condition
is true;
<?php
$d=date("D"); else
echo $d, "<br/>"; code to be executed if condition
if ($d=="Fri")
echo "Have a nice weekend! <br/>";
is false;
else
echo "Have a nice day! <br/>";
$x=10;
if ($x==10) date() is a built-in PHP function
{ that can be called with many
echo "Hello<br />"; different parameters to return the
echo "Good morning<br />"; date (and/or local time) in
}
various formats
?>
<?php <?php
$i=1; $i=0;
while($i <= 5) do
{ {
echo "The number is $i <br />"; $i++;
$i++; echo "The number is $i <br />";
} }
?> while($i <= 10);
?>
</body>
</body>
</html> view the output page </html> view the output page
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
true as a special condition is true (so
will always execute at least once)
Looping: for and foreach
Can loop depending on a "counter"
<?php <?php
for ($i=1; $i<=5; $i++) $a_array = array(1, 2, 3, 4);
{ 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)
{
echo $key . " = " . $value . "\n";
}
view the output page ?>
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
takes_array(array(1,2));
?> view the output page
Variable Scope
The scope of a variable is the context within which it is defined.
<?php
$a = 1; /* limited variable scope */
function Test()
{
echo $a; The scope is local within functions,
/* reference to local scope variable */ and hence the value of $a is
}
Test();
undefined in the “echo” statement.
?>
<?php <?php
$a = 1; function Test()
$b = 2; global { static
function Sum() static $a = 0;
{ refers to its echo $a; does not lose
global $a, $b; global $a++; its value.
$b = $a + $b; }
}
version. 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;
*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 ways.
PHP Information
The phpinfo() function is used to output PHP information about the version installed on the server, parameters
<?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)
{
echo $key . " = " . $value . "<br/>"; $_SERVER info
} on php.net
?>
</body>
</html>
view the output page
The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.
File Open
The fopen("file_name","mode") function is used to open files in PHP.
<html> $_POST
<!–- welcome.php COMP 519 -->
<body> contains all POST data.
Welcome <?php echo $_POST["name"]."."; ?><br />
You are <?php echo $_POST["age"]; ?> years old!
$_GET
contains all GET data.
</body>
</html>
Print Function
function print_form($f_name, $l_name, $email, $os)
{
?>
<?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
<?php
echo "Name: $f_name $l_name <br/>";
echo "Email: $email <br/>";
echo "OS: $os";
} //** end of "confirm_form" function
Main Program
/*Main Program*/
if (!$_POST["submit"])
{
?>
<?php
print_form("","","","");
}
else{
check_form($_POST["f_name"],$_POST["l_name"],$_POST["email"],$_POST["os"]);
}
?>
</body>
</html> view the output page
Learning Outcomes
In the lecture 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.
28