0% found this document useful (0 votes)
2 views31 pages

06 PHP

This document provides an overview of PHP, including its basics, syntax, and server-side functionality. It covers topics such as variables, arrays, operators, conditionals, loops, user-defined functions, and file inclusion. Additionally, it outlines PHP's integration with HTML and its compatibility with various web servers and databases.

Uploaded by

randa19112013
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)
2 views31 pages

06 PHP

This document provides an overview of PHP, including its basics, syntax, and server-side functionality. It covers topics such as variables, arrays, operators, conditionals, loops, user-defined functions, and file inclusion. Additionally, it outlines PHP's integration with HTML and its compatibility with various web servers and databases.

Uploaded by

randa19112013
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/ 31

541106 1611

Lecture 6: PHP

Ouissem Ben Fredj


[email protected]
http://lms.tu.edu.sa/
502261-3 – Web Systems

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

Other server-side alternatives try to avoid the drawbacks


● 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 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.
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
● 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)
● PHP: Hypertext Preprocessor
What do You Need?

Our server supports PHP


You don't need to do anything special!
You don't need to compile anything or install any extra tools!
Create some .php files in your web directory - and the server will parse them for
you.

Most servers support PHP


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
Help with PHP

Loads of information, including help on individual PHP


functions may be found at
http://php.net/
Basic PHP syntax
A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be
placed (almost) anywhere in an HTML document.
<html> print and echo
<!-- hello.php --> for output
<head><title>Hello World</title></head>
<body>
<p>This is going to be ignored by the PHP interpreter.</p> a semicolon (;) at the
<?php echo '<p>While this is going to be parsed.</p>'; ?> end of each statement
<p>This will also be ignored by the PHP preprocessor.</p>
<?php print('<p>Hello and welcome to <i>my</i> page!</p>');
?>
<?php // for a single-line
//This is a comment comment
/*
This is /* and */ for a large
a comment block comment block.
*/
?> view the output page
</body>
</html>
The server executes the print and echo statements, substitutes output.
Scalars
All variables in PHP start with a $ sign symbol. A variable's type is determined by
the context in which that variable is used (i.e. there is no strong-typing in PHP).
<html><head></head>
<!-- scalars.php -->
<body> <p>
<?php Four scalar types:
$foo = true; if ($foo) echo "It is TRUE! <br /> \n"; boolean
$txt='1234'; echo "$txt <br /> \n"; true or false
$a = 1234; echo "$a <br /> \n";
$a = -123; echo "$a <br /> \n";
integer,
$a = 1.234; echo "$a <br /> \n"; float,
$a = 1.2e3; echo "$a <br /> \n"; floating point
$a = 7E-10; echo "$a <br /> \n"; numbers
echo 'Arnold once said: "I\'ll be back"', "<br /> \n"; string
$juice= ‘Nadek'; echo "$juice 's taste is great <br /> \n";
$str = <<<EOD
single quoted
Example of string double quoted
spanning multiple lines
using “heredoc” syntax.
EOD;
echo $str; view the output page
?>
</p></body></html>
Arrays
An array in PHP is actually an ordered map. A map is a type that maps values to keys.

<?php array() = creates arrays


$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar key = either an integer or a
echo $arr[12]; // 1 string.
?>
value = any PHP type.
if no key given (as in example), the PHP interpreter
<?php uses (maximum of the integer indices + 1).
array(5 => 43, 32, 56, "b" => 12);
if an existing key, its value will be overwritten.
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>

<?php can set values in an array


$arr = array(5 => 1, 12 => 2);
foreach ($arr as $key => $value) { echo $key, '=>',
$value); } unset() removes a key/value pair
$arr[] = 56; // the same as $arr[13] = 56;
$arr["x"] = 42; // adds a new element
array_values() makes reindexing effect
unset($arr[5]); // removes the element (indexing numerically)
unset($arr); // deletes the whole array
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
$b = array_values($a); view the output page *Find more on arrays

?>
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

// Valid constant names


define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more"); You can access constants
anywhere in your script
// Invalid constant names (they shouldn’t start without regard to scope.
// with a number!)

define("2FOO", "something");

// This is valid, but should be avoided:


// PHP may one day provide a "magical" constant
// that will break your script

define("__FOO__", "something");

?>
Operators

Arithmetic Operators: +, -, *,/ , %, ++, -- Example Is the same as


x+=y x=x+y
Assignment Operators: =, +=, -=, *=, /=, %= x-=y x=x-y
x*=y x=x*y
x/=y x=x/y
x%=y x=x%y
Comparison Operators: ==, !=, >, <, >=, <=
Logical Operators: &&, ||, !
String Operators: . and .= (for string concatenation)

$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> INFO_GENERAL The configuration line,


<!– info.php php.ini location,
<body> build date,
<?php Web Server,
// Show all PHP information System and more
phpinfo(); INFO_CREDITS PHP 4 credits
?> INFO_CONFIGURATION Local and master
<?php values
// Show only the general information for php directives
phpinfo(INFO_GENERAL); INFO_MODULES Loaded modules
?> INFO_ENVIRONMENT Environment
</body> variable
</html> information
INFO_VARIABLES All predefined variables
view the output from EGPCS
page
INFO_LICENSE PHP license information
INFO_ALL Shows all of the above (default)
X
Server Variables
The $_SERVER array variable is a reserved variable that contains all server information.

<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.

<?php For w, and a, if no file exists, it tries to create


$fh=fopen("welcome.txt","r"); it (use with caution, i.e. check that this is the
?> case, otherwise you’ll overwrite an existing
file).
For x if a file exists, this function fails
<?php (and returns 0).
if
( !($fh=fopen("welcome.txt","r")) ) If the fopen() function is unable to open
exit("Unable to open file!"); the specified file, it returns 0 (false).
?>
X
File Workings
fclose() closes a file. feof() determines if the end is true.

fgetc() reads a single character fgets() reads a line of data

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

function confirm_form($f_name, $l_name, $email, $os)


{
?>
<h2>Thanks! Below is the information you have sent to us.</h2>
<h3>Contact Info</h3>
<?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"])
{
?>

<h3>Please enter your information</h3>


<p>Fields with a "<b>*</b>" are required.</p>

<?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.

You might also like