Page 1 of 25 - AlaSoch

strawberriesfarctateΛογισμικό & κατασκευή λογ/κού

4 Νοε 2013 (πριν από 3 χρόνια και 10 μήνες)

89 εμφανίσεις

Page 1 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
PHP
PHP is a server-side scripting language. Means that the script is run on web
browser and not on users browser. Therefore there is no need to worry
about compatibility issues. PHP is comparatively new language unlike Perl
(CGI) and Java). PHP is becoming one of the most popular scripting
language on the internet.

PHP Install
Since we know that PHP is a server side scripting language, there is no need for your users to
install new software
, your web host will need to have PHP setup on their server
.
PHP Syntax
Actually writing PHP on your computer is very simple. except text editor (like Notepad
in
Windows) You don't need any specail software. and you are ready to write your.first PHP
script.
PHP Variables
As with any other programming languages, PHP allows to define variables. In PHP there are
many variable types,but the most common among them is a String variable.
PHP Operators
Operator is a symbol or can be a series of symbols, which when used .with some values
performs some action and produce a new value
PHP Functions
Function play a very important role in any programming language, including PHP.They are
pieces of code which takes in some value processes it and produce results.
PHP Forms
Setting up a form in PHP script is exactly the same as in HTML
PHP Includes
The include() function includes and evaluates the specified file. The include() statement takes
all the contents of the specified file andcopies it to the one which consist this statement.
PHP Files
There are many built-in functions in PHP to handle files and directories. Using these functions
we can read, write, delete, and get lots of information of the files
PHP Cookies
After a request from script or a server user's browser stores
small amount of data, This data is
called cookie.
PHP Session
A session-enabled page allocates unique identifiers to the users the first time they access the
page, and then reassociates them with previously allocated ones when they return to the page
PHP Email
The major advantage of server side scripting language is that, it provides a way to take a form
input from a server and send e-mail to a perticular e-mail address
PHP Sql
The process of accessing and working with a database
connection from within a PHP script.





Page 2 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
Introduction to PHP
Up until very few people even attempted scripting on the internet, let alone
mastered.
Though many people started building their own websites, scripting
languages become more important. This has made scripting languages
easier to learn and PHP is one among those scripting language. PHP is the
most powerful scripting language.


What Is PHP?
PHP stands for Hypertext Preprocessor and is a server-side scripting language. It means
that the script is run on web browser and not on user’s browser. Therefore there is no need to
worry about compatibility issues. PHP is comparatively new language unlike Perl (CGI) and
Java). PHP is becoming one of the most popular scripting languages on the internet.

Why Learn PHP?
There might have arise a question in your mind, Why to learn PHP? When there are other
languages such as Perl. Why should learn a scripting language at all? Learning a scripting
language can open up many new possibilities for your website. You might have observed that
pre-made scripts downloaded from sites often contain advertising for the Author or will not do
what exactly we want it to do. But if u have the knowledge of scripting language you can edit
to make it work as you wish or can easily create your own script.
A script in your web-site allows to add many interactive features like message boards,
guestbook, feedback forms, counters, content management
, advertising managers, portal
systems and many other features. When all these features are found in your website it gives a
professional image to your web-site.
Download and Install PHP
Since we know that PHP is a server side scripting language, there is no need
for your users to install new software
, your web host will need to have PHP
setup on their server.
If your server dont support PHP you can ask web host to install it as it is
free to download.

How to install PHP?
IF PHP is supported by your server then you need not do anything. You need not to compile
anything or install any extra tools. just create your php files and save them in your web
directory. Then server will parse them.
Page 3 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
And if PHP is not supported by the server, you should install it. Here is a link to a good tutorial
from PHP.net on how to install PHP5:
http://www.php.net/manual/en/install.php
Download PHP
Download PHP for free here: http://www.php.net/downloads.php
Download MySQL Database

Download MySQL for free here: http://www.mysql.com/downloads/index.html
Download Apache Server
Download Apache for free here: http://httpd.apache.org/download.cgi

Syntax for PHP
General Syntax for PHP
PHP scripts should always be enclosed in between two PHP tags. This tells the server to parse
all the information between them as PHP code. The three different ways for this are as follows:
<?
Here is a PHP Code
?>
<?php
Here is a PHP Code
php?>
<script language="php">
Here is a PHP Code
</script>

Your First PHP Script
You will be writing very basic code as your first PHP script. All that it will do is, just print
out
all the information about PHP on your server. Write following code in your text editor:
<?
phpinfo();
?>
Nearly all lines are ended with a semicolon as with many other scripting and programming
languages and if you miss it you will get an error.
Page 4 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar

Finishing and Testing the PHP Script
After writing your script save it as phpinfo.php and then upload it to your server. in the normal
way. And now, using your browser, go to the URL of the script. If it has worked (and if PHP is
installed on your server) you will get a huge page containing all the information about PHP on
your server
Variables in PHP
As with any other programming languages, PHP allows to define variables.
In PHP there are many variable types, but the most common among them is
a String variable.

String Variable
A String variable holds text and numbers. All strings begin with a symbol "$". To assign some
text to the string you can use the following code:
$welcome_text = "Hello and welcome to BS07";
Strings are case sensitive so the string variable $Welcome_Text is not the same as
$welcome_text A string name can contain letters, underscores and numbers. But it should not
begin with a number or underscore. When assigning numbers to the string variables you need
not include the quotes so:
$user_id = 987
would be allowed.

How to display the Variable.
We use exactly the same code to display a variable on the screen, as we used to display the
text. But slightly different form. The following code would display the welcome text:
<?
$welcome_text = "Hello and welcome to BS07";
print($welcome_text);
?>
As you can see, the only major difference is that you need not put the quotation marks if you
are printing
a variable.

Page 5 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
How to format the Text?
Output from your PHP programs is quite boring unfortunately. All the content is just output in
the browser's default font. It is easy, to format your text using HTML. This is because, as we
know that the PHP is a server side scripting language, code is been executed before the page
is sent to browser. This means, only the resulting information from script is sent, so in the
above example, the browser would just sent the text:
Hello and welcome to BS07
This means, that you can include standard HTML markup in your strings and scripts. The
problem with this is that many HTML tags require the " symbol. You may notice that this
symbol will clash with the quotation marks used to print
the text. To overcome this confusion
you must tell the script which quotes to be used (those at the beginning and end of the
output) and which to be ignored (those of the HTML code).

How to solve this problem?
To illustrate this let us consider the example, Change the font of the text to the Arial font in
red. The code for this is as follows.
<font face="Arial" color="#FF0000">
</font>
As you can see this code contains 4 quotation marks so can confuse the script. To solve this
you must add a backslash before each quotation mark to make the PHP script ignore it. Then
the code would look like.
<font face=\"Arial\" color=\"#FF0000\">
</font>
Now you can include this in your print statement, which will make the browser display it.
print("<font face=\"Arial\" color\"#FF0000\">Hello and welcome to BS07</font>");
Output:Hello and welcome to BS07

Operators in PHP
Operator is a symbol or can be a series of symbols, which when used with
some values performs some action and produce a new value.

Assignment Operator
Assignment operator "=" is most widely used operator in PHP. This operator is used to
initialize the variable. This operator is used in between two operands. It evaluates right-hand
Page 6 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
operand and assigns its value to the left-hand operand. Most operators are used to produce
some result without changing the value of their operands. But assignment operator breaks this
rule.
print
($name = “Umer”); //assigns “Umer” to “$name”, then outputs “$name”

At the same time you can perform multiple things. So you can assign not only the word
“Umer” to the variable “$name”, but can also output the variable at (almost) the same time..

Dot Operator
Using the concatenation operator we can append additional characters to a string. This is a
single dot “.”. Treating both operands as the string types, it appends the right-hand operand
to the left-hand operand; the result is of course, a string.
$first_name = “Umer”;
$last_name = “BS07”;
print $first_name . $last_name; //outputs “Umer BS07”

Arithmetic Operators
Arithmetic operators are also used in many programming languages. You know for sure what
each of them do, so we’ll just stick to point them out: addition “+”, subtraction “-”, division
“/”, multiplication “*”, and modulus “%”.
<?php

/* define some variables */
$mean = 5;
$median
$mode = 9;

//post-increment operator
$mean++;
//$mean now equals 6

//pre-increment operator
++meanx;
//$mean is now 7

//post-decrement operator
$mean--;
//$mean is down to 6

//pre-decrement operator
--$mean;
//$mean is down to 5

//addition operator
$median = $mean + $mode;
//$median now equals 14
Page 7 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar

//substraction operator
$median = $mode - $mean;
//$median now equals 4

php?>


Comparison Operators
You've already seen some of the arithmetic and string operators in PHP's. However, the
language also comes with operators that are designed specifically to compare two values:
These operators are called "comparison operators". Here's an example to demonstrates
Comparison Operators in action:
<?php

/* define some variables */
$mean = 9;
$median = 10;
$mode = 9;

// less-than operator
// returns true if left side is less than right
// returns true here
$result = ($mean < $median);
print "result is $result<br /> ";

// greater-than operator
// returns true if left side is greater than right
// returns false here
$result = ($mean > $median);
print "result is $result<br /> ";

// less-than-or-equal-to operator
// returns true if left side is less than or equal to right
// returns false here
$result = ($median <= $mode);
print "result is $result<br /> ";

// greater-than-or-equal-to operator
// returns true if left side is greater than or equal to right
// returns true here
$result = ($median > = $mode);
print "result is $result<br /> ";

// equality operator
// returns true if left side is equal to right
// returns true here
$result = ($mean == $mode);
print "result is $result<br /> ";

// not-equal-to operator
// returns true if left side is not equal to right
// returns false here
$result = ($mean != $mode);
Page 8 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
print "result is $result<br /> ";

// inequality operator
// returns true if left side is not equal to right
// returns false here
$result = ($mean <> $mode);
print "result is $result";

php?>

Loops and Arrays in PHP
The WHILE Loop
The WHILE loop seems very useful when we want to execute a piece of code for several times.
The loop keep executing the code until certain condition is reached.
This is one of the most useful command in PHP.
If you want to execute a piece of code for several times without retyping, you can make use of
a while loop. For example if you have to print "Hello World" 5 times, you can use the following
code
$times = 5;
$x = 0;
while ($x < $times)
{
echo "Hello World";
++$x;
}

In the first two lines we are just setting variables. $time holds number of times the code to be
executed. $x is used to count the number of times the code has executed. Then there comes
the while loop statement, This tells the processor to execute the code while $x is less than or
equals $time. And this statement is followed by the code enclosed within { }.

Arrays in PHP
An array can hold more than one value, These are special variables used in almost many
programming languages. Values in array are stored in its own numbered 'space'. Arrays are
very useful specially when using WHILE loop.
Initialising an array is slightly different from initialising a normal variable. Setting up an array
is slightly different to setting up a normal variable. In this example let us set up an array with
5 names in it:
$names[0] = 'Salman';
$names[1] = 'Ali';
$names[2] = 'Zubair';
Page 9 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
$names[3] = 'Zahida';
$names[4] = 'Salma';

Here the array elements are numbered from 0. To insert a value to the array you must specify
the location in the array by putting a number in the brackets [ ].

Reading From An Array
Reading data from the array is very simple, it is same as we put in data. All that we have to
do is refer to array and the number of the data item which we want to read out from the
array. So if i want to print the third name of the array, then can use the following code.
echo "The third name is $names[2]";
Which would output:
The third name is Zubair


Using Arrays And Loops
One of the best use of loop is to display out all the elements in an array. Loop is used to fetch
the elements in an array if the array has huge number of elements. For example consider the
following array.
Name 1 is John
Name 2 is Paul
Name 3 is Steven
Name 4 is George
Name 5 is David

use the following code:
$number = 5;
$x = 0;
while ($x < $number)
{
$namenumber = $x + 1;
echo "Name $namenumber is $names[$x]<br>";
++$x;
}

In the code we have assigned $namenumber as "1" and $x have assigned "0", because the
counting of name should start from "1" and the first name stored in the array is in position
"0". The echo statement is executed till $x becomes greater than $number, And thus all the
names in array are read out.

Page 10 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
Functions in PHP
Function play a very important role in any programming language, including
PHP. They are pieces of code which takes in some value processes it and
produce results.
Funtions are very useful when you are writing repetitive code, and you are
in need of same code in some other script.

Function with no Arguments:
For a funtion to process on require some arguments to be passed to it. This is not the case
always, some funtions require no arguments. such funtion outputs the same message
whenever it is called on. This is illustrated in the example below.
function display_goodbye_message() //no semicolon here!
{
print “<h1>Thanks for visiting our web-site</h1>”;
}

Whenever this function is called on, it outputs the same message. It takes no arguments and
doesn't return anything.

Function to Perform Calculation
The "return" statement is used to send the result to the function. Here in this case the result is
calculated value of the purchase (which is number of items purchased multiplied by price)
function calculate_value($price, $items)
{
return ($price * $items); //returns a result
}


Calling a Function Dynamically
A function can be called dynamically in the same way we access dynamic variables. We can
treat an expression's name as a funtion name and thus can call it.
$function_name = “calculate_value”;
$function_name(40, 5);

This is identical to:
calculate_value(40, 5);


Page 11 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
Global statement in a Function.
When we want to access some important information which are outside the function, and
without using arguments. Then we have to use the "global" statement.
<html>
<body>
<?php
function add($x,$y)
{
global $exchange_rate;
$total = $x + $y + $exchange_rate;;
return $total;
}echo "1 + 16 = " . add(1,16)
?>
</body>
</html>

Here we have used the global statement to tell the function that "$exchange_rate" is declared
outside the the function. If we wont declare like this then the function would have returned
zero, since $exchange_ratewould have been "NULL".

Forms in PHP
Setting up a form in PHP script is exactly the same as in HTML

Setting Up Your Form
As in HTML, the form elements are enclosed within <form> tags. Here is a small example.
<form action="process.php" method="post">
Form elements and formatting etc.
</form<
The form element takes two values, First is the form's "action" that tells to which script the
data has to be sent. In the example above it is "process.php". It can also be in the form of
URL (e.g. http://www.vyom.co.in/scripts/private/processors/process.php) Second is the
"method" which tells the form how to send the data. POST method sends data in data stream,
and maintains it as a secret. like password GET method is used to send data making visible to
users. For example if we are sending a name=george then it would look like (e.g.
http://www.vyom.co.in/process.php?name=george)

Getting The Form Information
The variable that the form passes on by POST method is collected using $_POST. In the
following example it takes variable from the POST and assigns it to the variable $name
Page 12 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
$name=$_POST['variable'];
If we are using GET method to pass the data then should use the following code.
$variablename=$_GET['variable'];
For each variable that is passed from form, we should follow the above procedure.

How to create form to mail script
The following code is to create a system which will e-mail a user's comments to you.
HTML
<form action="mail.php" method="post">
Your Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br><br>
Comments<br>
<textarea name="comments"></textarea><br><br>
<input type="submit" value="Submit">
</form>
The above code is used to make a simple form, where a user can enter their e-mail address.
name and comments if any. Here can add extra parts if required. After adding remember to
update the php script too.
PHP
<?
function checkOK($field)
{
if (eregi("\r",$field) || eregi("\n",$field)){
die("Invalid Input!");
}
}
$name=$_POST['name'];
checkOK($name);
$email=$_POST['email'];
checkOK($email);
$comments=$_POST['comments'];
checkOK($comments);
$to="php@abc.com";
$message="$name just filled in your comments form. They said:\n$comments\n\nTheir e-
mail address was: $email";
if(mail($to,"Comments From Your Site",$message,"From: $email\n")) {
echo "Thanks for your comments.";
} else {
echo "There was a problem sending the mail. Please check that you filled in the form
correctly.";
}
?>

here we have used php@abc.com, You should replace it with your own e-mail address. save
the script as mail.php and upload both the files. And now just fill in your comment box.
Page 13 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
First part of the script stops the spammers from using your form to send their spam
messages. this is done by checking for special characters not present in the input that can be
used to trick the computer into sending messages to other addresses. It is this function which
checks for these characters. and if they are found, stops running the script.
Includes and Require in PHP
include()
The include() function includes and evaluates the specified file.
The include() statement takes all the contents of the specified file and copies it to the one
which consist this statement.
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>

test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>

require().
Similarly the require() statement includes and evaluates the specified file. Both include() and
require() works in same way, the only difference is how they handle failure. The include()
statement produces warning, but the script will continue its execution. While the require()
statement produces a Fatal Error and script stop its execution.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>

Warning:
require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Fatal error:
require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5


Page 14 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
File Handling in PHP
There are many built-in functions in PHP to handle files and directories.
Using these functions we can read, write, delete, and get lots of information
of the files.
To perform any funtion on a file we should have the right permission which
will allow us to manupulate that file.

Creating and Deleting a File
We can create a file using the funtion "touch()". The touch() funtion when called first
searches whether the specified file exists or not if the file doesnot exists it creates one with
the specfied file name. To delete a file we use the function called "unlink()". This funtion
removes the file that has been sent as an argument.
touch(“newinfo.txt”); //create a new file, if it doesn’t already exist
unlink(“oldinfo.txt”); //delete a file


Open Existing File
When a file got created, How to access it?
We can access an existing file using the funtion called "fopen()". This funtion takes two
arguments, The first argument specifies the name of the file that has to be opened, and the
second argument specifies in which mode the file has to be opened.i'e in "read-r", "write-
w"or both "read-write" mode.
If the function fopen() executes successfully then it returns an integer value known as a file
pointer. This value should be stored in a variable. This variable is used to work on with the
opened file. If the funtion fopen() fails executing for any reason, It just returns FALSE. Once
the file is used we should close it using the "fclose()" function. This function takes only the
file name as the argument.
$oldfp = fopen(“oldinfo.txt”, “r”); //opens a file for reading
if(!$fp = fopen(“newinfo.txt”, “w”)) //tries to open a file for writing
die(“Error on opening file!”); //terminates the execution of the script if it cannot open the file
fclose($oldfp);


Reading from Files
To read from the file we use the funtion called "fgets()". When this funtion is called, it reads
out all the characters until a newline(\n), or End Of File(EOF), or till a specified length is
reached.
The function "fgets()" is similar to "fgets()", Unlike fgets() it returns a single character from
a file. there is no need to specify any length as a argument, since a character is always 1 byte.
Page 15 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
$text = fgets($fp, 2000); //reads 2000 bytes at most
$chr = fgetc($fp); //reads 1 byte only


More File Handling Functions
There are a lot of other functions that you can use with files like: testing functions –
“file_exists()”, “is_file()”, “is_dir()”, “is_readable()”, “is_writeable()”, “is_executable()”;
functions that return information on files: “filesize()”, “fileatime()”, “filemtime()”, “filectime()”.
You can figure out what the function does by just reading its name.
Following table contains few File Handling functions and their description

Example

Description Preview
chdir
Changes PHP's current directory to specified directory. Returns TRUE on success
or FALSE on failure.
chroot
Change the root directory
closedir
Closes a directory handle previously opened with opendir().
copy
Makes a copy of a file. Returns TRUE if the copy succeeded, FALSE otherwise.
dir
dir -- directory class class dir { dir(string directory); string path; resource
handl...
file
Returns the contents of a file in an array.
filesize
Gets file size
fopen
Opens a file handle to be used .
fread
Reads the contents of a file descriptor assigned with fopen().
fwrite
Writes to a file descriptor opened with fopen().
getcwd
gets the current working directory string. getcwd (void) Returns the current
working directory.
opendir
Returns a directory handle that can be used with readdir(), closedir() and
rewinddir().
readdir
Reads the next file from a directory handle opened with opendir().
rename
Renames a file from the old file name to the new file name.
rewinddir
rewind directory handle, void rewinddir ( resource dir_handle) Resets the directory
stream indicated by dir_handle to the beginning of the directory.
scandir
List files and directories inside the specified path
Unlink
Deletes a file.


Page 16 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
Cookies in PHP
After a request from script or a server
user's browser stores small amount
of data, This data is called cookie.

Cookie can be accessed in three ways by a PHP script:
In a cookie there are information about a name, value, expiry date, host and path. As cookies
are sent from server through HTTP header, they end up to the user. Here are the 3 ways to
access cookies:
• using “$HTTP-COOKIE” which is the environmental variable, all cookie names and
values are present in this variable.
• using global variable “$cookie_name”, here the name should be replaced
• using “HTTP_COOKIE_VARS [“cookie_name”]” which is a global array variable. (here
replace the “cookie_name” by actual name of the cookie).
print $HTTP_COOKIE; //outputs “visits=23”
print getenv(“HTTP_COOKIER”); //outputs “visits=23”
print $visits; //outputs “23”
print $HTTP_COOKIE_VARS[visits]; //outputs “23”


How to Set a Cookie with PHP
“header()” function, or “setcookie()” function can be used to set cookie with PHP. The main
purpose of “header()” function is not to set a cookie, and works
just like “setcookie()”. Cookie
header is written by ourself by using “header()” funtion, but “setcookie()” is much automated.
//don’t output anything before this...
header(“visits=23; expires=Friday, 15-Nov-06 03:27:21 GMT;
path=/;domain
=softwareprojects.org”);
setcookie(“hits”, 23, time() + 3600, “/”, “softwareprojects.org”, 0); //notice this last extra
argument

Weather the cookies will be send over a secure connection or not is denoted by the last
argument to "setcookie()" function. Here "0" means no and "1" means yes.

How to Retrieve a Cookie Value
To retrieve a cookie value, PHP $_COOKIE variable is used. In the following example the value
of cookie named "user" is retrieved and displayed on the page.
<?php
// Print
a cookie
Page 17 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
echo $_COOKIE["user"];

// A way to view all cookies
print_r($_COOKIE);
?>

How to Delete a cookies
To delete a cookie we should SET the cookie we want to delete with the date that has already
expired. While doing so we should include the same path, secure parameters and domain
which was originally used to set the cookie.
setcookie(“visits”, 23, time() - 60, “/”,“vyom.co.in”, 0)

Weather the cookies will be send over a secure connection or not is denoted by the last
argument to "setcookie()" function. Here "0" means no and "1" means yes.

Limitations of cookies
Apart from the advantage of passing information from one page to another page or visit to
visit, Cookies do have some limitations. The maximum number of cookies that can be stored
by the browser is 20.And maximum size of the cookie is 4KB. The user's privacy is maintained
since only the originating host can read the data that has been stored.
Session in PHP
Besides cookies, there is one more way to pass information to different
web-pages: Sessions.
A session-enabled page allocates unique identifiers to the users the first
time they access the page, and then re associates them with previously
allocated ones when they return to the page. Any global variables which
were associated with the session will then become available to your code.

The difference between sessions and cookies
The main difference between sessions and cookies is that a session can hold multiple
variables, and you need not have to set cookies for every variable. By default, the session
data is stored in the cookie wich has an expiry date of zero, which means that the session
remains active only as long as the browser.Once you close the browser, all the stored
information is lost. This behavior can be modified by changing the “session. cookie_lifetime”
setting in “php.ini” from zero to whatever you want the cookie lifetime to be.

Page 18 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
How to Start a Session
Before starting to work
with sessions, you must explicitly start a session using
“session_start()” function. If you want sessions to start themselfs automatically, you should
enable the “session.auto_start” setting in PHP’s configuration file.
session_start();
//starts or resumes a function
print
“Your session ID is: “ . session_id();
//displays the session ID
session_destroy();
//ends the session; comment this line and the browser will output the same session ID as
before

After starting a session, you can access to the session ID via the “session_id()” function. After
completing the work, you can destroy the session using “session_destroy()”.

Register Variables to a Session
the main objective of the session is to hold the values of variables. You must register session
variables using the “session_register()” function, before trying to read them on a session-
enabled page. Remember that a “session_register()” requires you to pass as an argument
"variable name", and not the variable itself:
<?php
session_start();
?>
<html>
<body>
<?php
if(isset($stored_var))
{
print $stored_var; //this will not be displayed the first time you load the page, because you
haven’t registered the variable yet!
}
else
{
$stored_var = “Hello from a stored variable!”;
session_register(“stored_var”); //don’t do this: session_register($session_var)
}
?>
</body>
</html>

you can test if a variable is assigned using the “isset()” function.

Page 19 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
Remove the Registered Variables
To remove the registered variables, you need to use the session_unset() function. This
function when called destroys all variables associated with a session, both in the the script and
within session file .
<?php
session_start();
?>
<html>
<body>
<?php
session_register("test");
$test = 12;
print $test;//outputs 12 session_unset(); //$test is destroyed
session_destroy();
print $test; //outputs nothing
?>
</body>
</html>

E-mail in PHP
The major advantage of server side scripting language is that, it provides a
way to take a form input from a server and send e-mail to a perticular e-
mail address.

The Mail Command
Many of the scripting languages require special set up(like CGI) to send an e-mail, But with
PHP it is very easy, since it uses one simple command called mail(). This command is used as
follows.
mail($to,$subject,$body,$headers);

The recepients address to whom mail has to be sent is mentioned using the $to variable.
Subject line is mentioned using the $subject. And finally the body of the mail is denoted by
$body variable.
If at all any additional headers has to be added to the mail then $headers is used. For
example if we want to add cc(carbon copy) and bcc(blank carbon copy) headers then this
variable can be used.

Sending An E-mail
Befopre sending the mail you should have to set the variable content that are to be used in
mail command. Here is a simple code that illustrate this.
Page 20 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
$to = "php@abc.com";
$subject = "This is PHP Script";
$body = "PHP is one of the best scripting language";
$headers = "From: webmaster@abc.com\n";
mail($to,$subject,$body,$headers);
echo "Mail sent to $to";
Here e-mail is from webmaster@abc. This code performs two things.
• Firstly it will send a message to php@abc with
subject:'This is PHP Script'and
text: PHP is one of the best scripting language
• Secondly It will output the
text:Mail sent to php@abc to the browser.
Something you may have noticed from the example is that the From line ended with \n. This is
actually a very important character when sending e-mail. It is the new line character and tells
PHP to take a new line in an e-mail. It is very important that this is put in after each header
you add so that your e-mail will follow the international standards and will be delivered.
The \n code can also be used in the body section of the e-mail to put line breaks in but should
not be used in the subject or the To field

Error Control
if(mail($to,$subject,$body,$headers))
{
echo "An e-mail was sent to $to with the subject: $subject";
}
else
{
echo "There was a problem sending the mail. Check your code and make sure that the e-mail
address $to is valid";
}
In this code the mail() function is taken into a IF loop, If the the funtion executes properly,
then the echo statement inside the IF funtion is executed saying that the mail has been sent.
Otherwise it displays the error message saying that the mail has not sent and suggests to
correct the problem.





Page 21 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
PHP SQL Database
The process of accessing and working with a database connection from
within a PHP script is as follows.
• First you need to establish a connection to the database server.
• You should have to validate any user input
• Then select the database on the server to use.
• Execute all the desired query against the database.
• Further retrieve and process the results.
• Then create HTML or perform actions based on results.
• Finally close the database connection.

How to connect to MySQL Database?
The first step here is to connect to the database, This is done via the mysql_connect()
function, whose syntax is as follows:
mysql_connect($server , $username , $password )
<?php
$con = mysql_connect("localhost","mcs","mcs123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}// some code
?>
The first parameter $server which we have passed, is the address of MySQL server to connect
using the username and password provided by the $username and $password parameters.

How to close a Database Connection
Though not strictly necessary, sometimes it is advantageous to close an open connection to
the database when it is no longer needed, Instead of waiting for an end of the request, while
PHP will do so automatically. The syntax of mysql_close() function is as follows.
mysql_close($link)
where the parameter $link is the database connection resource returned from the
mysql_connect() function.

Page 22 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
How to select the Database to Use?
Once you have set up a database connection, the next step is to select the database on which
you will be performing queries (This is similar to SQL USE). To do so, you need the
mysql_select_db() function which has the following syntax:
mysql_select_db($database , $link);
<?php
$con = mysql_connect("localhost","mcs","mcs123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}// some code

mysql_select_db("my_db", $con);

mysql_close($con);
?>
Here $my_db is the name of database, and the other parameter $con which is optional is the
database connection resource returned by the mysql_connect() function. This function
attempts to select the specified database and return a Boolean value indicating the success or
failure.

How to perform Query against a Database
To perform a query against the database within PHP, we make use of mysql_query() function,
whose syntax is as follows:
mysql_query($query , $link);
<?php
$con = mysql_connect("localhost","mcs","mcs123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}// some code

mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person");
mysql_close($con);
?>

where $result holds the result of the query executed. Query is written inside the mysql_query
function(without the terminating semi-colon or \g), the optional parameter $con is the value
returned by the function mysql_connect(). And if the database is not closed, then PHP will use
the last opened connection.

Page 23 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
How to retrieving a Result Set?
PHP has many different methods to access the data from a result set, but they all have the
same general form. Here we are showing the example with the context of mysql_fetch_row()
function. Its syntax is as follows:
mysql_query($query , $link);
<?php
$con = mysql_connect("localhost","mcs","mcs123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}// some code

mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM person");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>
where $result holds the result returned from a successful query executed using the function
mysql_query(). This function returns a single row from the result set when called, in the form
of enumerated array, where element "0" represents the first column, element "1" represents
the second, and so on. Each subsequent call to the funtion will return the subsequent row in
the result set until no row remains. Then the function mysql_fetch_row() returns a boolean
false. Generally mysql_fetch_row() function is used in conjunction with the while loop to
retrieve the entire array as shown in the above example.
PHP Summary
What Is PHP?
PHP stands for Hypertext Preprocessor and is a server-side scripting language.
It means that the script is run on web browser and not on users browser. Therefore there is no
need to worry about compatibility issues. PHP is comparatively new language unlike Perl
(CGI) and Java). PHP is becoming one of the most popular scripting languages on
the internet
.

General Syntax for PHP
PHP scripts should always be enclosed in between two PHP tags. This tells the server
to parse
all the information between them as PHP code. The three different ways for this are as follows:
<?
Here is a PHP Code
?>
Page 24 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
<?php
Here is a PHP Code
php?>
<script language="php">
Here is a PHP Code
</script>

Rules for Variable Naming
• A variable name should always start with a letter or an underscore "_"
• A variable name only contains underscores and alpha-numeric characters (a-Z, 0-9,
and _ )
• A variable name should not contain spaces in between. If the variable name should be
of more than one word, it should be separated by underscore (like $my_string), or
with capitalization ($myString)

Operators that are used in PHP
• Assignment Operator
• Dot Operator
• Arithmetic Operators
• Comparison Operators

include()
The include() function includes and evaluates the specified file. The include() statement takes
all the contents of the specified file and copies it to the one which consist this statement.
require().
Similarly the require() statement includes and evaluates the specified file. Both include() and
require() works
in same way, the only difference is how they handle failure. The include()
statement produces warning, but the script will continue its execution. While the require()
statement produces a Fatal Error and script stop its execution..

Cookie can be accessed in three ways by a PHP script:
In a cookie there are information about a name, value, expiry date, host and path. As cookies
are sent from server through HTTP header, they end up to the user. Here are the 3 ways to
access cookies:
Page 25 of 25
CSIT – 21401 Web Programming (20) by: Haroon Akhtar
• using “$HTTP-COOKIE” which is the environmental variable, all cookie names and
values are present in this variable.
• using global variable “$cookie_name”, here the name should be replaced
• using “HTTP_COOKIE_VARS [“cookie_name”]” which is a global array variable. (here
replace the “cookie_name” by actual name of the cookie).

The difference between sessions and cookies
The main difference between sessions and cookies is that a session can hold multiple
variables, and you need not have to set cookies for every variable. By default, the session
data is stored in the cookie which has an expiry date of zero, which means that the session
remains active only as long as the browser. Once you close the browser, all the stored
information is lost. This behavior can be modified by changing the “session. cookie_lifetime”
setting in “php.ini” from zero to whatever you want the cookie lifetime to be.

The Role Of MySQL DataBase
we can summarize the process of accessing and working with a database connection from
within a PHP script in the following steps.
• First you need to establish a connection to the database server.
• You should have to validate any user input
• Then select the database on the server to use.
• Execute all the desired query against the database.
• Further retrieve and process the results.
• Then create HTML or perform actions based on results.
• Finally close the database connection.