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

Lecture 7& 8

This is Lecture note-3

Uploaded by

Kirubel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Lecture 7& 8

This is Lecture note-3

Uploaded by

Kirubel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Lecture 7

Server side scripting language


Request / Response Cycle..
Server Side Programming
• JSP/ASP/PHP vs CGI/Servlets
– CGI & Servlets -- Mostly Code with some HTML via
print & out.println
– JSP/ASP/PHP -- Mostly HTML, with code snippets
thrown in
• No explicit recompile
• Great for small problems
• Easier to program
• Not for large computations
PHP
Hypertext Pre-Processor
What is PHP?
• Server-side scripting language designed specifically
for the Web
• Executed on the server-side
• 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
• Embedded within an HTML page
PHP overview
Some of PHP’s Strengths
• High performance
– Using a single inexpensive server, you can serve
millions of hits per day
• Interfaces to many different database systems
– In addition to MySQL,you can directly connect to
PostgreSQL, mSQL, Oracle, dbm, FilePro
• Built-in libraries for many common web tasks
– You can generate GIF image, send email, work
with cookies,and generate PDF documents
Cont.…
• Low cost
– PHP is free.
• Ease of learning and use
– If you already know C or a C-like language such as C++ or
Java, you will be productive using PHP almost immediately
• Strong object-oriented support
• Portability
– Its platform independent
• Availability of source code
– You are free to modify or add something to the language
What you need to get started with PHP

• Before you can write and test your PHP


scripts, there's one thing you'll need - a
server! (wamp server,IIS,etc)
• You can use software called Wampserver. This
allows you to test your PHP scripts on your
own computer
• It installs everything you need for windows
operating systems.
Basic PHP Syntax
• A PHP script always starts with <?php and
ends with ?>.
• A PHP script can be placed anywhere in the
document.
• PHP files can contain text, HTML tags and
scripts
• PHP files are returned to the browser as plain
HTML
• PHP files have a file extension of “.php” or
“.php3”
Basic PHP Syntax cont.
Embedding in HTML
• XML style – can’t be disabled
<?php
Php statements;
?>
• Short style – enable short_open_tag
<?
Php statements;
?>
• Script style
<script language=“php”>
Php statements;
</script>
• ASP style – enable asp_tags
<%
Php statements;
%>
Overview of PHP
Whitespace
– Browsers ignore white space in HTML;
• so does the PHP engine
echo “Hello world”;
echo “Hello World”;
Comments
– Can be used to explain the purpose of the script
– The PHP parser skips over the comments, making them
equivalent to whitespace
// This is a comment on a single line
/* This is a block
of comments
on multiple lines
*/
Overview of PHP
Variables
– Variables are used for storing a values, like text
strings, numbers or arrays.
– When a variable is set it can be used over and over
again in your script
– All variables in PHP start with a $ sign symbol.
– The correct way of setting a variable in PHP:
$var_name = value;
Overview of PHP
Variables
– variable does not need to be declared before being set.
– PHP automatically converts the variable to the correct data
type, depending on how they are set.
– In a strongly typed programming language, you have to
define the type
– A variable name must start with a letter or an underscore
"_"
– A variable name can only contain alpha-numeric
characters and underscores (a-Z, 0-9, and _ )
Overview of PHP
Accessing form variables:
– Content Can be accessed in three ways:
• Short - $objectName
– register_globals – should be turned on
• Medium - $_POST[‘objectName’]
– Recommended
– Depends on the method used – GET or POST
• Long style - $HTTP_POST_VARS[‘objectName’]
– register_long_arrays – can be disabled to improve
performance
– Depends on the method - $HTTP_GET_VARS[‘objectN’]
– Old style – Deprecated
Overview of PHP
Strings
– String variables are used for values that contains character
strings
<?php
$txt="Hello World";
echo $txt;
?>
– To concatenate use dot (.)
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;
?>
Overview of PHP
Data types:
– Integer—Used for whole numbers
– Float (double)—Used for real numbers
– String—Used for strings of characters
– Boolean—Used for true or false values
– Array—Used to store multiple data items
– Object—Used for storing instances of classes
Type casting:
– $variable = (dataType)$anotherVariable
e.g. $total = 0;
$totalAmount = (float)$total
Overview of PHP
Constant
– To declare a constant
define(“consName”, value);
– No $ sign while using it
define(‘PI’,3.14); echo “PI=“.PI;
Scope of variables(three types )
– Built-in – super global, visible everywhere
$_GET ,$_POST, $_SESSION, ,$_FILES , $_SERVER
– Constants – once declared can be used inside and outside functions
– Globals – declared outside functions and can be used anywhere
within that script
- to use them inside a function declare a variable
with the same name as the global variable.
global $varName;
-Local variables used only with In the function
Cont.…
<?php
$s = 25; $t = 50;
function subtraction() {
$GLOBALS['v'] = $GLOBALS['t'] - $GLOBAL
S['s']; }
subtraction();
echo $v;
?>
Overview of PHP
Arithmetic Operating:
– +, *, /, -, %
– $a+$b, $a*$b, $a/$b, $a-$b
Assignment operator
– Assigns the value of the expression on the right side to the left side
$myVar = $anotherVar or expression
$myName = “My name is “.$name;
$b = 6 + ($a = 5);
– Combined assignments - +=,-=,*=,/=,%=
$a+=$b  $a= $a + $b
Post and pre-increment/decrement
$a=2; echo ++$a; prints 3
$b=2; echo $b++; prints 2 and changes the of $b to 3
Overview of PHP
Comparison operators:
– Compare to values and return True/False
– ==, >=,<=,<>,!=, <,>
– Usually used in conditional statements
Logical operator:
– Combines to Boolean values
– !,&, ||, &&, and, or
– & and or bitwise
!$a && $b  returns True/False based on values of $a and $b
Array operators:
– Applied on two arrays - +, ==, ===,!=,!==,<>
– $a === $b Identity TRUE if $a and $b have the same key/value pairs in
the same order and of the same types.
– $a !== $b Non-identity TRUE if $a is not identical to $b.
Eg if("22" == 22) echo "YES";
else echo "NO";
Overview of PHP
Variable functions:
– Mostly used functions
string gettype(mixed var);
int settype(mix var, string type);
$a=20;
echo gettype($a) – prints integer
settype($a,’String’ –prints string
var_dump ()— Dumps information about a variable
Isset(), unset()

– EXERCISE - Read for the other functions


Overview of PHP
Conditional statements:
– if statement
if (condition) {
statement;
}
– if – else
if (condition){
Statement;
} else{
anotherStatement;
}
– if, elseif, else
if(condition)
statement;
elseif(another condition)
statement;
elseif(another condition)
statement;
….
else
statement;
Overview of PHP
Switch statements:
switch (expression){
case value1: statement; break;
case value2: statement; break;
…..
default : statement; break;
Loops:
• for(var=initial;condition;incr/decr){
statements;
}
• while(condition){
statements;
}
• do{
statements;
}while(condition);
Arrays
Definition
– an array is a named place to store a set of values
– The values stored in an array are called the array
elements
– Each array element has an associated index
– Index can be an integer or a string
$varName = array(elements);
$names = array(‘Abebe’, ‘Belay’, ‘Fasil’);
Or $names[0]=“Abebe”;
$names[1]=“Belay”;
$names[2]=“Fasil”;
Cont.…
• Imagine you have a matchbox on which you
have written the word team.
$team= “CS";

CS

CS
Arrays
Definition
– To create a sequence of values within a
range
$arrName=range(lower, higher)
$arrName=range(lower, higher, difference)
$days = range(1,7);
$evens = range(2,20,2);
$letters = range(‘a’, ‘z’);
Arrays
Access Array elements
– To access array elements, use index or key
for($i=0;$i<4;$i++)
echo $names[$i];
– We can initialize arrays with keys and associated values
$names = array(‘A’=>’Abebe’,’B’=>’Belay’,
‘F’=>’Fasil’);
– We can create the same array as
$names[‘A’]=“Abebe”;
$names[‘B’]=“Belay”;
$names[‘F’]=“Fasil”;
– To access elements:
echo $names[‘A’];
– Accessing elements using loop:
foreach($names as $myIndex=>$myValue)
echo $myIndex.”=>”.$myValue;
– You can’t use for loop in this case
Arrays
Access Array elements
– each() function returns the next element of an array as an array
with indexes key and value or indexes 0 and 1.
While( $nextElement=each($names)){
echo $nextElement[‘key’].”-”.$nextElement[‘value’];
}
While( $nextElement=each($names)){
echo $nextElement[0].”-”.$nextElement[1];
}
Arrays
Access Array elements
– list() can be used to split an array into a number
of values.
while ( list( $index, $name ) = each( $names ) )
echo $index.” - ”. $name.”<br>”;
– Use reset() to loop through the $names array
again
reset($names);
//loop again here using each() method
Arrays
Multidimensional array
$team=array(array("Abebe","Belay",20),
array("Aster","Fasil",25),
array("Belay","Desta",30));
– To access elements
for ($i=0;$i<3;$i++){
for($j=;$j<3;$j++){
echo $team[$i][$j];
}
echo ”<br>”;
}
Cont.
Arrays
Multidimensional array
– We can also create multidimensional array using keys and values
$team=array( “”array(“fname”=>”Abebe”,
“lname”=>”Belay”, “age”=>20),
array(“fname”=>”Aster”,
“lname”=>”Fasil”, “age”=>25),
array(“fname”=>”Belay”,
“lname”=>”Desta”, “age”=>30));
– To access elements
for($i=0;$i<3;$i++){
while(list($title,$value)=each($team[$i])){
echo $value;
}
}
Arrays
Sorting Arrays
– The function sort() takes one dimensional array and sorts
the elements in ascending order
$names = (“Tesfaye”, “Abebe”, “Kebede”);
Sort($names);
– After this $names contains (“Abebe”, “kebede”,
“Tesfaye”)
– For arrays with key and value combination use
– asort() – to sort based on the values
– ksort() – to sort based on the keys
– To sort in descending order use the functions:
rsort(), krsort(), arsort()
– To sort multidimensional arrays, define a function
Arrays
Reordering arrays
– Shuffle() puts elements in a random order
– array_reverse() returns an array with elements in a reverse order
Navigating within an array
– While using each() function, a pointer points to the next element
– We can redirect this pointer
reset() – takes the pointer to the first element and returns the first element
current() – returns the element at the current pointer position
next() – advances the pointer and returns the current element
prev() – advances the pointer to previous position and returns the element
at that position
end() – takes the pointer to the last position, returns the elem.
Counting elements
– count(array) and sizeof(array) return the number of elements in array
String Manipulation And Regular
Expression
Formatting Strings
Trimming Strings:
trim() - strips whitespace from the start and end of a string
trim(str, ‘listChars’) – strips listChars from end/end str
• Only the end will be cut if both start and end matches listchars
rtrim() – strips whitespace from end of a string
ltrim() – strips whitespace from start of a string
Formatting Strings for printing:
nl2br() – converts newlines (\n) to <br> html tag
print() – same as echo, but it can format a string
$total = 12.4;
printf(“Total = %.2f”, $total); //prints 12.40
Formatting Strings
Change cases:
strtoupper(str) – returns upper case of str
strtolower(str) – returns lower case of str
ucfirst(str) – returns str with first letter in
upper case
ucwords() – returns str with first letter in each word in
upper case
Formatting Strings for Storage – store in DB:
addslashes() – adds escape character (\)
stripslashes() – removes escape character
• magic_quotes_gpc - is configured to add/remove slashes
automatically
Formatting Strings
Joining and Splitting Strings:
explode(separator, str) – returns an array of strings by breaking
str using separator
• $address=explode(‘@’, [email protected])
returns an array containing “info” and “bdu.edu.et”
implode() – does the opposite of explode(), joins elements of an
array using a string glue
• Implode(“@”, $address) returns [email protected]
join() – same as implode()
stroke() – returns a single fragment of the string using the
separator.
• Can take multiple separators
$token = stroke($str, “ .,;”);
while($token!=“ “){
echo$token;
$token = stroke($str, “ .,;”);
}
Formatting Strings
Joining and Splitting Strings:
string substr(string str, int start , int length ) – returns a
substring starting from start index to the last or the
given length.
Comparing Strings:
int strcmp(string str1, string str2) – returns: 0 if they are
equal, 1 if str1 is greater than str2, less than 0 if str1
less than str2
• It is case sensitive
strcasecmp() – identical to strcmp() but it is not case
sensitive
Formatting Strings
Testing String Length:
int strlen(string str) – takes a string and returns the
number of characters
Finding Strings in Strings:
string strstr(string haystack, string needle) - If an exact
match of the needle is found, the function returns
the haystack from the needle onward; otherwise, it
returns false
• If the needle occurs more than once, the returned string will start
from the first occurrence of needle.
stristr() - identical but is not case sensitive
strrchr() – which is again nearly identical, but returns
the haystack from the last occurrence of the needle
onward.
Formatting Strings
Finding the Position of a Substring:
int strpos(string haystack, string needle, int
[offset] ) – returns the position of the first
occurrence of the needle within haystack
• Starts searching at offset
$test = ‘Hello world’;
strpos($test, ‘o’); - returns 4
strpos($test, ‘o’, 5); - returns 7

strrpos() – identical but returns the last


occurrence
• In both case, if the string is not available they return false
Formatting Strings
Replacing Substrings:
mixed str_replace(mixed needle, mixed new_needle,
mixed haystack [,int count])) - replaces all the instances
of needle in haystack with new_needle and returns the new
version of the haystack
• The optional fourth parameter, count, contains the number of
replacements made
string substr_replace(string string, string
replacement,int start, int [length] ) - replaces part of the
string string with the string replacement. Which part is
replaced depends on the values of the start and optional
length parameters
Reusing Code and Writing
Functions
Reusing Code
Using require() and include():
– allow you to reuse any type of code stored as a file
– The following code is stored in a file named reusable.php:
<?php
echo ‘Here is a very simple PHP statement.<br />’;
?>
– The following code is stored in a file named main.php:
<?php
echo ‘This is the main file.<br />’;
require( ‘reusable.php’ );
echo ‘The script will end now.<br />’;
?>
– Main.php displays the content of both files
– The statements require() and include() are almost identical. The only
difference between them is that when they fail, the require() construct
gives a fatal error, whereas the include() construct gives only a
warning
Functions
Calling Functions
– The following line is the simplest possible call to a
function:
function_name();
– This line calls a function that does not require parameters
and ignores any value that might be returned by this
function
– Another possible call is with parameters
function_name(parameterList);
$returnedValue=function_name(parameterList);
– The type of calling a function depends on the definition of
the function
– Calling a function is not case sensitive, be consistent
FUnCtion_Name(); FUNCTION_NAME();
Functions
Function definition:
– The declaration begins with the keyword function,
provides the function name and parameters required, and
contains the code that will be executed each time this
function is called.
function Function_name(parameters){
statements;
}
– It is a good idea to have a file or set of files containing your
commonly used functions. You can then have a require()
statement in your scripts to make your functions available
when required.
Functions
Variable Scope
– Variables declared inside a function are in scope from the statement in
which they are declared to the closing brace at the end of the
function.
• This is called function scope. These variables are called local variables.
– Variables declared outside functions are in scope from the statement
in which they are declared to the end of the file, but not inside
functions.
• This is called global scope. These variables are called global variables.
– The special superglobal variables are visible both inside and outside
functions
– Using require() and include() statements does not affect scope. If the
statement is used within a function, function scope applies. If it is not
inside a function, global scope applies.
– The keyword global can be used to manually specify that a variable
defined or used within a function will have global scope.
– Variables can be manually deleted by calling unset($variable_name).
Functions
Passing by Reference Versus Passing by Value
– Consider the following example
function increment($value, $amount = 1)
{ $value = $value +$amount; }
$value = 10;
increment ($value);
echo $value;
– This prints the value 10, which is not incremented
– Can be modified in two ways
Pass by reference:
function increment(&$value, $amount = 1)
{ $value = $value +$amount; }
Modify the scope:
function increment($value, $amount = 1)
{ global $value; $value = $value +$amount; }
Functions
Returning from Functions:
– The keyword return stops the execution of a function
function myfunction(){
statements;
if (condition)
return;
statements; }
Returning Values from Functions:
– To send some value use return followed by value
function add($x, $y){
$sum=$x+$y;
return $sum; }
Storing and Retrieving Data
Storing and Retrieving Data
• Data can be stored:
– Flat/text files
– Database
• Writing to a file is done in three steps:
– Open the file, or create if it doesn’t exist
– Write the data to the file.
– Close the file.
• To read from a file
– Open the file
– Read the data
– Close file
Storing and Retrieving Data
fopen (path, mode)
– has two arguments filepath and mode
– Mode can be for writing, reading,
replacing and so on.
• r - Read- Open the file for reading, beginning from
the start of the file.
• r+ - Read - Open the file for reading and writing,
beginning from the start of the file.
• w - Write - Open the file for writing, beginning from
the start of the file. If the file already exists, delete
the existing contents. If it does not exist, try to create
it.
• w+ - Write - Open the file for writing and reading,
beginning from the start of the file. If the file already
exists, delete the existing contents. If it does not
exist, try to create it.
Storing and Retrieving Data
fopen (path, mode)
• x - Cautious write - Open the file for writing,
beginning from the start of the file. If the file already
exists, it will not be opened, fopen() will return false,
and PHP will generate a warning.
• x+ - Cautious write - Open the file for writing and
reading, beginning from the start of the file. If the file
already exists, it will not be opened, fopen() will
return false, and PHP will generate a warning.
• a – Append - Open the file for appending (writing)
only, starting from the end of the existing contents, if
any. If it does not exist, try to create it.
• a+ - Append Open the file for appending (writing)
and reading, starting from the end
• b- Binary- Used in conjunction with one of the other
modes
Storing and Retrieving Data
fwrite(filePtr, str)
– Writes the string str to a file pointed by filePtr
– Example
$fb = fopen(“c:\\myfolder\\file.txt”,a)
if(!$fb){
echo “Error message”;
exit(1);
}
$str=“This is a text to be written on file”;
fwrite($fb,$str);
– After using a file it should be closed
fclose($fb);
Storing and Retrieving Data
Reading from a file:
– To read a character at a time
$char = fgetc($fileptr);
$char = fgetc($fb);
– To read a string at a time
$str = fgets(fileptr, length);
$str = fgets($fb, 999);
Useful functions
– feof(fileptr) – returns if the pointer is at the end of the file
While(!feof($fb)){ $char=fgetc($fb);}
– file_exists(filepath) – returns true if it exists
If(file_exists(“c:\\myWeb\\IT.txt”))
$fb=fopen(“c:\\myWeb\\csed.txt”), rb);
– filesize(path) – returns file size if it exists
– unlink(filepath) – deletes a file and returns true if successful
– flock(fileptr, operation)- locks the file for r, w
– Navigating Inside a File
• rewind(fileptr)-points to the beginning
• fseek(fileptr,offset) – points to specific location- offset
• ftell(fileptr) – how far the pointer is in bytes
Storing and Retrieving Data
Database Management Systems
• Problems with Using Flat Files
– When a file grows large, working with it can be very slow.
– Searching for a particular record or group of records in a
flat file is difficult
– Dealing with concurrent access can become problematic.
– Inserting records into or deleting records from the middle
of the file (random access)
– Beyond the limits offered by file permissions, there is no
easy way of enforcing different levels of access to data
Storing and Retrieving Data
• How RDBMSs Solve These Problems
– RDBMSs can provide much faster access to data
than flat files.
– RDBMSs can be easily queried to extract sets of
data that fit certain criteria.
– RDBMSs have built-in mechanisms for dealing
with concurrent access so that you, as a
programmer, don’t have to worry about it.
– RDBMSs provide random access to your data.
– RDBMSs have built-in privilege systems. MySQL
has particular strengths in this area.

You might also like