SE - WEB - Chapter 5 PHPv1
SE - WEB - Chapter 5 PHPv1
Jimma, Ethiopia.
Server side scripting
It is a web technology that allows custom HTML to be delivered to a client machine where
the code that generates processed on the web server.
Server-side language code remains on the web server. After it has been processed, the server
sends only the output of the script to the user as HTML format.
Server-side language brings websites to life in the following ways:
Uploading files through a web page
Reading and writing to files
Displaying and updating information dynamically
Sending feedback from your website directly to your mailbox
Using a database to display and store information
Making websites searchable. Etc…
2
How Server side scripting work
When a PHP–driven website is visited, it sets in train the following sequence of events:
The browser sends a request to the web server.
The web server hands the request to the PHP engine, which is in the server.
The PHP engine processes the code. It might also query a database
The server sends the completed page back to the browser.
3
Introduction to PHP
PHP is the web development language written by and for Web developers.
PHP stands for Hypertext Preprocessor. PHP is currently in its fifth major version called
PHP5.
PHP is a server-side scripting language, which can be embedded in HTML or used as a
standalone binary. it is a server-side scripting language, which means that the scripts are
executed on the server.
The server reads the PHP code and outputs browser-friendly HTML
Because PHP scripts execute on the server, PHP can dynamically create the HTML code
that generates the Web page. This allows individual users to see customized Web pages.
Web page visitors see the output from scripts, but not the scripts themselves.
PHP is particularly strong in its ability to interact with databases. PHP handles connecting to
the database and communicating with it, avoiding the knowledge of technical details for
connecting to a database: i.e MySQL, PostgreSQL, oracle, Sybase.
Cont...
With PHP you can store data on the server as files or in databases.
PHP supports a large number of major protocols such as POP3, IMAP.
PHP4 added support for Java and distributed object architectures (COM and CORBA),
making n-tier development a possibility for the first time.
Create a customized user experience for visitors based on information that you have
gathered from them.
What is a PHP File?
? PHP files may contain text, HTML tags and scripts
? PHP files are returned to the browser as plain HTML
? PHP files have a file extension of ".php", ".php3", or ".phtml"
PHP Syntax
The PHP code is enclosed in special start and end processing instructions <?php and ?>
You can add PHP code to your web page by using tags, similar to other tags in the HTML
file.
The PHP code section is enclosed in PHP tags with the following form:
<?php PHP statements ?>
PHP code is executed on the server, generating HTML which is then sent to the client. The
client would receive the results of running that script, but would not know what the
underlying code was.
For example, you can add the following PHP section to your HTML file.
<?php echo “This line brought to you by PHP”; ?>
Web pages that contains PHP should be saved with .php extension
<?php echo “<p>Order processed. </p>”; ?>
Cont...
The two most basic ways for displaying output in PHP are echo and print. Both can be used
either with parentheses or without.
echo outputitem1 and echo (output);
print output; and print(output);
Example: different ways of echo and print PHP supports two types of comments:
• single-line comment (short
echo 123; //output: 123
comment) by using the # or //
echo “Hello World!”; //output: Hello world! • multi-line comment (long
echo “Hello”, ”World!”; //output: Hello World! comment) by using /* */
In PHP, all variable names should start with a dollar sign ($). This tells PHP that it
is a variable name.
To store information in a variable, use a single equal sign (=).
For example:
$age = 21;
$price = 20.52;
$temperature = -5;
$name = “Clark Kent”;
echo “Your age is $age”;
PHP is a loosely typed language. This means that a single variable may contain any
type of data.
Cont...
PHP has a total of eight types: integers, doubles, Booleans, strings, arrays, objects, NULL, and
resources:
Integers are whole numbers, without a decimal point, like 495.
Resources are special variables that hold references to resources external to PHP such as
database connections.
NULL is a special type that only has one value: NULL.
Cont...
Removing Variables
You can uncreate the variable by using this statement:
unset($age);
After this statement, the variable $age no longer exists. If you try to echo it, you get an
“undefined variable” notice.
You can unset more than one variable at once, as follows:
unset($age, $name, $address);
Sometimes you just need to know whether a variable exists or what type of data is in the variable.
Here are some common ways to test variables:
isset($varname) - true if variable is set, even if nothing is stored in it.
empty($varname) - true if value is 0 or is a string with no characters in it or is not set.
You can also test what type of data is in the variable. is_integer($var), is_array($var2),
is_bool($var):
Cont...
$my_var = 4;
Arithmetic Operators (+, - , / , * )
$my_var = 4; $my_var2= 5;
$sum= $my_var + $my_var2;
echo $sum;
Comparison Operators (==, <=, >=, <, >,!=)
$my_str.="hello";
$my_str = $my_str . "hello";
Pre- and Post-Increment and Decrement operators
Conditional Statements
if ($day == 5)
print(“Five golden rings<BR>”);
elseif ($day == 4)
print(“Four calling birds<BR>”);
elseif ($day == 3)
print(“Three French hens<BR>”);
elseif ($day == 2)
print(“Two turtledoves<BR>”);
elseif ($day == 1)
print(“A partridge in a pear tree<BR>”);
Cont...
switch statements: The switch statement works in a similar way to the if statement, but
allows the condition to take more than two values.
<?php
$mood = “happy";
switch ($mood) {
case "happy":
echo "Hooray, I'm in a good mood";
break;
case "sad":
echo "Awww. Don't be down!";
break;
default:
print "Neither happy nor sad but $mood";
break; }
?>
Using Loops
$counter = 0;
while ( $counter < 5 ) {
$counter++; The output of this statement is the following:
Last line in loop: counter=1
if ( $counter == 3 ) {
Last line in loop: counter=2
echo “break\n”; break
break; First line after loop
}
echo “Last line in loop: counter=$counter\n”;
}
echo “First line after loop\n\n”;
Cont...
Exercise
1. Write a while loop that displays prime numbers between 1 and 100
2. Write a for loop that displays the squared and cubed value of numbers between
0 and 100.
3. Write a do while loop that calculates the factorial of a number.
4. Write a loop that gets the factors of a given number.
ARRAY
$GLOBALS: Contains all the global variables. For example, if you use the statement,
$testvar = 1, you can then access the variable as $GLOBALS [‘testvar’].
$ _POST: Contains all the variables contained in a form if the form uses method=”post”.
$HTTP_POST_VARS: Same as $ _POST.
$ _GET: Contains all the variables passed from a previous page as part of the URL. This
includes variables passed in a form using method=”get”.
$HTTP_GET_VARS: Same as $ _GET.
$ _COOKIE: Contains all the cookie variables.
$HTTP_COOKIE_VARS: Same as $ _COOKIE.
$ _SESSION: Contains all the session variables.
$HTTP_SESSION_VARS: Same as $ _SESSION.
Cont...
$_REQUEST: Contains all the variables together that are in $_POST, $_GET, and
$_SESSION.
$_FILES: Contains the names of files that have been uploaded.
$HTTP_FILES_VARS: Same as $_FILES.
$_SERVER: Contains information about your server. Because your Web server provides the
information, the information that’s available depends on what server you’re using.
$HTTP_SERVER_VARS: Same as $_SERVER.
$_ENV: Contains information provided by your operating system, such as the operating
system name, the system drive, and the path to your temp directory. This info varies
depending on your operating system
$HTTP_ENV_VARS: Same as $_ENV.
Cont...
The $_SERVER and $_ENV arrays contain different information, depending on the
server and operating system you’re using.
You can see what information is in the arrays for your particular server and operating
system by using the following statements:
foreach($_SERVER as $key =>$value)
echo “Key=$key, Value=$value\n”;
Function in PHP
Example:
function increment(&$value, $amount = 1){
$value = $value +$amount;
}
$value = 10;
increment ($value, 1);
echo $value; //prints 11
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 and are called local variables.
Variables declared outside of functions are in scope of the statement in which
they are declared to the end of the file, but not inside functions. This is called
global scope and are called global variables.
The keyword global can be used to manually specify that a variable defined or
Example: local variable
<?php
$num=50;
function test(){
$testvari = "this is a test variable";
echo “Num is ”, $num; //output: Num is
}
echo "test variable: $testvar"; //output: test variable:
echo “Num is ”, $num; //output: Num is 50
?>
The value of the variable $testvar is not printed. This is because no such variable exists
outside the test() function.
Similarly, a variable declared outside a function will not automatically be available within it.
Cont...
If you want a variable created within a function to be global, we can use the
keyword global as follows:
function fn(){
global $var;
$var = “contents”;
echo “inside the function, \$var = “.$var.”<br>”;
}
fn();
echo “outside the function, \$var = “.$var.”<br>”;
output:
inside the function, $var = contents
outside the function, $var = contents
Cont...
In PHP global variables must be declared global inside a function if they are going
to be used in that function.
<?php
$a = 1; $b = 2;
function Sum() {
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b; ?>
The above script will output "3".
By declaring $a and $b global within the function, all references to either variable
will refer to the global version.
Cont...
A second way to access variables from the global scope is to use the special PHP-
defined $GLOBALS array.
The previous example can be rewritten as:
<?php
$a = 1; $b = 2;
function Sum(){
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum();
echo $b;
?>
Execirse
Write a function that accepts a number and returns the squared and cubed value of
the number.
Write a function that accepts a number as parameter and then calculates the factorial
Cookies
A cookie is a small piece of information that is retained on the client machine, either
in the browser’s application memory or as a small file written to the user’s hard disk.
A cookie is stored by the user's browser in compliance with a request from a server
or script.
A cookie is often used to identify a user. Each time the same computer requests a
page with a browser, it will send the cookie too.
You store cookies by using the setcookie function. The general format is as follows:
setcookie(“variable”, ”value”);
For example, the following statement stores the pair city=Jimma in the cookie file on
the user’s computer: setcookie(“city”,”Jimma”);
Cont...
You can access the cookie using a built-in array called $_COOKIE.
The next Web page can display the information from the cookie by using the following statement.
echo “Your home city is “.$_COOKIE[‘city’]; //Your home city is Jimma
Setting expiration dates
If you want the information stored in a cookie to remain in a file on the user’s computer after the
user leaves your Web site, set your cookie with an expiration time, as follows:
setcookie(“variable”, ”value”, expiretime); The expiretime value sets the time when the cookie
expires. setcookie(“state”, ”CA”, time()+3600); #expires in one hour
Deleting a Cookie setcookie(“Name”, $Name, time()+(3*86400)) #expires 3 days
Officially, to delete a cookie, you should call setcookie() with the name argument only:
setcookie(“city");
This approach does not always work well, however, and should not be relied on. It is safest to set the
cookie with a date you are sure has already expired: setcookie(“city", "", time()-60);
Session(Cont...)
You should open a session at the beginning of each Web page. Open the session with the
session_start function, as follows:
session_start();
The function first checks for an existing session ID number.
If it finds one, it sets up the session variables.
If it doesn’t find one, it starts a new session by creating a new session ID number.
To avoid an error, the session_start function must be called before any output is sent.
This means that it is must be the first line code in your program.
You may want to restrict your site to users with a valid user ID and password.
For restricted sessions that users log into, you often want users to log out when they’re
finished.
To close a session, use the following statement wherever to want to close the session:
session_destroy();
Cont...
To save a variable in a session so that it’s available on later web pages, store the value in the
$_SESSION array, as follows:
When you open a session on any subsequent web page, the values stored in the
$_SESSION array are available.
If you want to stop storing any variable at any time, you can unset the variable by using
the following statement:
unset($_SESSION[‘varname’]);
Working with Forms
We use one of two methods to submit form information. The methods pass the form data
differently and have different advantages and disadvantages
GET method:
The form data is passed by adding it to the URL that calls the form-processing script.
For example, the URL may look like this:
processform.php?lname=Smith&fname=Goliath
The advantages of this method are simplicity and speed.
The disadvantages are that
less data can be passed and
the information is displayed in the browser, which can be a security problem in some
situations.
Cont...
POST method:
The form data is passed as a package in a separate communication with the
processing script.
The advantages of this method are unlimited information passing and security of
the data.
The disadvantages are the additional overhead and slower speed.
The form data is available in the processing script in the PHP built-in arrays.
Information from forms that use the POST method is available in the built-in array
called $_POST.
If your form uses the GET method, the information is available in the array $_GET.
Both types of form information are also stored in an array called $_REQUEST.
You get information from the array by using the form field name as the array key.
Cont...
PHP is particularly strong in its ability to interact with databases. PHP supports pretty much
every database out there. The most commonly used database with PHP is MySQL
MySQL is a free and open source database that has a lot of users especially for web
applications.
Whichever database you’re using, the steps to interact with a database are similar:
Connect to the database.
Send an SQL query that contains instructions for the database software.
If you retrieved data from the database, process the data.
Close the connection to the database.
Connecting to the database
The first step in a database interaction is connecting to the database. You have to use a PHP
To process the data returned from database, you need to get it from the temporary
table where it is placed when the SQL query is executed.
We use PHP database functions to get the data from the temporary table.
The data is stored in the temporary table in rows and columns.
You can use PHP functions to retrieve one row from the table and store it in an
array
The array has the field names as the array keys.
For MySQL, the statement is as follows:
$row = mysql_fetch_array($result);
It requires one of the mysql_fetch functions to make the data fully available to PHP.
Cont...
<?php
$con = mysql_connect("localhost","root","vertrigo");
mysql_select_db(“Sales”);
$query = “SELECT * FROM Customers”;
$result = mysql_query($query);
echo(“<TABLE border=’1’>”);
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo('<TD> '.$row["ID"].' </TD> ');
echo('<TD>'. $row["firstname"] . '</TD> ');
echo('<TD> '.$row["lastname"] .'</TD> ');
echo('<TD> '.$row["sex"].' </TD> ');
echo "</tr>";
} echo(“</TABLE><BR>\n”); ?>
Inserting Data into Database
Inserting new items into the database is remarkably similar to getting items out of the
database.
You follow the same basic steps
make a connection,
send a query, and
check the results.
In this case, the query you send will be an INSERT rather than a SELECT.
$query = “INSERT INTO users VALUES($ID, $fn, $ln, $sx, $tl, $st)”;
$result = mysql_query($query);
if (mysql_affected_rows($result) >= 1)
echo ‘<P>Your information has been saved.</P>’;
else
echo ‘<P>Something went wrong with your signup attempt.</P>’;
Cont...
In addition to insertion, you can do many other operations on database using SQL
SELECT item_list FROM table_list WHERE search_condition;
select lname, fname, balance from account where balance > 10000
CREATE TABLE table-name (column-name data-type, .... )
Create table customer(lname varchar(20), fname varchar(20), branch varchar(30), balance number);
INSERT INTO table_name(column_names) VALUES (value_list)
INSERT INTO account (lname, fname, branch, balance) VALUES ('john', 'smith', 101, 10000)
DELETE FROM table_name WHERE search_condition
UPDATE account SET balance = balance * 1.06 where balance > 1000
Closing the connection
Any open database connections are closed when the script ends.
However, it is good programming practice to close the connections in the script to
avoid any possible problems.
You close database connections with a PHP function
For example, for MySQL, use the following function to close a database
connection:
mysql_close($connect);
Other PHP-Database Functions
• field_index is the numerical offset of the field. Note that field_index starts at 0.
mysql_list_tables — List tables in a MySQL database.
<?php
$link = mysql_connect('localhost', 'root', 'vertrigo');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_row($db_list)) {
echo $row[0] . "<br>";
}
$tn = mysql_list_tables(“lab", $link);
while($row = mysql_fetch_array($tn, MYSQL_NUM)){
echo $row[0]."<br>";
}
?>
Working with Files
Uploading Files
You may want users to upload files to your Web site. For example, you may want users to be
able to upload resumes to your job-search Web site or pictures to your photo album Web site.
You can display a form that allows a user to upload a file by using an HTML form designed
for that purpose.
The general format of the form is as follows:
<form enctype=”multipart/form-data” action=”file.php” method=”post”>
<input type=”hidden” name=”MAX_FILE_SIZE” value=”30000”>
<input type=”file” name=”user_file”>
<input type=”submit” value=”Upload File”>
</form>
Cont...
When the user submits the form, the file is uploaded to a temporary location.
The script that processes the form needs to copy the file to another location because the
temporary file is deleted as soon as the script is finished.
You can use phpinfo() to see where the temporary files are stored.
If you don’t like the location of the temporary directory, you can change it by changing
upload_tmp_dir in the php.ini file.
If no directory is specified in php.ini, a default temporary directory is used.
Accessing Information About An Uploaded File(Cont...)
Along with the file, information about the file is sent with the form.
This information is stored in the PHP built-in array called $_FILES.
An array of information is available for each file that was uploaded.
You can obtain the information from the array by using the name of the field.
$_FILES[‘fieldname’][‘name’] – contains filename
$_FILES[‘fieldname’][‘type’] – contains type of file
$_FILES[‘fieldname’][‘tmp_name’] – contains temporary location of file
$_FILES[‘fieldname’][‘size’] – contains size of file
For example, suppose you use the following field to upload a file:
<input type=”file” name=”user_file”>
Moving Uploaded Files To Their Destination
Since the temporary file created during upload is deleted when the script finishes, it
has to be moved to another location if you want to store it permanently.
The general format of the statement that moves the file is as follows:
move_uploaded_file(path/tempfilename, path/permfilename);
You can use the following statement to move the file to your desired location, in this
case, c:\data\new_file.txt:
move_uploaded_file($_FILES[‘user_file’][‘tmp_name’], ‘c:/data/new_file.txt’);
Working with Date and Time
PHP's time() function gives you all the information that you need about the current date and time. It
requires no arguments and returns an integer.
For us humans, the returned number is a little hard on the eyes, but it's extremely useful nonetheless.
echo time(); //1060751270
This represents August 12th, 2003 at 10:07PM
PHP offers excellent tools to convert a timestamp into a form that humans are comfortable with.
There are two ways to get useful information from timestamp:
Using getdate() function
Using date() function
The getdate() function optionally accepts a timestamp and returns an associative array
containing information about the date.
If you omit the timestamp, getdate() works with the current timestamp as returned by time().
Cont...
The table lists the elements contained in the associative array returned by getdate().
Key Description Example
seconds Seconds past the minute (0–59) 28
minutes Minutes past the hour (0–59) 7
hours Hours of the day (0–23) 12
mday Day of the month (1–31) 20
wday Day of the week (0–6) 4
mon Month of the year (1–12) 1
year Year (4 digits) 2000
yday Day of year (0–365) 19
weekday Day of the week (name) Thursday
month Month of the year (name) January
0 Timestamp 948370048
Cont...
PHP has built-in mathematical constants, and trigonometric, logarithmic, and base conversion
functions. PHP constants are:
function Behavior
pow() Takes two numerical arguments and returns the first argument raised to the power
of the second. The value of pow($x, $y) is xy.
exp() Takes a single argument and raises e to that power. The value of exp($x) is ex.
log() The “natural log” function. Takes a single argument and returns its base e logarithm.
If ey = x, then the value of log($x) is y.
log10() Takes a single argument and returns its base-10 logarithm. If 10 y = x, then the value
of log10($x) is y.
pi() Takes no arguments and returns an approximation of pi (3.1415926535898). Can be
used interchangeably with the constant M_PI.
sin() Takes a numerical argument in radians and returns the sine of the argument as a
double.
Cont...
cos() Takes a numerical argument in radians and returns the cosine of the argument as a
double.
tan() Takes a numerical argument in radians and returns the tangent of the argument as a double.
asin() Takes a numerical argument and returns the arcsine of the argument in radians. Inputs must be
between –1.0 and 1.0, otherwise, it will return a result of NAN. Results are in the range –pi / 2 to pi /
2.
acos() Takes a numerical argument and returns the arccosine of the argument in radians. Inputs must be
between –1.0 and 1.0, otherwise, it will return a result of NAN. Results are in the range 0 to pi.
atan() Takes a numerical argument and returns the arctangent of the argument in radians. Results are in
the range –pi / 2 to pi / 2.
atan2() A variant of atan() that takes two arguments. Atan($y, $x) is identical to atan($y/$x) when $x is
positive, but the quadrant of atan2’s result depends on the signs of both $y and $x. Range of the
result is from –pi to pi.
sqrt ($num) Returns square root of a number.
floor($float) Returns the next lowest integer value by rounding down value.
ceil($float) Returns the next highest integer value by rounding up value.
Cont...
One of the goals of software engineers is to reuse code in instead of writing new code.
Reusing existing code reduces costs, increases reliability, and improves consistency.
Ideally, a new project is created by combining existing reusable components, with a
minimum of development from scratch.
PHP provides two very simple, yet very useful, statements to allow you to reuse any type
of code.
Using include or require statement, you can load a file into your PHP script.
The file can contain anything you would normally type in a script including PHP
statements, text, HTML tags, etc
The two functions are identical in every way, except how they handle errors:
include() generates a warning, but the script will continue execution
require() generates a fatal error, and the script will stop
Cont...
These two functions are used to create functions, headers, footers, or elements that will be reused
on multiple pages
Using require:
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 called main.php:
<?php
echo “This is the main file. <br> “;
require(“reusable.php”);
echo ”The script will end now. <br>”;
Using include(Cont...)
The statements require() and include() are very similar, but some important
differences exist in the way they work.
For example, we might decide that we are opening files a lot and rather than
retyping the same lines of code every time, we want an include file to open them
for us.
Our include file might be called openfile.php and resemble the following:
//openfile.php <?php
<?php $name = “file.txt”;
$fp = fopen($name, $mode); $mode = “r”;
if($fp){ $result = include(“openfile.php”);
echo “Could not open the file.”
if($result == 1) {
return 0;
} else
//continue reading/writing the file
return 1; }
?> ?>
Reading Assignment