Chapter 4 Final
Chapter 4 Final
Basics of PHP
Internet Programming
Mr. Abel T.
Contents
Introduction
Features of PHP
Displaying Errors
Functions
Web Programming 2
Server-side programming
Server-side pages are programs written using one of many
web programming languages/frameworks
Scripts (programs) are stored on the server and are
executed on request (from a client).
Result of execution is sent to client in the form of HTML.
The server side script/program itself is never returned to
the client!
My be written in a wide variety of programming/scripting
languages.
▪ php, asp, c/c++, perl, java, …
Can perform several powerful operations.
▪ Examples: PHP, Java/JSP, Ruby on Rails, ASP.NET,
Python, Perl
Web Programming 3
Cont’d
Also called server side scripting:
▪ Dynamically edit, change or add any content to a Web
page
▪ Respond to user queries or data submitted from HTML
forms
▪ Access any data or databases and return the results to a
browser
▪ Customize a Web page to make it more useful for
individual users
▪ Provide security since your server code cannot be viewed
from a browser
Web Programming 4
Cont’d
Web server:
▪ contains software that allows it to run server side
programs
▪ sends back their output as responses to web
requests
Each language/framework has its pros and cons
▪ we use PHP
Web Programming 5
What is PHP?
PHP stands for "PHP Hypertext Preprocessor“
Open-source, server-side scripting language
Used to make web pages dynamic:
▪ provide different content depending on context - dynamic
▪ interface with other services: database, e-mail, etc.
▪ authenticate users
▪ process form information
can be embedded within HTML code
Object Orientation supported
Source-code not visible by client
▪ ‘View Source’ in browsers does not display the PHP code
Various built-in functions allow for fast development
Compatible with many popular databases
Web Programming 6
Lifecycle of a PHP web request
Web Programming 7
Where does PHP fit?
server
Page
HTTP
Request
Added
Internet or Web
function
Intranet Server
ality
Web Browser
Web Web
page page
Server-side
Client-side
“Dynamic pages”
“Active pages”
CGI, SSI, Server
JavaScript, VBScript,
API, ASP, JSP, PHP,
Applet, ActiveX
COM/DCOM,
CORBA
Active and dynamic page technology can be used
together – server-side program generates customized
active pages
Web Programming 8
Server-side execution using PHP Script
Web-Client Web-Server
PHP
Web-Browser WWW Script
Response Response
Reply
Web Programming 9
Putting it all together
Web-Client Database
Web-Server Server
HTML-Form
(+JavaScript) Submit Call PHP DBMS
Data interpreter LAN
PHP SQL
Web-Browser WWW Script commands
Response Response Database
Reply Output
Web Programming 10
Including PHP in a Web Page
There are 4 ways of including PHP in a web page
1. <?php echo("Hello world"); ?>
2. <script language = "php">
echo("Hello world");
</script>
3. <? echo("Hello world"); ?>
4. <% echo("Hello world"); %>
You can also use print instead of echo
Method (1) is clear and unambiguous
Method (2) is useful in environments supporting mixed
scripting languages in the same HTML file (most do not)
Methods (3) and (4) depend on the server configuration
Web Programming 11
Basic PHP Syntax
Syntax
▪ PHP code should enclosed within:
<?php and ?>
So that it is distinguished from HTML.
▪ Hence, the PHP parser only parses code which is in between
<?php and ?>
• PHP code can be embedded in HTML
▪ Contents between <?php and ?> are executed as PHP code
▪ All other contents are output as pure HTML
Example: HTML content
<p>This is going to be ignored.</p> <?php
<?php echo 'While this is going to be parsed.'; ?> PHP code
?>
<p>This will also be ignored.</p> HTML content ...
Web Programming 12
Hello World!
<?php
print "Hello, world!";
?> PHP
Web Programming 13
Comments
# single-line comment
# another single-line comment style
/*
multi-line comment
*/
like Java and JavaScript but # is also allowed
- a lot of PHP code uses # comments instead of //
Web Programming 14
Data Types
Boolean (bool or boolean)
▪ Simplest of all
▪ Can be either TRUE or FALSE
Integer (int or integer)
▪ Hold integer values (signed or unsigned)
Floating point (float or double or real)
▪ Hold floating point values
String (string)
▪ Hold strings of characters within either ‘ or ‘’
▪ Escaping of special characters can be done using \
▪ Ex. “this is a string”, ‘this is another string’, “yet
\”another\” one”
Web Programming 15
Cont’d
Array
▪ Collection of values of the same data type
Object
▪ Instance of a class
Resource
▪ Hold a reference to an external resource created by
some functions
NULL
▪ Represents that a variable has no value
▪ A variable is considered to be NULL if
• it has been assigned the constant NULL.
• it has not been set to any value yet.
• it has been unset()
Web Programming 16
Type Casting
The casts allowed are:
▪ (int), (integer) - cast to integer
▪ (bool), (boolean) - cast to boolean
▪ (float), (double), (real) - cast to float
▪ (string) - cast to string
▪ (array) - cast to array
▪ (object) - cast to object
Web Programming 17
Variables
Variable names always begin with dollar sign ($), on both
declaration and usage
names are case sensitive
Valid variable name → starts with letter or underscore,
followed by any number of letters, numbers, or
underscores
PHP is not strongly typed
▪ No variable declaration ( implicit )
▪ To create a variable, just assign some value to it!
Example:
$myNum = 5; //declares and assigns 5 to variable $myNum
$var = 'Bob';
$4site = 'not yet'; //invalid; starts with number
Web Programming 18
Cont’d
❑ basic types: int, float, boolean, string, array, object,
NULL
• test type of variable with is_type functions, e.g.
is_string
• gettype function returns a variable's type as a string
❑ PHP converts between types automatically in many
cases:
• string → int auto-conversion on +
• int → float auto-conversion on /
❑ type-cast with (type):
• $age = (int) "21";
Web Programming 19
Cont’d
Referencing
$var1 = “some string”;
$var2 = &$var1;
$var2 = “another string”
echo $var1; //another string
echo $var2; //another string
Web Programming 20
Cont’d
Variables within double quoted strings (“”) are
parsed
Example
$name = “Abebe”;
$message = “Hello $name”;
echo $message; //Hello Abebe
Variables within single quoted strings (‘’) are not
parsed!
Example
$name = “Abebe”;
$message = ‘Hello $name’;
echo $message; //Hello $name
Web Programming 21
Cont’d
Array variables
▪ Can be created using the array() construct.
Syntax: array( [ key => ] value, … )
key : can be an integer or a string
value : can be any value
Example
<?php
$arr = array( "foo", "bar” );
echo $arr[0]; // foo
echo $arr[1]; // bar
?>
Web Programming 22
Cont’d
Example
<?php
$arr = array("foo" => "bar", 12 => true);
Example
<?php
$arr = array("somearray" => array(6 => 5, 13
=> 9, "a" => 42));
echo $arr["somearray"][6]; // 5
echo $arr["somearray"][13]; // 9
echo $arr["somearray"]["a"]; // 42
Intern
?> 24
Variables (cont’d)
▪ If you do not specify a key for a given value,
then the maximum of the integer indices is
taken, and the new key will be that maximum
value + 1.
• If no integer indices exist yet, the key will be 0
(zero).
▪ If you specify a key that already has a value
assigned to it, that value will be overwritten.
Example
<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);
25
Intern
Variables (cont’d)
❖Creating/modifying with square-bracket
syntax
▪ You can also modify an existing array by
explicitly setting values in it
Syntax
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value
▪ If $arr doesn't exist yet, it will be created
▪ To change a certain value, just assign a new
26
Intern
value to an element specified with its key.
Variables (cont’d)
Example
<?php
$arr = array(5 => 1, 12 => 2);
29
Intern
Variables (cont’d)
❖Strings
▪ Three types of string literals
• Single quoted
– $str1 = ‘some string’;
• Double quoted
– $str2 = “some other string”;
• Heredoc
– $str3 = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
30
Intern
Variables (cont’d)
❖Character escaping
▪ If the string is enclosed in double-quotes ("),
PHP understands more escape sequences for
special characters:
sequence meaning
\n linefeed
\r carriage return
\t horizontal tab
\\ backslash
\$ dollar sign
\" 31
double-quote
Intern
Variables (cont’d)
▪ Variable parsing
variables within double quoted strings are
parsed.
Example
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works
echo "He drank some $beers"; // won't work
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
32
Intern ?>
Variables (cont’d)
❖String concatenation
▪ Use the . (dot) operator
Example
<?php
$var1 = “Today is “;
$message = $var1 . date(“d-m-Y”); //Today is
28-12-2007
?>
❖Indexing strings
▪ $str[index]
33
Intern ▪ String index starts with 0 (similar to arrays)
Output
❖Three types of output
▪ Using the function echo
• Syntax: echo $var or echo string_constant
▪ Using short tags
• Syntax: <?= $var ?>
▪ Using heredoc
• Syntax:
echo <<<LABEL
….
LABEL;
* LABEL must be placed in the first column of a new line.
* Special characters, like “, need not be escaped
34
Intern
Arithmetic Operations
Operators
▪ Addition + 1+1
▪ Subtraction - $x - 5
▪ Multiplication * 2 * $y
▪ Division / $a / $b
▪ Modulus % $c % 2
Automatic Conversion
▪ "Lucky numbers are $n1 and $n2"
Web Programming 35
Control Structures
Control Structures: Are the structures within a language
that allow us to control the flow of execution through a
program or script.
Grouped into conditional (branching) structures (e.g. if/else)
and repetition structures (e.g. while loops)
Example if/else if/else statement:
if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;}
Web Programming 36
Input
Input to server side scripts comes from clients through
forms
Two methods of sending data: GET & POST
▪ GET
• Search queries and small amounts of data
• Also generated when a user clicks on a link
• Non secure (displayed in address bar)
▪ POST
• Large and secure data
▪ The default method for HTML forms is GET
To access form field values in PHP, use the built-in
PHP arrays: $_GET and $_POST respectively for GET
and POST request methods
Web Programming 37
Cont’d
The names of the form fields will be used as indices in the
respective arrays
For example, to access the value of an input box named
‘first_name’ in a form whose method is POST, write:
$_POST[ ‘first_name’ ]
If the form method is GET,
$_GET[ ‘first_name’ ]
Example:
<form method=‘POST’ action=“login.php”>
<input type=‘text’ name=‘username’><br>
<input type=‘password’ name=‘password’><br>
<input type=‘submit’ value=‘login’>
</form>
Web Programming 38
Cont’d
<?php
$username = $_POST[ ‘username’ ];
$password = $_POST[ ‘password’ ];
if($username == “user” && $password == “pass”){
//login successful
header( ‘Location: home.php’ );
exit();
}else{
//login failed
header( ‘Location: login.html’ );
exit();
}
} ?>
Web Programming 39
Cont’d
In effect, all form data will be available to PHP
scripts through the appropriate array: $_GET or
$_POST
Another way of getting input from client can be
using cookies
Cookie is information stored on the client by the
server
Cookies stored on a client associated to a particular
server are sent to the server every time that same
client computer requests for a page
Cookies are often used to identify a user
Web Programming 40
Cont’d
To create a cookies, use the setcookie() function
Cookies must be sent before any output from your
script.
▪ This function must be called before any other output in
the PHP file, i.e before <html>, any spaces, …
To retrieve a cookie value, use the $_COOKIE array
with the name of the cookie as index
<html><body>
<?php if( isset( $_COOKIE[ “uname” ] ) )
echo “Welcome “ . $_COOKIE[ “uname” ] . “! <br> “;
else
echo “Cookie not set <br>”;
?>
Web Programming 41
Operators
Arithmetic
▪ +, -, *, /, %, --, ++
Assignment (simple, compound)
▪ =, +=, -=, *=, /=, %=
Comparison
▪ ==, != , ===, !==, <, >, <=, >=
Logical
▪ &&, || , !
String
▪ . (dot)
Web Programming 42
Control Structures
Conditional constructs
▪ If … else
if ( condition1 ){
statements
}elseif ( coditon2 ){
statements
}elseif( condition3 ){
…
}else{
statements
}
Web Programming 43
Control structures (cont’d)
▪ Conditional statement
( condition ) ? True_value : False_value
Example:
…
<?php
$year = (int)date( “Y”);
echo ( $year % 4 == 0 ) ? “Leap Year” : “Not
Leap Year”;
?>
Intern
… 44
Control structures (cont’d)
▪ Switch
switch ( expression ){
case value 1:
statements
break;
…
case value n:
statements
break;
default:
45
Intern statements
Control structures (cont’d)
❖Looping constructs
▪ For loop
for( initialization; condition; increment ){
loop body
}
▪ Foreach loop
foreach( array as [key=>]value ){
loop body
46
Intern }
Control structures (cont’d)
▪ Example
…
$arr = array(“name”=>”Abebe”, “dept”=>”CS”,
“year”=>3, “cgpa”=>3.5);
foreach( $arr as $key=>$value ){
echo $key . “ = “ . $value . “<br>”;
}
//output
name = Abebe
dept = CS
Intern
year = 3
47
Control structures (cont’d)
▪ While loop
while( condition ){
loop body
}
▪ Do-while loop
do{
loop body
}while( condition );
48
Intern
Control structures (cont’d)
❖break
▪ ends execution of the current for, foreach,
while, do-while or switch structure.
▪ accepts an optional numeric argument which
tells it how many nested enclosing structures
are to be broken out of.
❖continue
▪ used within looping structures to skip the rest
of the current loop iteration
Intern
▪ execution continues at the condition
49
Control structures (cont’d)
❖return
▪ If called from within a function, the return
statement immediately ends execution of the
current function, and returns its argument as
the value of the function call
▪ If return is called from within the main script
file, then script execution ends.
50
Intern
Control structures (cont’d)
❖include / require
▪ Format: include “file”; or require “file”;
▪ includes and evaluates the specified file.
▪ include generates a warning while require
generates a fatal error. Otherwise, both
structures behave the same way.
❖include_once / require_once
▪ similar in behavior to include / require with the
only difference being that if the code from a
Intern
file has already been included / required, it
51
Control structures (cont’d)
❖Example
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
include 'vars.php';
?>
52
Intern
Functions
<?php
function function_name($arg_1, $arg_2,
..., $arg_n)
{
function body
[return $retval;]
53
}
Intern
Conditional functions
<?php
$defined= true;
// We can't call f1() from here since it doesn't exist yet, but
we can call f2()
f2();
if ($defined) {
function f1() {
echo "I don't exist until program execution reaches me.\n";
}
}
if ($defined) f1();
function f2() {
echo "I exist immediately upon program start.\n";
}
54
?>
Intern
Functions within functions
<?php
function f1(){
function f2(){
echo "I don't exist until f1() is called.\n";
}
}
f1();
f2();
?>
55
Intern
Functions (cont’d)
❖Recursive functions
Example
<?php
function recursion($a){
if ($a < 20) {
echo "$a \r\n";
recursion($a + 1);
}
}
?>
when calling:
Intern
58
Function arguments (cont’d)
❖PHP allows you to use arrays and
special type NULL as default values
❖The default value must be a constant
expression, not a variable, a class
member or a function call.
❖Note that when using default
arguments, any defaults should be on
the right side of any non-default
arguments; otherwise, things will not
work as expected.
59
Example
Intern
Returning values
❖Values are returned by using the
optional return statement.
❖Any type may be returned, including
lists and objects.
❖This causes the function to end its
execution immediately and pass
control back to the line from which it
was called.
❖To return a reference from a function,
you have to use the reference operator
60
<?php
function &returns_reference(){
return $someref;
}
61
Intern
Thank You For your
Patience!