Transcript PHP_Part1
ITCS373: Internet Technology
Server-Side Programming
PHP – Part 1
Dr. Faisal Al-Qaed
Introduction to Server Side
Programming
Web Server
Web server respond to client requests (typically from a
Web browser) by providing resources, such as
HTML/XHTML documents.
Web server and clients communicate with each other via
the platform independent Hypertext Transfer Protocol
(HTTP).
For example, when users enter a URL address such as
http://www.w3schools.com/index.htm into a webbrowser, they are requesting index.htm document from a
web server. The web server maps the URL to a resource
on the server and returns the requested resource to the
client using HTTP.
Popular Web Servers
IIS (Internet Information Services) 5.0/6.0 is an
enterprise-level web server that is included with
several versions of Windows. It runs on
Windows platforms and it is part of Windows OS
(XP, Windows Server 2003) – (Not Free).
The Apache web server, maintained by the
Apache software foundation, is the most popular
web server in use today and runs on many
platforms (Unix-, Mac-, Windows- based
platforms) – (it is open source and Freeware).
Client-Side (CS) Scripting
CS scripting validates user input, accesses the browser and
enhances web-pages with DHTML, ActiveX controls, and
Java Applets.
CS validation reduces the number of requests that needed to
be passed to the server. Performance Tip: to conserve
server resources and minimize internet traffic and delays,
perform as much processing as possible on the client side.
Interactivity allows users to make decisions, click buttons,
play games, and so on – making the website experience more
interesting.
However, CS does have limitations, such as browser
dependency, the browser or scripting host must support the
scripting language.
Another issue is that CS scripts are viewable to the client (e.g.
by using the view source option in IE browser). Some web
developers do not advocate this because users potentially
can view their code. Therefore, sensitive information such as
passwords or other personally identifiable data should not be
stored or validated on the client.
Server-Side (SS) Scripting
Programmers have greater flexibility when using SS scripts.
SS scripts executed on the server often generate custom
responses for clients. For example, a client might connect to
an airline’s web server and request a list of all flights from
Bahrain to Scotland between May 19th and July 5th. The
server queries the database, dynamically generates HTML
content containing the flight list and sends the HTML
document to the client.
SS scripting languages have a wider range of programmatic
capabilities than CS equivalents. For example, SS scripts
often can access the server’s file directory structure, whereas
CS scripts cannot.
SS scripts also have access to the SS software that extends
the server functionality such as counting the number of web
page hits, server log files, etc.
You can place two types of files on the
server.
1. HTML files, XHTML or XML all of which
display their code at the client system.
2. Server Side scripts like PHP, ASP, etc.
where the output of these scripts are
displayed on the clients system.
Server Side Programming Concept
HTTP Request Types
The most common HTTP request types are GET and
POST.
An HTTP request often posts data to a SS form handler
(program) that processes the data. GET and POST
requests can both used to send form data to a web
server, yet each type sends the information differently.
A GET request sends information to the server as part of
the URL (e.g. www.searchengine.com/search?name=value), where search is the
name of a SS form handler, name is the name of the
HTML form element and value is the value assigned to
that variable. Note a ? Separate the query string from the
rest of the URL.
GET Method Submissions
The contents of a form are concatenated with the action URL.
Name / value pairs are separated by ‘&’;
Each name is separated from its value by a ‘=’;
Spaces are replaced by plus signs ‘+’.
Based on these rules, the appropriate input string is formed. You may
see this string in the URL window of your browser after submitting a
form and entering the requested HTML page.
http://www.altavista.com/search.cgi?topic=computing&keywords
=agents+software+papers&lang=en-gb
POST Method Submissions
The post method sends form data as an HTTP message, not as part of
the URL. Because a GET request limits the query string (i.e.
everything to the right of the ?) to 2048 characters, it is often
necessary to send large pieces of information using the POST method.
The POST method is also sometimes preferred because it hides the
submitted data from the user by embedding it in HTTP message. The
form data still reaches the server and is processed in a similar fashion
to a GET request, but the user does not see the exact information
sent.
As a result, large pieces of information or sensitive form data such as
passwords, are usually sent using the POST method.
Accessing Web Servers
To request documents from web servers, users must
know the machine names (called host names) on which
the web server software reside. User can request
documents from local web servers (i.e. ones residing on
users’ machines) or remote web servers (i.e. ones
residing on different machines).
Local web server can be accessed in two ways:
Through machine name (computer name)
Through localhost – a host name that references the local
machine, or through local IP (127.0.0.1)
A remote web server can be accessed by the domain
name that is registered with ISP (Internet Service
Provider) or IP address of the remote machine.
Popular Server-Side Scripts:
ASP/ASP.NET
Microsoft ASP stands for Active Server Pages. The
classic ASP is interpreted by IIS where ASP.net is a
compiled .NET programming platform.
ASP.NET takes the advantage of Microsoft .NET
framework, which provides a thousands of classes.
IIS can serve ASP.net documents, although the Apache
web server support older versions of ASP (if additional
modules are installed), it does not support ASP.net
This means that ASP.net can be only executed using IIS
on Windows platform only.
The classic ASP file extension is .asp where ASP.net file
is .aspx
Popular Server-Side Scripts: Perl/CGI
Perl (Practical Extraction and Report Language) is the
most widely used language for web programming, known
for its power with text-processing capabilities. – Perl
script needs interpreter program to be executed.
CGI (Common Gateway Interface): is a standard
protocol through which applications interact with web
servers. Because CGI is an interface, it cannot be
programmed directly, a script like Perl must be executed
to interact with it. CGI add the necessary interface for
Perl program to extract data from HTML form and
cookies. Perl is arguably the most popular CGI program.
IIS and Apache web server can both serve Perl
generated documents. But of course you will need to
install Perl interpreter
Perl file extension is .pl or .cgi.
Popular Server-Side Scripts: Java
Servlet/JSP
Java Servlet/JSP (Java Active Pages) developed by Sun Microsystems.
Java provides a number of built-in networking capabilities that make it easy
to develop Internet-based and Web-based applications.
A Servlet extends the functionality of a server, such as a Web server.
Packages javax.servlet and javax.servlet.http provide the classes and
interfaces to define servlets. Packages javax.servlet.jsp and
javax.servlet.jsp.tagext provide the classes and interfaces that extend the
Servlet capabilities for JSPs.
Using special syntax, JSP allows Web-page implementers to create pages
that use encapsulated Java functionality and even to write scriptlets of
actual Java code directly in the page.
Note that Servlet is a compiled java technology where JSP is a script that
need an interpreter program to be executed. In fact, JSP file is converted
into Servlet program on runtime before execution.
The servlet and JSP are part of the Jakarta Project is called Tomcat server.
Tomcat is based on Apache web server. It contains the official reference
implementation of the JSP and servlet standards.
JSP file extension is .jsp, where Servlet file extension is .java (before
compilation) and . Class (after compilation).
Popular Server-Side Scripts: Python
Python is an interpreted, cross-platform, object-oriented
language that can be used to write large-scale Internet
search engines, small administration scripts, GUI
applications, CGI scripts and more.
Python is a freely distributed technology whose opensource nature has encouraged a wide base of
developers to submit modules that extend the language.
Python’s interpreted nature facilitates rapid application
development (RAD) of powerful programs. GUI
applications, in particular, can be developed and tested
quickly using Python’s interface to Tcl/Tk (among other
GUI toolkits).
ActivePython is the industry-standard distribution of
Python for Windows, Solaris and Linux platforms.
Python file extension is .py
Popular Server-Side Scripts: PHP
PHP (Hypertext Preprocessor), is quickly becoming one
of the most popular SS scripting languages for creating
dynamic web pages.
PHP is an open source technology that is supported by a
large community of users and developers.
Of PHP’s many strength as a SS language, perhaps the
greatest lies in its ability to dynamically change its HTML
output in reactions to user input.
PHP is platform independent; implementations exist for
all major Unix, Linux and Windows OSs. PHP script
needs interpreter program to be executed.
PHP also supports a large number of databases,
including MySQL, Informix, Oracle, Sybase, Solid,
PostgreSQL, Generic ODBC, etc.
PHP file extension is .php
Other Server-Side Languages
Macromedia ColdFusion MX (it is not free):
It is a programming language based on standard HTML that is used to write
dynamic web-pages. ColdFusion pages consist of standard HTML tags such as
<FONT SIZE=.+2.>, together with CFML (ColdFusion Markup Language) tags
such as <CFQUERY>, <CFIF> and <CFLOOP>.
It supports most operating systems including Windows, Unix, Linux, IBM AIX
and HP-UX
ColdFusion file extension is .cfm
Ruby
Ruby is a dynamic, reflective, general purpose object-oriented programming
language that combines syntax inspired by Perl with Smalltalk-like features.
It is open source programming language with a focus on simplicity and
productivity. It has an elegant syntax that is natural to read and easy to write.
In Ruby, Everything, including a literal, is an object, so this works:
"ruby is cool".length
#output = 12
Ruby file extension is .rb
It supports most operating systems including Windows, Unix, Linux, and Mac
Server Side Programming Using
PHP
PHP: Hypertext PreProcessor
PreProcessor means it processes what
will appear as Hypertext before the
hypertext appears on the screen.
This means it will allow you to do
programming, loops, database search,
before the script generates the HTML that
will appear on the screen.
Why PHP?
PHP runs on different platforms (Windows,
Linux, Unix, etc.)
PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
PHP is FREE to download from the official PHP
resource: www.php.net
PHP is easy to learn and runs efficiently on the
server side.
PHP is an open source technology that is
supported by a large community of users and
developers (so it will not die soon).
How Does it work?
The server has an interpreter (a program)
that takes the script you write as input, and
it executes all the commands that are
enclosed in the script type tags. For php
these are <?php ?>
Executing may display data, or perform
comparisons, or loops. It may also access
a database, to search for values and
display the results on the screen.
What do you need to run PHP?
You will need three components to work with
PHP server side scripting;
Apache web server
PHP interpreter program
MySql database
However, to make your lives easier, there is such a
thing as a “kit”. All you have to do is to get an
AppServ kit (ver. 2.5.10 for Windows) and install
it. It will install all the three components for you
without the need for doing any configurations.
The Directory to use:
Once you have installed the kit you must find out
what folder to place all your files in (i.e.
C:\AppServ\www\)
You can open an browser window and type the
word localhost (or type in 127.0.0.1) and that
will open the default page that came with the kit.
Remember that the default page always has the
name index so it is either index.htm or
index.html or index.php.
Good PHP Tutorials for Beginner
Check out these websites:
http://www.tizag.com/
http://www.w3schools.com/
Your First Script
You can use HTML Kit or Notepad if you wish and write a
script that has php code in it, then save it as the
filename.php
<html> <body>
<?php
echo "Hello World";
?>
</body> </html>
There are two basic statements to output text with PHP:
echo and print. In the example above we have used the
echo statement to output the text "Hello World".
Note:
You cannot view the PHP source code
by selecting "View source" in the
browser - you will only see the output
from the PHP file, which is plain HTML.
This is because the scripts are
executed on the server before the
result is sent back to the browser.
Comments in PHP
<html> <body>
<?php
//This is a comment
/* This is a comment
block */
?>
</body> </html>
Variables in PHP
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.
<?php
$txt = "Hello World!";
$number = 16;
echo $txt;
print $number;
?>
PHP is a Loosely Typed Language
In PHP a 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 PHP the variable is declared automatically when you
use it.
Variable Naming Rules
A variable name must start with a letter or an
underscore "_"
A variable name can only contain alpha-numeric
characters and underscores (a-z, A-Z, 0-9, and _ )
A variable name should not contain spaces. If a variable
name is more than one word, it should be separated
with underscore ($my_string), or with capitalization
($myString)
Another Example
To concatenate two or more variables together, use the
dot (.) operator
The strlen() function is used to find the length of a string.
<html> <body>
<?php
$txt1="Hello World";
$txt2="1234";
echo ($txt1." ".$txt2); //output: Hello World 1234
echo ("<BR />".strlen("Hello world!")); //output: 12
echo ("<br />$txt1 $txt2"); //will also work in PHP
?>
</body> </html>
PHP Operators
PHP operators are similar to C Operators
(i.e. +, -, ==, !=, ++, --, %)
See:
http://www.w3schools.com/php/php_operato
rs.asp
If Statement
<html> <body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body> </html>
Switch Statement
<html> <body>
<?php
switch ($x) {
case 1: echo "Number 1"; break;
case 2: echo "Number 2"; break;
case 3: echo "Number 3"; break;
default: echo "No number between 1 and 3"; } ?>
</body> </html>
PHP Looping
while (condition)
code to be executed;
do {
code to be executed; }
while (condition);
for (initialization; condition; increment) {
code to be executed; }
PHP Arrays
There are three different kind of arrays:
Numeric array - An array with a numeric ID key
Associative array - An array where each ID
key is associated with a value
Multidimensional array - An array containing
one or more arrays
Numeric Arrays
Create an array:
$names = array("Peter","Quagmire","Joe");
OR use this way:
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[] = "Joe"; //will automatically use the next index
echo $names[1] . " and " . $names[2] . " are ".
$names[0] . "'s neighbors"; ?>
echo count($names); //output 3
Associative array
An associative array, each ID key is associated with a
value.
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old <br /> ";
for( reset($ages); $elem=key($ages); next($ages))
print (“$elem is $ages[$elem] <br />”);
?>
reset function set the pointer to the 1st element
Key function will return the current key index
Next function will move the pointer to next element
The loop will continue as long as the key returns an
index
Note: unset($ages[‘Joe’]); will delete the element
Multidimensional Arrays
$families = array (
"Griffin"=>array ( "Peter", "Lois", "Megan" ),
"Quagmire"=>array ( "Glenn" ),
"Brown"=>array ( "Cleveland", "Loretta", "Junior" )
);
echo "Is " . $families['Griffin'][2] . " a part of the
Griffin family?";
//Is Megan a part of the Griffin family?
//you can use $families[0][2] instead
The foreach Statement
foreach (array as value) {
code to be executed; }
Example:
<html> <body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value)
{ echo "Value: " . $value . "<br />"; } ?>
</body> </html>
The foreach with Associative Arrays
<html> <body>
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
foreach ($ages as $key =>$value)
{ echo $key. “=".$value . "<br />"; } ?>
</body> </html>
PHP Functions
Creating PHP functions:
All functions start with the word "function()"
Name the function - It should be possible to understand
what the function does by its name. The name can start
with a letter or underscore (not a number)
Add a "{" - The function code starts after the opening
curly brace
Insert the function code
Add a "}" - The function is finished by a closing curly
brace
Note: PHP function names are not case sensitive
Example
<html> <body>
<?php
function add($x,$y) {
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body> </html>
PHP Functions
The real power of PHP comes from its
functions library.
In PHP - there are more than 700
functions available.
See:
http://www.w3schools.com/php/php_func
tions.asp
Example: Header function
<?php
//Redirect browser
header("Location: http://www.w3schools.com/");
?>
Note: header function must be used before any
output including space character in the php
file
Disable Caching Using Headers
<?php
//to disable caching use this
header("Cache-Control: no-cache, mustrevalidate"); // HTTP/1.1
//Or
header("Expires: Mon, 26 Jul 2008 05:00:00
GMT"); // Date in the past
?>
PHP Server Variables
<?php
echo "Referer: " .
$_SERVER["HTTP_REFERER"] . "<br />";
echo "Browser: " .
$_SERVER["HTTP_USER_AGENT"] . "<br />";
echo "User's IP address: " .
$_SERVER["REMOTE_ADDR"]; ?>
IP Split Example
<?php
//to disable caching use this
header("Cache-Control: no-cache, must-revalidate"); ?>
<html> <body>
<?php
$myIP=$_SERVER["REMOTE_ADDR"];
$arr=split("\.", $myIP); //explode(“\.", $myIP) is equivalent
echo ($myIP."<br />");
foreach ($arr as $value)
echo ("IP Portion: " . $value . "<br />");
?>
</body> </html>
PHP Variable Scope
PHP Variable Scope
Using $GLOBALS Associative Array:
Using global keyword
Using static keyword =>
PHP Form Handling
<html> <body>
<form action="welcome.php" method="POST">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form></body> </html>
Welcome.php
<html> <body>
Welcome
<?php echo $_POST["name"]; ?>. <br />
You are <?php echo $_POST["age"]; ?>
years old!
</body> </html>
Output
Welcome John.
You are 28 years old!
Note: If the method attribute of the form is
GET, then the form information will be set
in $_GET instead of $_POST.
The $_REQUEST Variable
The PHP $_REQUEST variable contains the contents of
both $_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the
result from form data sent with both the GET and POST
methods.
Example
Welcome <?php
echo $_REQUEST["name"]; ?>.<br />
You are <?php echo $_REQUEST["age"]; ?> years old!
Form Validation
User input should be validated whenever possible. Client
side validation is faster, and will reduce server load.
However, any site that gets enough traffic to worry about
server resources, may also need to worry about site
security. You should always use server side validation if
the form accesses a database.
A good way to validate a form on the server is to post the
form to itself, instead of jumping to a different page. The
user will then get the error messages on the same page
as the form. This makes it easier to discover the error.
PHP Include and Require
PHP Include: you can save yourself a great deal of time with the
use of the PHP include command. include takes a file name and
simply inserts that file's contents into the script that issued the
include command.
PHP Require: Just like Include command, the require command is
used to include a file into your PHP code. However there is one
huge difference between the two commands, though it might not
seem that big of a deal.
Include versus Require: When you include a file with the include
statement and PHP cannot find it you will see an error message like
“Warning: main(noFileExistsHere.php): failed to open stream:
No such file or directory “ and the remaining php script will be
executed because a Warning does not prevent our PHP script from
running. On the other hand, if you used the require statement we
would get the same warning message but with fatal error and the
remaining php script will not be executed.
PHP Include Example
Note: to use require instead,
replace include with
require(“menu.php”);
The Date() Function
The Date() Function
The date() function is used to format a time or a
date.
Syntax
string date (date_format[,int timestamp])
This function returns a string formatted according
to the specified format.
A timestamp is the number of seconds from
January 1, 1970 at 00:00
Date Examples
This example uses the mktime function to create a timestamp for tomorrow.
To go one day in the future we simply add one to the day argument of mktime.
For your future reference, we have the arguments of mktime.
Note: These arguments are all optional. If you do not supply any arguments
the current time will be used to create the timestamp.
mktime(hour, minute, second, month, day, year, daylight savings time)
Date Function: Time Reference
For Full date reference, visit:
http://www.tizag.com/phpT/phpdate.php
Example: Dynamic Content
noCache.php
<?php
//Note we will use this file for disable caching
//in all php examples
//you need to save this file with your PHP scripts
header("Cache-Control: no-cache, mustrevalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 2008 05:00:00
GMT"); // Date in the past
?>
Form.php
<?php
require("noCache.php");
?>
<html><body>Enter Your Details:
<form action="processData.php" method="post">
Name: <input name="name" /> <br />
Surname: <input name="sname"/> <br />
Occupation Description: <textarea
name="descr"></textarea><br />
Gender: Male<input type="radio" name="gender" value="M"
checked/>
Female<input type="radio" name="gender" value="F"/><br />
<input type="submit" name="T" value="Tabular"/>
<input type="submit" name="L" value="List"/>
</form></body></html>
processData.php
<?php
require("noCache.php");
?>
<html><body>
<?php
extract($_POST); //Built-in function that will extract form elements to PHP
variables
if ( !$name || !$sname || !$descr){
echo ("Information missing");
die(); // terminate script execution
}
else if (isset($T)) //used to check which submit button was used
{
displayTable($name,$sname,$descr,$gender);
}
else if (isset($L))
{
displayList($name,$sname,$descr,$gender);
}
?>
<center>Thank You</center></body></html>
Continued: processData.php
<?php
function displayTable($name,$sname,$descr,$gender)
{
echo("<center><table border='4'>\n");
echo ("<tr bgcolor='yellow'>
<th>Name</th><th>Surname</th><th>Gender</th><th>Description</th></tr>");
echo ("<tr bgcolor='blue'>
<td>$name</td><td>$sname</td><td>$gender</td><td>$descr</td></tr>");
echo ("</table></center>\n");
}
function displayList($name,$sname,$descr,$gender)
{
echo("Your Details: <ul>\n");
echo ("<li>Name: $name</li><li>Surname: $sname</li><li>Gender:
$gender</li><li>Description: $descr</li>");
echo ("</ul>\n");
}
?>
Example: Dynamic Table Creation
Form.php
<?php
require("noCache.php");
?>
<html><body>
Enter Table Size:
<form action="displayTable.php" method="post">
Rows: <input name="rows" /> <br />
Columns: <input name="cols"/> <br />
<input type="submit" value="Create Table"/>
</form></body></html>
displayTable.php
<?php
require("noCache.php");
?>
<html><body>
<?php extract($_POST); //it will extract all form elements to PHP variables
if ( !$rows || !$cols) { echo ("Table Info Missing"); die();}
else
{
settype($rows,"integer"); //data-type conversion function (integer, double, string)
settype($cols,"integer");
if ($rows>0 && $cols>0)
displayTable($rows,$cols);
else
{ echo ("Invalid Table Size"); die(); }
}
?>
<center>Your Table Size is <?php echo "$rows x $cols";
?></center></body></html>
Continued: displayTable.php
<?php
function displayTable($rows,$cols)
{
echo("<center><table border='4'>\n");
for ($r=1;$r<=$rows; ++$r)
{
echo ("<tr>");
for ($c=1;$c<=$cols; ++$c)
echo ("<td>$r:$c</td>");
echo ("</tr>");
}
echo ("</table>\n");
} ?>
Form Example with $PHP_SELF
<html><body>
<?php
extract($_POST);
if (!isset($submit)) { // if page is not submitted to itself echo the form
?>
<form method="post" action="<?php echo $PHP_SELF;?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
Gender:<br />Male:<input type="radio" value="Male" name="gender"><br />
Female:<input type="radio" value="Female" name="gender"><br />
Please choose type of residence:<br />
Steak:<input type="checkbox" value="Steak" name="food[]"><br />
Pizza:<input type="checkbox" value="Pizza" name="food[]"><br />
Chicken:<input type="checkbox" value="Chicken" name="food[]"><br />
<textarea rows="5" cols="20" name="quote">Enter your favorite
quote!</textarea><br />
Select a Level of Education:<br />
<select name="education">
<option value="Jr.High">Jr.High</option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option></select><br />
Select your favorite time of day:<br />
<select name="TofD" size="3">
<option value="Morning">Morning</option>
<option value="Day">Day</option>
<option value="Night">Night</option></select><br />
<input type="submit" value="submit" name="submit"></form>
<?php
} else {
echo "Hello, ".$Fname." ".$Lname.".<br />";
echo "You are ".$gender.", and you like: <br /> ";
foreach ($food as $f) {
echo $f."<br />";
}
echo "<i>".$quote."</i><br />";
echo "You're favorite time is ".$TofD.", and you passed
".$education."!<br />";
}
?>
</body></html>
Reading Cookie:
Cookies
Creating Cookie:
<?php
$inTwoMonths = 60 * 60 * 24 * 30
* 2 + time();
setcookie("lastVisit", "my site
is wonderful",
$inTwoMonths);
?>
<?php
if(isset($_COOKIE['lastVisit'])){
$visit = $_COOKIE['lastVisit'];
echo "The contents of your
cookie are - ". $visit;}
else
echo "You've got out of date
cookie!";
?>
Deleting a Cookie
<?php
Note: time() return the current
time in seconds
// set the expiration date to one hour
ago
setcookie(“lastVisit", "", time()-3600);
?>
Session
A PHP session variable is used to store information about, or change
settings for a user session. Session variables hold information about
one single user, and are available to all pages in one application.
When you are working with an application, you open it, do some
changes and then you close it. This is much like a Session. The
computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web
server does not know who you are and what you do because the HTTP
address doesn't maintain state.
A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping items,
etc). However, session information is temporary and will be deleted
after the user has left the website. If you need a permanent storage
you may want to store the data in a database or file.
Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.
Sessions
<?php
session_start();
//store session data
$_SESSION['views'] = 1;
//retrieve data
echo "Pageviews = ".
$_SESSION['views'];?>
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] =
$_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
echo "views = ". $_SESSION['views'];
?>
<?php
//destroy Session views
unset($_SESSION['views']);
<br><br>
<a href="conf.php">Click
here</a>
//Destroy All Sessions
session_destroy();
?>
Note: The session_start() function must appear BEFORE the <html> tag:
Tip: a good use of session is to check whether the user had login or not, if not,
redirect the user to the login page.
What if a Browser Does NOT
Support Cookies/Sessions?
If your application deals with browsers that
do not support cookies/sessions, you will
have to use other methods to pass
information from one page to another in
your application. There are two ways of
doing this:
1. Add parameters to a URL
You can add parameters to a URL:
<a href="welcome.php?fname=John&lname=Smith"> Go
to Welcome Page</a>
And retrieve the values in the "welcome.php" file like
this:
<?php
$fname= $_GET["fname“];
$lname=$_GET[“lname“];
echo ("<p>Hello $fname $lname !</p>");
?>
2. Use a form
You can use a form. The form passes the user input to
"welcome.php" when the user clicks on the Submit
button.
You can use invisible form element called hidden as
follow:
<input type=“hidden” name=“username” value=“fa” />
or
<input type=‘hidden’ name=‘username’ value=‘<?php
echo ($un); ?>’ />
Retrieve the values in the "welcome.php" file like this:
$un=$_POST(“username");
$un=$_GET(“username"); //depending on the form
method used
PHP Files
Manipulating files is a basic necessity for serious
programmers and PHP gives you a great deal of
tools for creating, reading, and editing files.
Create/Open/Close
$myFile = "testFile.txt";
$myFileHandle = fopen($myFile, 'w') or die("can't
open file");
fclose($myFileHandle);
File Write
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
Note: if you open the file again with ‘w’ mode, it will
overwrite the old data
File Read
$myFile = "testFile.txt";
$fh = fopen($myFile, ‘r') or die("can't open
file");
$theData = fread($fh, 5); //it’ll read 5 bytes
fclose($fh);
echo $theData;
File Read: reading all data in a file
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
Note: filesize will return returns the length of a file,
in bytes
File Read by line
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
Note: fegets read the file by line. Use this function
if you had separated your data with new lines.
Reading a File Line by Line
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//The feof() checks if the "end-of-file" (EOF) has been reached
while(!feof($file)) {
echo fgets($file). "<br />";
}
fclose($file);
?>
Note that you can use split or explode the function to read
each string in the line separately
Reading a File Character by Character
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
echo fgetc($file);
fclose($file);
?>
The fgetc() function is used to read a single
character from a file.
Read file using fscanf Function
<?php
require("noCache.php");
$handle = fopen("C:\AppServ\users.txt", "r");
while (!feof($handle))
{
list ($name, $prof, $cc) =fscanf($handle, "%s\t%s\t%d\n");
echo "Hi $name, $prof, country code is $cc. <br />";
}
fclose($handle);
?>
Note: DON’T Store your files in the Server path (i.e. WWW) because if
so, it can be downloaded by any user.
You can use the following for reading using fscanf (%c (char), %d (int),
%f (float), %s (string)).
Browser Output
Hi Noof, Student, country code is 971.
Hi Ali, Manager, country code is 44.
Hi Ameena, Secertary, country code is 973.
Hi Mike, Supervisor, country code is 44.
The content of the file users.txt as follows:
File Write using fprintf
<?php
$str = "Hello";
$number = 123;
$file = fopen("test.txt","w");
echo fprintf($file,"%s world. Day number
%d",$str,$number);
?>
Fseek function
fseek($fh,0);
//jump to the beginning of a file
fseek($fh, 1024);
//jump to byte 1024 from the beginning
fseek($fh, 100, SEEK_CUR);
//jump ahead 100 bytes from your current position
fseek($fh, -100, SEEK_CUR);
//jump back 100 bytes from your current position
fseek($fh, -100, SEEK_END);
//jump back 100 bytes before the end of the file
File Append to end of File
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);
The above example may not seem very useful, but appending data onto a file is
actually used everyday. Almost all web servers have a log of some sort. These
various logs keep track of all kinds of information, such as: errors, visitors, and
even files that are installed on the machine.
A log is basically used to document events that occur over a period of time,
rather than all at once. Logs: a perfect use for append!
File Delete/Truncate
Delete a file
$myFile = "testFile.txt";
unlink($myFile); //will delete the file
//make sure you delete the write file
Truncate a file (deleting all information in the
file)
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fclose($fh);
Reading
Read the Book Chapter on PHP
Use PHP handout in the Yahoo Group as
reference