PHP CH-01
PHP CH-01
PHP CH-01
CHAPTER – 01
INTERNET PROGRAMMING WITH PHP
Learning Outcomes
On successful completion of the course, the students should be able to:
Apply the Internet Programming design concepts in solving real world problems.
Web page – consists of objects (HTML file, image, Media) and addressed by URL
Web development:
►is the process of building websites and applications for the internet, or for a private network known as an
intranet.
►It is not concerned with the design of a website; rather, it’s all about the coding and programming that
powers the website’s functionality.
►Web development can be broken down into three layers:
1. Client-side coding (frontend)
2. Server-side coding (backend)
3. Database technology
Cont…
1. Client-side coding (frontend)
refers to everything that the end user experiences directly.
executes in a web browser and directly relates to what people see when they visit a website.
Things like layout, fonts, colors, menus and contact forms are all driven by the frontend.
Languages: HTML, CSS, JavaScript
2. Server-side coding (backend)
is all about what goes on behind the scenes.
Is part of a website that the user doesn’t actually see.
It is responsible for storing and organizing data, and ensuring that everything on the client-side
runs smoothly.
It does this by communicating with the frontend.
Languages: PHP, Java, Python, Perl, ASP.NET, Ruby
3. Database technology
Creating and maintaining a database
MySQL, SQL Server, Postgres, Oracle
Scripting Languages(SL) - General
►Scripting languages are generally interpreted - compiles a code line by line.
►It is translated into machine code when the code is run, rather than beforehand.
►PHP, JavaScript, Python, and Ruby are all examples of scripting languages.
►“Easy to learn” and have support for high-level structures and libraries.
►Automatic memory management controls the allocation and freeing (garbage
collection) of memory on demand.
►Many scripting languages are starting to adopt object-oriented structures.
►Most modern scripting languages have built-in support for high level data structures.
►All scripting languages are programming languages, not all programming languages
are scripting languages.
►Two categories of Scripting Languages: Client-side Scripting and Server-side
Scripting
Client-side Scripting
►refers to the class of computer programs on the web that are executed on client-side,
by the user's web browser.
►It reduces demand on the server, allowing web pages to load faster.
►is more focused on user interface and functionality.
►are often embedded within an HTML or XHTML document (hence known as an
"embedded script"), but they may also be contained in a separate file.
►may also contain instructions for the browser to follow in response to certain user
actions, (e.g., clicking a button). Often, these instructions can be followed without
further communication with the server.
►E.g. HTML, CSS, JavaScript
Client Side Scripting
►Client Side Scripting performing tasks like:
Make interactive user interface
Validates user input
Enhances Web pages with ActiveX® controls, applets, etc.
Manipulates browser documents
Reduces number of requests that need to be passed to server
Browser dependency
Shortcomings of Client Side Scripting
►Browser support is inconsistent - for example VBScript is poorly supported by non-Microsoft
browsers
►The script must be passed from server to client across the network
►Security - the script is visible to client end-users
►Accessibility - content produced client-side is often "hidden" from associative technologies
such as screen readers
Server-side scripting languages
►It is any scripting or programming that can runs on a web server. When a client sends a
request, the server processes the request and responds by sending content via HTTP.
►Benefit - are not viewable by the public like client-side scripts are.
►Scripting focuses on faster processing, access to data, and resolving errors.
►originally developed to interface with databases or other data stores on the server.
►constructs a communication link between a server and a client (user).
►The web server abstracts the scripts from the end user until serving the content, which
makes the data and source code more secure.
►Performs operations like:
customization of a website,
dynamic change in the website content,
response generation to the user’s queries,
accessing the database
►E.g. PHP, ASP.NET, Python, Perl, JSP(Java Server Page),
Server-Side Scripting
Database , file system access & network access (from the server only)
Known platform for execution (as opposed to client-side, where the platform is
uncontrolled.) Independent of HW & SW
Security improvements
Sever-side scripting
►When evaluating which server-side technology to use, you need to consider a
number of critical factors
Ease of development
• How easily can you build new applications
Performance (responsiveness)
• How fast can the technology respond to queries
Scalability
• Can the technology scale to thousands, even millions of users?
Security
• Are there any inherent security vulnerabilities?
►The most widely used web servers are:
• Apache, nginx, Microsoft-IIS, Lighthttpd, Caddy, MonkeyServer, OpenLiteSpeed,
Cherokee, Jigsaw Server
Common Features
►All server-side frameworks share a common set of features
Read, Check and Validate data submitted by the user
Generate HTML dynamically based on user input
Determine information about the client browser
Access database systems, file systems, & other resources
Exploit the HTTP protocol
User does not need to download plugins like Java or Flash
Generally quicker to load than client-side scripting
User is able to include external files to save coding
Scripts are hidden from view so it’s more secure.
Server- side options -Dynamic Websites
►Dynamic websites shows different information at different point of time. It is possible to
change a certain portion of a web page without loading the entire web page. It has been made
possible using Ajax technology.
►Server-side dynamic web page is created by using server-side scripting such as PHP.
►Dynamic websites are websites that do more than just fetch and return files. Here are some
examples of what a dynamic site might do when it receives a request:
Perform a database search and return a list of search results.
Log a user into a website by checking the database for the user's credentials.
Redirect the user to a login page if the user requests a members-only page.
Record a user's support request in a database, email the user a friendly message & the auto-generated support ticket number.
Gets Page
WEB SERVER
<HTML>
<?php PHP code ?>
HTTP Request </HTML>
(url)
Server response Interprets the PHP code
<HTML>
<B>Hello</B>
CLIENT </HTML>
Hello
Browser creates
the web page
18
Introduction to PHP(Hypertext
Preprocessor)
• PHP stands for PHP: Hypertext Preprocessor
• It is a powerful server-side scripting language for creating dynamic & interactive website
• It is perfectly suited for Web development and can be embedded directly into the HTML code.
• PHP is often used together with Apache (web server) on various operating systems. It also supports IS-
• PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC,
etc.)
• PHP scripts are executed on the server, the computer where the Web site is located.
PHP Features
Supports (almost) all major databases and web servers (apache, IIS)
►Install WAMPP: stands for “Windows Apache MySQL Php” can also be installed which
will work only on windows platform.
PHP – Language Basics(Syntax)
►PHP code can be embedded in HTML and all PHP code must be included inside one
of the following possible tags that are recognized by the PHP Parser.
Canonical PHP tags
<?php PHP code goes here ?>
Short-open (SGML-style) tags
<? PHP code goes here ?>
HTML script tags
<script language="php"> PHP code goes here </script>
ASP-style tags
<% PHP code goes here %>
►Hence, the PHP parser only parses code which is in between <?php and ?>
►Php files can be saved with .php extension in the server recognized directory i.e.
htdocs for Xampp and www for Wamp.
PHP – Language Basics
►PHP is whitespace insensitive
it almost never matters how many whitespace characters you have in a row. one whitespace
character is the same as many such characters.
► PHP variables are case sensitive. E.g. $phpvar and $PHPVAR are different variables
►All user defined functions, classes and keywords (eg: if, else, echo, etc) are not case
sensitive.
► Statements are expressions terminated by semicolons(;)
► Expressions are combinations of tokens
►Tokens of PHP (variables, data types, functions, methods, objects, classes,
resources, packages(APIs) etc )
►Comments in PHP:
Single Line Comment: enclosed in // or #. E.g. // This is a single line comment
Multiple Line Comment: start with /* and end with */. E.g. /* This is a multiple line comment
*/
PHP – Language Basics -Examples
Variables & Data Types
<?php
Expressions & Operators
// PHP statements
?> Functions, Objects, Methods & Classes
Resources & Packages
►Web pages that contain PHP should be saved with .php extension.
Example :
<?php echo “This line brought to you by PHP”;?>
►When the Web server gets the file and sees the .php extension, it checks for PHP tags.
When it finds the PHP tag, it executes the PHP echo statement instead of sending it to
the browser.
►Echo & print: echo () or print () is a method used for displaying the html tags or
response with data back to the client.
►Echo() can accept many arguments but print() accepts only one argument.
►Echo() is faster than print()
PHP – Language Basics –Examples …
Example :
<html> <head><title>Hello World Script</title></head>
<body>
<?php
echo “<p>Hello World!</p>”
?>
</body> </html>
►When the PHP section is processed, it is replaced with the output. In this case, the
output is as follows:
<p>Hello World!</p>
►In your browser window, you see the output at the location in the page where you
added the PHP section. Even if you view the source in your browser, you only see the
output, not the PHP code.
Variables in PHP
►A variable is used to storing a values, like text strings, numbers or arrays. When a
variable is declared, it can be used over and over again in your script.
►Rules for naming a variable is same as in C++
►All variables start with “$” followed by name of the variables.
E.g. $var_name; or $var_name = value;
►PHP does a good job of automatically converting types from one to another when
necessary.
►The variable data type depends on the current value it holds
PHP Variable Types
►PHP Variable Types can be classified as: scalar , compound and special types.
►Integers − are whole numbers, without a decimal point, like 4195.
►Doubles − are floating-point numbers, like 3.14159 or 49.1.
►Booleans − have only two possible values either true or false.
Strings − are sequences of characters, like PHP supports string operations.
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
NULL − is a special type that only has one value: NULL.
Resources − are special variables that hold references to resources external to PHP (such
as database connections).
Var_dump() and gettype() are the methods for finding the data type of the
variable. E.g. $x=NULL; var_dump($x); //NULL
Variable Scope
►Scope can be defined as the range of availability a variable has to the program in which
it is declared. PHP variables can be one of four scope types:
Local Variables - are variables declared in a function. Any assignment outside of
that function will be considered to be an entirely different variable from the one
contained in the function.
Function Parameters - Function parameters are declared after the function name
and inside parentheses.
Global Variables - can be accessed in any part of the program. This is done, by
placing the GLOBAL keyword in front of the variable. E.g. GLOBAL $num;
Static Variables - not lose its value when the function exits and will still hold that
value should the function be called again.
• This done by placing the STATIC keyword in front of the variable name.
• E.g. STATIC $num;
PHP Global Variables - Superglobals
►Several predefined variables in PHP are "superglobals", which are always accessible
regardless of scope - and from any function, class or file without having to do anything.
►There is no need to do global $variable; to access them within functions or methods.
►The PHP superglobal variables are:
►$GLOBALS - used to access global variables from anywhere in the PHP script.
►$_SERVER – Contains server and execution environment information.
►$_REQUEST - used to collect data after submitting an HTML form.
►$_POST - used to collect form data after submitting an HTML form with method="post".
►$_GET - used to collect form data after submitting an HTML form with method="get".
►$_FILES - HTTP File Upload variables
►$_COOKIE - stores variables passed to current script along with HTTP request
Constant Variables
►PHP is a loosely typed language – no need of declaration before use.
No variable declaration ( implicit ), to create a variable, just assign some value to
it!
Example: $myNum = 5; //declares and assignes 5 to the variable $myNum
►Constant variables:- defined by using define() method.
►It takes 3 arguments(name of the constant, value of the constant, case insensitive)
►The third argument is by default set to false. If it is true then the constant can be case
insensitive.
►The length of a string is often used in loops or other functions, when it is important
to know when the string ends.
►The strpos() function is used to search for a string or character within a string.
►If a match is found in the string, this function will return the position of the first
match. If no match is found, it will return FALSE.
E.g. echo strpos("Hello world!","world"); // displays 6
Operators in PHP
►Arithmetic operators: +, - , *, / , %;
►Comparison operators: ==(equals), !=(not equals), >, <, >=, <=, ===(identical, true if
the variables used for comparison are both equal in value and also equal in datatype). !
==(not identical).
►if...else statement − use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true
►elseif statement − is used with the if...else statement to execute a set of code if one of
the several condition is true
►switch statement − is used if you want to select one of many blocks of code to be
executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..else if..else code.
Control Structure in Php- Decision Making
►The switch statement is used to perform different actions based on different conditions.
►Use the switch statement to select one of many blocks of code to be executed.
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
Control Structure in Php- Looping
►Loops in PHP are used to execute the same block of code a specified number of times.
for (int counter; test counter; increment counter) { code to be executed for each iteration; }
2. while − loops through a block of code if and as long as a specified condition is true.
3. do...while − loops through a block of code once, and then repeats the loop as long as a special
condition is true.
1. Write a PHP program that displays your age from a variable with echo statement.
2. Write a function to check a number is prime or not using if-else conditional structure.
3. Write a PHP program to compute the sum of the prime numbers less than 100 using
do-while loop.
Arrays in PHP
►An array is a data structure that stores one or more similar type of values in a single value.
►The array() function is usually used when you want to create a new array and populate it with more
than one element, all at the same time.
1. Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
array(value1,value 2, …value n);
2. Associative array − An array with strings as index. This stores element values in association with
key values . array(“key1”=>’value1” , “key2”=>”value2”…”keyn”=>”valuen”);
3. Multidimensional array − An array containing one or more arrays and values are accessed using
multiple indices. array( array( ) );
1. Numeric Indexed Array
►are the arrays whose subscript or index is numeric.
►can store numbers, strings and any object but their index will be represented by numbers.
►By default array index starts from zero.
►we use array() function to create array.
►Example: Creating and accessing items of numeric arrays.
<?php
$cars=array(“BMW”,”VOLVO”,”TOYOTA”);
foreach( $cars as $car ) {
echo $car “<br />"; // display all cars in the array
}
echo $car[1] “<br />"; // display car at index 1
?>
2. Associative Array
►are very similar to numeric arrays in term of functionality but they are different in terms of
their index.
►Associative array will have their index as string so that you can establish a strong
association between key and values.
►NB − Don't keep associative array inside double quote while printing otherwise it would not
return any value.
►Example: Creating and accessing items of associative arrays.
<?php
$books=array(“title”=>”PHP Script”, ”author”=>”Abebe”, ”publisher”=>”Mega”);
echo “Book Title: ” . $books[“title”] . “<br />";
echo “Book Author: ” . $books[“author”] . “<br />";
echo “Book Publisher: ” . $books[“publisher”] . “<br />";
}
3. Multidimensional Arrays
►A multi-dimensional array each element in the main array can also be an array.
►And each element in the sub-array can be an array, and so on.
►Values in the multi-dimensional array are accessed using multiple index.
►Example: create a 2D array to store marks of two students in three subjects
<?php
$marks = array( “Girma" => array ("physics" => 35, "maths" => 30, "chemistry" => 39),
“Kalkidan" => array ("physics" => 30, "maths" => 32, "chemistry" => 29));
echo “ Girma’s Physics Mark is: ” . $marks[‘Girma']['physics'] . "<br />";
echo “ Girma’s Maths Mark is: ” . $marks[‘Girma'][‘maths'] . "<br />";
echo “ Kalkidan’s Physics Mark is: ” . $marks[‘Kalkidan']['physics'] . "<br />";
echo “ Kalkidan’s Chemistry Mark is: ” . $marks[‘Kalkidan'][‘chemistry'] . "<br />";
}
Viewing Array Structure and Values
►You can see the structure and values of any array by using one of two statements —
var_dump() or print_r().
►The print_r() statement, however, gives somewhat less information.
►<?php
$cities = array("London", "Paris", "New York");
print_r($cities); // Display: Array ( [0] => London [1] => Paris [2] => New York )
var_dump($cities);
//array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }
} $Book = array( “title” = > “php”, “author”
= > “John”, “pubYear” = > 1939 );
►Looping through array using foreach:
This displays: foreach ( $Book as $k = > $v ) {
foreach ($cities as $val ) { London echo “ key: $k < br > ”;
echo $val . “ < br/ > ”; Paris echo “ value: $v < br > ”;
New York }
Sorting Arrays in PHP
►PHP comes with a number of built-in functions designed specifically for sorting array
elements in different ways like alphabetically or numerically in ascending or descending
order.
►Here are some of the most commonly used functions for sorting arrays:
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key
Sorting Arrays in PHP
<?php // Sorting Indexed Array
$colors = array("Red", "Green", "Blue", "Yellow");
sort($colors);
print_r($colors); //Array ( [0] => Blue [1] => Green [2] => Red [3] => Yellow )
rsort($colors);
print_r($colors); //Array ( [0] => Yellow [1] => Red [2] => Green [3] => Blue )
?>
<?php // Sorting Associative Array by value
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
asort($age);
print_r($age);?> //Array ( [Harry] => 14 [Peter] => 20 [Clark] => 35 [John] => 45 )
arsort($age);
print_r($age); //Array ( [John] => 45 [Clark] => 35 [Peter] => 20 [Harry] => 14 )
Sorting Arrays in PHP
<?php // Sorting Associative Array by key
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
ksort($age);
print_r($age); //Array ( [Clark] => 35 [Harry] => 14 [John] => 45 [Peter] => 20 )
krsort($age);
print_r($age); //Array ( [Peter] => 20 [John] => 45 [Harry] => 14 [Clark] => 35 )
?>
►count() and sizeof() –to count number of elements in the array
e.g. echo count($age); // display: 4
echo sizeof($age); // display: 4
Adding and Removing Array Elements
You can add elements to an array using square bracket syntax. For example:
$myArray[] = “new value”; - for indexed array
$myArray[“newKey”] = “new value”; - for associative array
<?php
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
$age[“Joe"]=40; // adds [“Joe”]=>40 new element to $age array
?>
array_unshift(array, value) – Adds one or more new elements to the start of an array
array_shift(array) – Removes the first element from the start of an array
array_push(array, value) — Adds one or more new elements to the end of an array
array_pop(array) — Removes the last element from the end of an array
array_splice(array, from, numofelements-to-remove, new-values) — Removes element(s) from
and/or adds element(s) to any point in an array.
Adding and Removing Array Elements - Examples
<?php
$num = array(12,98,56,40,100);
array_unshift($num, 78);
print_r($num); // Array ( [0] => 78 [1] => 12 [2] => 98 [3] => 56 [4] => 40 [5] => 100 )
array_shift($num);
print_r($num); // Array ( [0] => 12 [1] => 98 [2] => 56 [3] => 40 [4] => 100 )
array_push($num, 25);
print_r($num); //Array ( [0] => 12 [1] => 98 [2] => 56 [3] => 40 [4] => 100 [5] => 25 )
array_pop($num);
print_r($num); //Array ( [0] => 12 [1] => 98 [2] => 56 [3] => 40 [4] => 100 )
?>
Adding and Removing Array Elements - Examples
<?php
$num = array(12,98,56,40,100);
array_splice($num, 1, 0, 245); // adds 245 at index 1 without removing element(0)
print_r($num); //Array ( [0] => 12 [1] => 245 [2] => 98 [3] => 56 [4] => 40 [5] => 100 )
array_splice($num, 3); // removes elements starting from index 3
print_r($num); // Array ( [0] => 12 [1] => 245 [2] => 98 )
array_splice($num, 1, 1, 333); // removes element at index 1 and replace it by 333
print_r($num); //Array ( [0] => 12 [1] => 333 [2] => 98 )
array_splice($num, 1, 2, 333); // removes two elements starting at index 1 and replace by 333
print_r($num); // Array ( [0] => 12 [1] => 333 )
?>
PHP Functions
►A function is a self-contained block of code that performs a specific task.
►It is a way to create reusable code packages that perform specific tasks and can be kept and
maintained separately form main program.
►advantages of using functions:
Code Reusability: Functions reduces the repetition of code within a program
Simplicity: Functions makes the code much easier to maintain
Functions makes it easier to eliminate the errors
Reusability: Functions can be reused in other application
<?php
function increment($i){
$i++;
echo "Local ".$i; Output:
echo “<br>”;
} Local 11
$i = 10; By value 10
increment($i);
echo "By value ".$i;
?>
Passing Arguments by Reference (call by reference).
►The actual value is modified if it is modified inside the function.
►In such case, you need to use & (ampersand) symbol with formal arguments.
►The & represents reference of the variable.
<?php
function increment(&$i){
$i++;
echo "Local ".$i; Output:
echo “<br>”;
} Local 11
$i = 10; By value 11
increment($i);
echo "By value ".$i;
?>
PHP Default Argument Value
►If we call the function without arguments it takes the default value as argument.
►Means, if you don't pass any value to the function, it will use default argument value.
►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.
Returning Values from a Function
►uses the return statement to make the function in PHP return a value after successful
execution.
►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
►Example:
<?php
function getSum($num1, $num2){
$total = $num1 + $num2; Output:
return $total;
} 15
echo getSum(5, 10); // Outputs: 15
?>