Lecture 9
Lecture 9
Functions in PHP
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
Before writing texts in to the file, it must be opened
fopen (path, mode)
– has two arguments filepath and mode
– MODE
The mode parameter specifies the type of access you
require to the stream. It may be writing, reading,
replacing and so on. The mode types include:
• 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
• When you open the file do you want to create the file, then write to it or do you want to open the file and
append to it?
For creating/writing/reading use w+
For opening/appending/reading use r+
"r"
Open a file for reading. The file must exist.
"w"
Create an empty file for writing. If a file with the same name already exists its content is erased and the file
is treated as a new empty file.
"a"
Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.
"r+"
Open a file for update both reading and writing. The file must exist.
"w+"
Create an empty file for both reading and writing. If a file with the same name already exists its content is
erased and the file is treated as a new empty file.
"a+"
Open a file for reading and appending. All writing operations are performed at the end of the file, protecting
the previous content to be overwritten. You can reposition the internal pointer to anywhere in the file for
reading, but writing operations will move it back to the end of file. The file is created if it does not exist.
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
– Navigating Inside a File
• rewind(fileptr)-points to the beginning
• fseek(fileptr,offset) – points to specific location- offset
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.
String Manipulation
String Functions
Trimming Strings:
trim() - strips whitespace (newline, carriage return, space, tab etc) from the start and end of a string
<?php
$text = "\t\tThese area few words :) ... ";
var_dump($text);//string ' These area few words :) ... ' (length=31)
var_dump(trim($text));//string 'These area few words :) ...' (length=27)
?>
trim(str, ‘listChars’) – strips listChars from end/end str
$hello = "Hello World";
$trimmed = trim($hello, "Hdle"); //prints o Wor
var_dump($trimmed); //prints 'o Wor'
rtrim() – strips whitespace (or other characters) from end of a string
$hello = "Hello World";
$trimmed = rtrim($hello, "rld");
var_dump($trimmed);//prints Hello Wo
ltrim() – strips whitespace (or other characters) from start of a string
$hello = "Hello World";
$trimmed = rtrim($hello, ”Hed");
var_dump($trimmed);//prints 'llo World'
Formatting Strings for printing:
nl2br() – converts newlines (\n) to <br> html tag
printf() – same as echo, but it can format a string
$total = 12.4;
printf(“Total = %.2f”, $total); //prints Total=12.40
String Functions
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
String Functions
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 info
@bdu.edu.et
join() – same as I
• join(“@”, $address) returns [email protected]
String Functions
<?php
$response='hi,how are you doing?';
$token = strtok($response, ', ');
The Output is:
echo $token.'<br />'; hi
while ($token!=‘’) string 'how' (length=3)
{ string 'are' (length=3)
string 'you' (length=3)
$token = strtok(', '); string 'doing?' (length=6)
var_dump($token).'<br />'; boolean false
} done chopping!!
echo 'done chopping!!';?>
String Functions
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.
$a="Internet Engineering";
echo substr($a,7)."<br>";//prints t Engineering
echo substr($a,7,10);//prints t Engineer
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
$a="B"; The Out put is:
$b='b'; 1
echo strcmp($b,$a);
• It is case sensitive
strcasecmp() – identical to strcmp() but it is not case sensitive
The Out put is:
$a="B";
0
$b='b';
echo strcasecmp($b,$a);//output:
String Functions
Testing String Length:
int strlen(string str) – takes a string and returns the number of characters
<?php
$password=‘123456’;
If(strlen($password)<8){ echo “invalid password”:}
else {“valid password”;}
?>
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.
$a="Computer Education";
$b='E';
echo strstr($a,$b).'<br>';//output:Education
echo stristr($a,$b).'<br>';//;//output:er Education
echo strrchr($a,$b).'<br>';//;//output:Education
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.
String Functions
Replacing Substrings:
mixed str_replace(needle, new_needle, haystack) - 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
<?php
$a="Computer is an electronic machine";
The output:
$b='an electronic';
Computer is a mechanical Machine.
$c="a mechanical";
echo str_replace($b,$c,$a);
?>
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
String Functions
<?php
$a="Computer is an electronic machine";
$c=",a mechanical“;
echo substr_replace($a,$c,9,16);
echo '<br>';
echo substr_replace($a,$c,0);
echo '<br>';
?> The output:
Computer ,a mechanical machine
,a mechanical
Chapter 2
FORMS AND SERVER SIDE SCRIPTS
•GET data comes from the URL itself, and will typically
follow the name of the script file in the URL
•The start of GET data is indicated with a question mark
(?).
•The name of the field is followed by an equal sign (=) and
the value of the field.
•Each field is then separated by an ampersand (&).
•Here's an example of a URL with GET data for first and last
name:
http://localhost/myform.php?usname=David&passw=123
• The disadvantages of using get method is that the data sent
will be seen by other user so we can say that it is not secure.
• The total amount of characters in the value of a GET
method is limited
•Its advantage is:
• GET requests can remain in the browser history
• GET requests can be bookmarked
• GET requests can be distributed & shared
•Get data is accessed with the $_GET associative array in
POST