0% found this document useful (0 votes)
3 views

Chapter One (Full)

Chapter One introduces server-side scripting, explaining how web communication occurs via HTTP and the differences between client-side and server-side scripting languages. It details the use of PHP as a server-side language, covering its syntax, variables, data types, control structures, and functions. Additionally, the chapter discusses handling form data and working with arrays, including various array functions and methods for managing multivalued form components.

Uploaded by

yilikalfikru71
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter One (Full)

Chapter One introduces server-side scripting, explaining how web communication occurs via HTTP and the differences between client-side and server-side scripting languages. It details the use of PHP as a server-side language, covering its syntax, variables, data types, control structures, and functions. Additionally, the chapter discusses handling form data and working with arrays, including various array functions and methods for managing multivalued form components.

Uploaded by

yilikalfikru71
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 69

Chapter One

Server Side Scripting


Introduction

How does the web work ?
 It uses the HTTP (Hyper Text Transfer Protocol) to
communicate between a client and a server
 The request ranges from simple get request to fetch a
static content to post and delete requests to add or
delete resources on the server
 Every request and response contains a header and
optional body
 Servers are always on and listen requests from clients
and handle them accordingly
Cont...

Communication Scenarios
 Static content
Cont...

- Dynamic Content
Server Side vs Client Side
Programming Languages

Client side scripts
• Are executed by the client, particularly by the
browser
• They are used for appearance and behavior of a
web page
• It has little or no access to the underlying operating
system
• Some features may not work or properly rendered
on specific browser(s)
Cont…
• What is server side scripting language ?
– a server-side scripting language is a script that is
executed on the server as apposed to client-side
scripting languages like JavaScript
– It requires server-side scripting engine
– It has full access to the server operating system
– there are variety of them like PHP, Python, Ruby,
C#, NodeJS, etc….
When to use server-side scripting
• When developing Dynamic web pages
• Authentication, authorization and session
tracking.
• Template-driven page generation. Including
repeated content like header/footers and
navigation menus around the “content area”
of a web page.
Cont.….
• Personalization and customization of content based
on authentication and authorization. This also
includes the serving of content based on the content
of the page (e.g. YouTube, Amazon, Facebook) or the
browsing behavior of the user.
• Handling POST form input
• Communication with other programs, libraries and
APIs – e.g. sending out e-mail
PHP
• It is server-side scripting language
• It is not visible to visitors
• It should be saved with .php extension
• It is denoted in a page with opening and
closing tags as follows
<?php
?>
• Every statement ends with a semicolon
Cont.…
• Example
<?php
// First line of code goes here;
// Second line of code goes here;
// Third line of code goes here;
?>
• Commenting
– Single line (//) or multiple line (/* -----*/)
Cont.….
• Creating the first program.
<html>
<head>
</head>
<body>
<?Php
echo “ hello there”;
?>
</body>
</html>
Cont.….
• PHP script can be emended into HTML page.
• Pitfalls:-
– Double quotes
• Use \” escaping character or single quote.
– Remember that you still have to follow PHP rules,
even though you’re coding in HTML.
• echo “<font size=\”2\”>”;
– Don’t try to cram too much HTML into your PHP
sections.
Variables and Constants
• It is case-sensitive.
• Variable declaration rules are applied.
– A variable starts with the $ sign, followed by the name of
the variable
– A variable name must start with a letter or the underscore
character
– A variable name cannot start with a number
– A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
– Variable names are case-sensitive ($age and $AGE are two
different variables)
Cont.…..
• A value in a variable is displayed using echo or print
statement.
• PHP also supports static variables. E.g. static $x = 0
• Variables have global and local scopes.
• define (“FAVMOVIE”, “The Life of Brian”);
e.g. echo “My favorite movie is “;
echo FAVMOVIE;
• Variables are denoted with a dollar sign ($).
• $num = 5;
• It is loosely typed language.
PHP data types
• PHP supports the following data types:
– String
– Integer - It is a number between -2,147,483,648 and
+2,147,483,647.
– Float (floating point numbers - also called double)
– Boolean
– Array
– Object
– NULL
• Reading Assignment : - string methods.
Cont.….
• Built in math functions.
– Rand([min],[max]);
– Ceil(number) Round numbers up to the nearest
integer;
– Floor(number) Round numbers down to the
nearest integer;
– Max(arg1, arg2);
– min(arg1,arg2);
Passing variables between pages
• $_GET
• $_POST
• $_REQUEST
• $_FILES
• $_SESSION
Control Structure
• Control structures determine the flow of code
within an application.
• Conditional statement
if (expression) {
statement
}
Cont.…..
if (expression) {
statement
}
else{
statement
}
Cont.….
switch($variable) {
case “expression 1":
statement(s)
break;
case “expression 2":
statement(s)
break;
default:
statement(s)
}
Looping
• While
while (expression) {
statements
}
• For
for(expression1;expression2;expressio
n3) {
statements
}
Break and Continue
• Encountering a break statement will
immediately end execution of a do...while, for,
foreach, switch, or while block.

• The continue statement causes execution of


the current loop iteration to end and
commence at the beginning of the next
iteration.
Function
• A block of code dedicated to achieve a single
task.
• Advantages
– Reusability.
– Easy to maintain.
Creating Function
function function_name (parameters) {
function-body
}

• To call a function use its name, and if it has


parameters pass the required arguments.
Passing Arguments
• Passing by value
– The original variable’s value will not be changed
even if the recipient variable value is changed.
• Passing by reference
– is done by appending an ampersand to the front
of the parameter(s).
– It changes the original variable's value.
Default and Optional arguments
• Default values can be assigned to input arguments,
which will be automatically assigned to the parameter if
no other value is provided.
– E.g. function salestax($price,$tax=.0575)
• You can designate certain arguments as optional by
placing them at the end of the list and assigning them a
default value of nothing.
– function salestax($price,$tax="")
Recursive Function
• Is a function which calls itself.
• It has condition to stop the iteration.
– E.g. a function that adds numbers b/n 1 and 10
Array
• Is a variable that can store more than one value.
• the array() function is used to create an array.
• indexed arrays
– There are two ways to create indexed arrays.
• $cars = array("Volvo", "BMW", "Toyota");
Or
 $cars[0] = "Volvo";
 $cars[1] = "BMW";
 $cars[2] = "Toyota"
• Associative Arrays
– Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Or
 $age['Peter'] = "35";
 $age['Ben'] = "37";
 $age['Joe'] = "43";
Creating Array
• There are two ways
– Informally
• you can create the array simply by making reference to
it.
• $state[0] = "Delaware";
– Formally
• Uses the array() function
• array array([item1 [,item2 ... [,itemN]]])
– $languages = array ("English", "Gaelic", "Spanish");
– $languages = array ("Spain" => "Spanish","Ireland" =>
"Gaelic", "United States" => "English");
Cont.……
• range()
– The range() function provides an easy way to quickly
create and fill an array consisting of a range of low and
high integer values.
• $die = range(0,6);
• Same as specifying $die = array(0,1,2,3,4,5,6)
– The optional step parameter offers a convenient means for
determining the increment between members of the
range.
• $even = range(0,20,2);
– also be used for character sequences
• $letters = range("A","F");
Outputting Array
• Using index or Key.
• print_r()
• Testing Array
– is_array() is used to check if a given variable is an
array or not.
– boolean is_array(mixed variable)
– Returns true if the variable is array and false if it is
not.
Adding and Removing array
elements
• PHP provides a number of functions for both growing
and shrinking an array.
• array_push()
– The array_push() function adds variable onto the end of the
target_array.
• $states = array("Ohio","New York");
• array_push($states,"California","Texas");
• array_pop()
– The array_pop() function returns the last element from
target_array.
• $states = array("Ohio","New
York","California","Texas");
• $state = array_pop($states); // $state = "Texas"
Cont.…..
• array_shift()
– The array_shift() function is similar to array_pop(), except
that it returns the first array item found on the
target_array rather than the last.
• $states = array("Ohio","New
York","California","Texas");
• $state = array_shift($states);
• array_unshift()
– The array_unshift() function is similar to array_push(), except
that it adds elements to the front of the array rather than to the
end.
• $states = array("Ohio","New York");
• array_unshift($states,"California","Texas");
Cont.….
• array_pad()
– The array_pad() function modifies the target
array, increasing its size to the length specified by
length.
• $states = array("Alaska","Hawaii");
• $states = array_pad($states,4,"New colony?");
Locating array elements
• Array_keys()
– returns an array consisting of all keys located in
the array target_array.
– E.g show the keys using print_r()
• array_key_exists()
– boolean array_key_exists(mixed key, array
target_array).
– returns TRUE if the supplied key is found in the
array target_array, and returns FALSE otherwise.
Cont.….
• array_values()
– The array_values() function returns all values located in the array
target_array, automatically providing numeric indexes for the
returned array.
• array_search()
– searches the array haystack for the value needle, returning
its key if located, and FALSE otherwise.
• mixed array_search(mixed needle, array haystack [, boolean
strict])
• Traversing array
– Using foreach loop
– foreach ($colors as $value)
– {
– echo "$value <br>";
• }
Determine Array size and
uniqueness
• count()
– integer count(input_array)
– returns the total number of values found in the
input_array.
– Sizeof() function can be also used.
• array_count_values()
– returns an array consisting of associative key/value pairs.
– Each key represents a value found in the input_array, and
its corresponding value denotes the frequency of that
key’s appearance (as a value) in the input_array.
• E.g. Array ( [Ohio] => 2 [Iowa] => 2 [Arizona] => 1 )
Sorting Array
• sort()
– sorts the target_array, ordering elements from
lowest to highest value.
• rsort()
– is identical to sort(), except that it sorts array
items in reverse (descending) order.
• asort()
– is identical to sort(), sorting the target_array in ascending
order, except that the key/value correspondence is
maintained.
Cont.…
• ksort()
– sorts the input array array by its keys, returning
TRUE on success and FALSE otherwise.
• krsort()
– operates identically to ksort(), sorting by key,
except that it sorts in reverse (descending) order.
Merging, Slicing, splicing and
Dissecting
• array_combine()
– array array_combine(array keys, array values)
– produces a new array consisting of keys residing in the input
parameter array keys, and corresponding values found in the
input parameter array values.
– both input arrays must be of equal size, and that neither can be
empty.
• E.g. $abbreviations = array("AL","AK","AZ","AR");
• $states = array("Alabama","Alaska","Arizona","Arkansas");
• $stateMap = array_combine($abbreviations,$states);
Cont.…….
• array_merge()
– appends arrays together, returning a single, unified
array.
– If an input array contains a string key that already
exists in the resulting array, that key/value pair will
overwrite the previously existing entry.
• array_slice()
– array array_slice(array input_array, int offset [, int length])
– returns the section of input_array, starting at the key
offset and ending at position offset + length.
Cont.……
• array_splice()
– array array_splice(array input, int offset [, int
length [, array replacement]])
– removes all elements of an array, starting at offset
and ending at position offset + length, and will
return those removed elements in the form of an
array.
Cont.….
• array_intersect()
– The array_intersect() function returns a key-
preserved array consisting only of those values
present in input_array1 that are also present in
each of the other input arrays.
– array array_intersect(array input_array1, array
input_array2 [, array...])
– Note that array_intersect() considers two items to
be equal only if they also share the same
datatype.
Cont….
• array_diff()
– array array_diff(array input_array1, array
input_array2 [, array...])
– returns those values located in input_array1 that
are not located in any of the other input arrays.
Handling Form Data
• There are two common methods for passing
data from a form to a script.
• POST and GET
– When to use post
• Sensitive information
• Large amount of data
• Can not bookmark
– When to use get
• Not sensitive data
• Not large amount of data ( about 2000 characters)
• Can bookmark
Cont.….
• The isset() is used to check if the submit button is
clicked or not.
• The script that handles the data submitted can be
placed within the same file as that of the form or in
different file and referred using the action attribute.
• The $_SERVER["PHP_SELF"] is a super global variable
that returns the file name of the currently executing
script.
• action="<?php echo $_SERVER['PHP_SELF']; ?>
Cont.…….
• Validation
– Required
– Name
– Email
– URL
• Include files
– Include
• include 'filename'
– Require
• require 'filename'
Working with multivalued form
components
• Multivalued form components such as checkboxes
and multiple-select boxes greatly enhance your Web-
based data-collection capabilities, because they
enable the user to simultaneously select multiple
values for a given form item.
• To make PHP recognize that several values may be
assigned to a single form variable (i.e., consider it an
array), you need to make a minor change to the form
item name, appending a pair of square brackets to it.
cont…..
Example
<?php
if (isset($_POST['submit']))
{
echo "You like the following languages:<br />";
foreach($_POST['languages'] AS $language) echo
"$language<br />";
}
?>
Cont.…..
• Reading and Writing files
– The readfile() function reads a file and writes it to
the output buffer.
– E.g. <?php
– echo readfile("webdictionary.txt");
– ?>
– A better method to open files is with the fopen()
function.
– The first parameter of fopen() contains the name
of the file to be opened and the second parameter
specifies in which mode the file should be
opened.
Cont.…..
Cont…..
• Reading single line
– The fgets() function is used to read a single line from a
file.
– <?php
– $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
– echo fgets($myfile);
– fclose($myfile);
• ?>
– fopen()
• The fopen() function is also used to create a file. a file is
created using the same function used to open files.
• If you use fopen() on a file that does not exist, it will create
it, given that the file is opened for writing (w) or appending
(a).
• E.g. $myfile = fopen("testfile.txt", "w")
Cont.……
• The fwrite() function is used to write to a file.
• The first parameter of fwrite() contains the name of the file to write to
and the second parameter is the string to be written.
• E.g. <?php
• $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
• $txt = "John Doe\n";
• fwrite($myfile, $txt);
• $txt = "Jane Doe\n";
• fwrite($myfile, $txt);
• fclose($myfile);
– ?>
Database connection
• How to connect to MySQL using PHP
– There are two options (adapters)
• Mysqli – works only with MySQL
• PDO (PHP Data Objects) – works with 12 different
database vendors, and some of them are
– MySQL
– PostgreSQL
– MS SQL Server
– Oracle
– SQLite
• Both are object oriented, but MySQL also provides a
non-object oriented option
Cont…..
• Connecting to MySQL through MySQLi
– MySQLi requires address, username and password of
the database server to connect
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = “test”;

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Cont…..
• Connecting to MySQL through PDO
– PDO requires provider and database (Data Source Name) in
addition to address, username and password of the database
server to connect
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Executing Query
• MySQLi
$sql = “create database db_name”;
$conn → query($sql);
– Query method returns true if the query executed
successfully, otherwise returns false
• PDO
– $conn → exec($sql);
Class
• It is a data type.
• Collection of objects.
• It is composed of fields and methods.
• E.g. class classname
{
// Field declarations defined here
// Method declarations defined here
}
Objects
• Is an instance of a class.
• The practice of creating objects based on
predefined classes is often referred to as class
instantiation.
• Objects are created using the new keyword.
• E.g.
– $employee = new Staff();
Invoking Fields
• Fields are referred to using the -> operator and, unlike
variables, are not prefaced with a dollar sign.
• Syntax:-
– $object->field
• When you refer to a field from within the class in
which it is defined, it is still prefaced with the ->
operator, although instead of correlating it to the
class name, you use the $this keyword.
Cont.…..
Field Scopes
– PHP supports five class field scopes: public, private,
protected, final, and static.
– Public
• Public fields can then be manipulated and accessed directly
by a corresponding object.
– Private
• Private fields are only accessible from within the class in
which they are defined.
– Protected
• Protected fields are also made available to inherited classes
for access and manipulation, a trait not shared by private
fields.
– final
Methods
• A method is quite similar to a function, except
that it is intended to define the behavior of a
particular class.
• E.g. public [function scope] function
functionName()
{
/* Function body goes here */
}
$object->method_name();
Constructors
• It is a block of code that automatically
executes at the time of object instantiation.
• PHP recognizes constructors by the name
__construct.
• Syntax:-
function __construct([argument1, argument2, ..., argumentN])
{
/* Class initialization code */
}
Static Class Members
• Static members of a class are shared by
multiple objects and they belong to a class.
• Syntax:-
– Public static variable_name;
– Static function function_name(){}
• Autoloading Objects
– require_once("classes/Books.class.php");
Session
• The Hypertext Transfer Protocol (HTTP) defines the rules
used to transfer text, graphics, video, and all other data
via the World Wide Web.
• It is a stateless protocol, meaning that each request is
processed without any knowledge of any prior or future
requests.
• means that by default, any two requests are handled
completely independently, regardless if they come from
the same address, request the same resource.
• The solution for the above problem are cookies and
sessions.
Cont.…..
• It is a means to solve the problem of
statelessness.
• This is accomplished by assigning each site
visitor a unique identifying attribute, known as
the session ID (SID), and then correlating that
SID with any number of other pieces of data,
be it number of monthly visits, favorite
background color, or middle name.
Starting a Session & VDestroying a
Session
• Use the session_start() function to create
session.
• Use session_destroy() function for destroying
a session.
Creating and Deleting Session
Variables
• Use $_SESSION super global array to create
session.
• To delete use unset(variable name);
– E.g.
<?php
session_start();
$_SESSION['username'] = "jason";
echo "Your username is ".$_SESSION['username'].".";
?>
Cont.….
<?php
session_start();
$_SESSION['username'] = "jason";
echo "Your username is: ".$_SESSION['username'].".<br />";
unset($_SESSION['username']);
echo "Username now set to: ".$_SESSION['username'].".";
?>

You might also like