PHP Mod 3 &4
PHP Mod 3 &4
PHP
a. INTRODUCTION TO PHP
• Getting started
PHP is a powerful tool for making dynamic and interactive Web pages.
PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
• Basic Syntax
A PHP script always starts with <?php and ends with ?>. A PHP script can be placed anywhere in
the document.
On servers with shorthand-support, you can start a PHP script with <? and end with ?>.
For maximum compatibility, we recommend that you use the standard form (<?php) rather than the
shorthand form.
<?php
?>
A PHP file must have a .php extension.
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP script that sends the text "Hello World" back to the
browser:
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print.
• Advantages
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
Download PHP
Download PHP for free here: http://www.php.net/downloads.php
• Data types
As with algebra, PHP variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carName.
• Variables in PHP starts with a $ sign, followed by the name of the variable
• The variable name must begin with a letter or the underscore character
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _
)
• A variable name should not contain spaces
• Variable names are case sensitive (y and Y are two different variables)
• Variable scope
The scope of a variable is the part of the script where the variable can be referenced/used.
• local
• global
• static
• parameter
Local Scope
A variable declared within a PHP function is local and can only be accessed within that function:
Example
<?php
$x=5; // global scope
function myTest()
{
echo $x; // local scope
}
myTest();
?>
The script above will not produce any output because the echo statement refers to the local scope
variable $x, which has not been assigned a value within this scope.
You can have local variables with the same name in different functions, because local variables are
only recognized by the function in which they are declared.
Global Scope
A variable that is defined outside of any function, has a global scope.
Global variables can be accessed from any part of the script, EXCEPT from within a function.
To access a global variable from within a function, use the global keyword:
Example
<?php
$x=5; // global scope
$y=10; // global scope
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name
of the variable. This array is also accessible from within functions and can be used to update global
variables directly.
Example
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y;
?>
Static Scope
When a function is completed, all of its variables are normally deleted. However, sometimes you
want a local variable to not be deleted.
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained from
the last time the function was called.
Parameter Scope
A parameter is a local variable whose value is passed to the function by the calling code.
Example
<?php
function myTest($x)
{
echo $x;
}
myTest(5);
?>
Note: When you assign a text value to a variable, put quotes around the value.
• Constants
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change
during the execution of the script (except for magic constants, which aren't actually constants). A
constant is case-sensitive by default. By convention, constant identifiers are always uppercase.
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with
a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Example:-
<?php
?>
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255
(0x7f-0xff).
• Comments in php
In PHP, we use // to make a one-line comment or /* and */ to make a comment block:
For example:-
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
c. PHP OPERATORS
• Type of operators
The assignment operator = is used to assign values to variables in PHP.
The arithmetic operator + is used to add values together in PHP.
x=y x=y The left operand gets set to the value of the expression on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
a .= b a=a.b Concatenate two strings
true
x=6
True if either or both x and y are
x or y Or y=3
true
(x==6 or y==5) returns true
x=6
True if either x or y is true, but not
x xor y Xor y=3
both
(x==6 xor y==3) returns false
x=6
y=3
x && y And True if both x and y are true
(x < 10 && y > 1) returns
true
x=6
True if either or both x and y are
x || y Or y=3
true
(x==5 || y==5) returns false
x=6
!x Not True if x is not true y=3
!(x==y) returns true
• Miscellaneous operators
Installation
The misc functions are part of the PHP core. There is no installation needed to use these functions.
Runtime Configuration
The behavior of the misc functions is affected by settings in the php.ini file.
• If …else
If
The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time is less than 20:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>
If….else
Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have a
good night!" otherwise:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
• Switch
The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated
once. The value of the expression is then compared with the values for each case in the structure. If
there is a match, the block of code associated with that case is executed. Use break to prevent the
code from running into the next case automatically. The default statement is used if no match is
found.
Example
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
e. FLOW CONTROL
• While
The while loop executes a block of code while a condition is true.
Syntax
while (condition)
{
code to be executed;
}
Example
The example below first sets a variable i to 1 ($i=1;).
Then, the while loop will continue to run as long as i is less than, or equal to 5. i will increase by 1
each time the loop runs:
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br>";
$i++;
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
• do while
The do...while statement will always execute the block of code once, it will then check the condition,
and repeat the loop while the condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
The example below first sets a variable i to 1 ($i=1;).
Then, it starts the do...while loop. The loop will increment the variable i with 1, and then write some
output. Then the condition is checked (is i less than, or equal to 5), and the loop will continue to run
as long as i is less than, or equal to 5:
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>
</body>
</html>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
• for
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init; condition; increment)
{
code to be executed;
}
Parameters:
• init: Mostly used to set a counter (but can be any code to be executed once at the beginning
of the loop)
• condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
• increment: Mostly used to increment a counter (but can be any code to be executed at the end
of the iteration)
Note: The init and increment parameters above can be empty or have multiple expressions
(separated by commas).
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as the
variable i is less than, or equal to 5. The variable i will increase by 1 each time the loop runs:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br>";
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
• foreach
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>
</body>
</html>
Output:
one
two
three
f. FUNCTIONS
• Structure
A function will be executed by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
PHP function guidelines:
• Give the function a name that reflects what the function does
• The function name can start with a letter or underscore (not a number)
Example
A simple function that writes my name when it is called:
<html>
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
</body>
</html>
Output:
My name is Kai Jim Refsnes
• Arguments
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.
Example 1
The following example will write different first names, but equal last name:
<html>
<body>
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br>";
}
writeName("Stale");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.
Example 2
The following function has two parameters:
<html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br>";
}
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Ståle Refsnes?
• Returning values
To let a function return a value, use the return statement.
Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
</body>
</html>
Output:
1 + 16 = 17
• Recursion
A recursive function is a function that calls itself
Calculating factorials is a commonly cited example - the factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1, or
720, and is usually represented as 6! So, given that factorial 6 (6!) is 720, what is factorial 7, and
how does it relate to 6!? Well, clearly 7! is 7 * 6! - once you calculate 6!, it is simply a matter of
multiplying the result by 7 to get 7!
This equation can be represented like this: n! = n * ((n - 1)!) That is, the factorial for any given
number is equal to that number multiplied by the factorial of the number one lower - this is clearly a
case for recursive functions!
So, what we need is a function that will accept an integer, and, if that integer is not 0, will call the
function again, this time passing in the same number it accepted minus 1, then multiply that result by
itself. If it is sounding hard, then you are in for a surprise: the function to calculate factorials is made
up of only two lines of code. Here is a working script to calculate factorials:
<?php
function factorial($number) {
if ($number == 0) return 1;
return $number * factorial($number - 1);
}
print factorial(6);
?>
That will output 720, although you can easily edit the factorial() function call to pass in 20 rather
than 6, for example. Note that factorials increase in value very quickly (7! is 5040, 8! is 40320, etc),
and so you will eventually hit a processing limit - not time, but merely recursive complexity; PHP
will only allow you to have a certain level of recursion
• Built in functions
g. ARRAYS
• Array structure
An array stores multiple values in one single variable:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could
look like this:
$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not
3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an
index number.
In PHP, the array() function is used to create an array:
array();
• Type of array
In PHP, there are three types of arrays:
• Indexed arrays - Arrays with numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
Indexed arrays
There are two ways to create indexed arrays:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
• Multidimensional array
A multidimensional array is an array containing one or more arrays.
In a multidimensional array, each element in the main array can also be an array. And each element
in the sub-array can be an array, and so on.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
Example 2
Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";
The code above will output:
Is Megan a part of the Griffin family?
• Array sorting
The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.
Example
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>
The following example sorts the elements of the $numbers array in ascending numerical order:
Example
<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
?>
Example
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
The following example sorts the elements of the $numbers array in descending numerical order:
Example
<?php
$numbers=array(4,6,2,22,11);
rsort($numbers);
?>
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
?>
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>
• Oops concept
Object Oriented Programming (OOP) is a programming concept that treats functions and data as
objects
• Object: An individual instance of the data structure defined by a class. You define a class once
and then make many objects that belong to it. Objects are also known as instance.
• The special form class, followed by the name of the class that you want to define.
• A set of braces enclosing any number of variable declarations and function definitions.
• Variable declarations start with the special form var, which is followed by a conventional $
variable name; they may also have an initial assignment to a constant value.
• Function definitions look much like standalone PHP functions but are local to the class and
will be used to set and access object data.
Example:
Here is an example which defines a class of Books type:
<?php
class Books{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $var;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.
PHP provides a special function called __construct() to define a constructor. You can pass as many
as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and title for
the book at the time of object creation.
Now we don't need to call set function separately to set price and title. We can initialize these two
member variables at the time of object creation only. Check following example below:
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Destructor:
Like a constructor function you can define a destructor function using function __destruct(). You
can release all the resourceses with-in a destructor.
• Inheritance
PHP class definitions can optionally inherit from a parent class definition by using the extends
clause. The syntax is as follows:
class Child extends Parent {
<definition body>
}
The effect of inheritance is that the child class (or subclass or derived class) has the following
characteristics:
• Automatically has all the member variable declarations of the parent class.
• Automatically has all the same member functions as the parent, which (by default) will work
the same way as those functions do in the parent.
Following example inherit Books class and adds more functionality based on the requirement.
class Novel extends Books{
var publisher;
function setPublisher($par){
$this->publisher = $par;
}
function getPublisher(){
echo $this->publisher. "<br />";
}
}
Now apart from inherited functions, class Novel keeps two additional member functions.
i. COOKIES
• Setting
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.
• Accessing
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
setcookie(name, value, expire, path, domain);
Example 1
In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it.
We also specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
Example 2
You can also set the expiration time of the cookie in another way. It may be easier than using
seconds.
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).
In the example below, we retrieve the value of the cookie named "user" and display it on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br>";
else
echo "Welcome guest!<br>";
?>
</body>
</html>
• Destroying
When deleting a cookie you should assure that the expiration date is in the past.
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
• Uses of cookie
To store username/password information so that the user doesn't have to log in every time they visit
the website ("remember me" sign ins).
To simply remember the user's name.
To keep track of a user's progress during a specified process.
To remember a user's theme.
• Limitations
Cookies aren't always enabled in all browsers
Cookie is hackable
j. SESSIONS
• session id
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.
• predefined PHP session variables
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.
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.
Note: The session_start() function must appear BEFORE the <html> tag:
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too.
A 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.
Cookies can be set to a long lifespan, which means that data stored in a cookie can be stored for
months if not years. Cookies, having their data stored on the client, work smoothly when you have a
cluster of web servers, whereas sessions are stored on the server, meaning in one of your web servers
handles the first request, the other web servers in your cluster will not have the stored information.
Sessions are stored on the server, which means clients do not have access to the information you
store about them - this is particularly important if you store shopping baskets or other information
you do not want you visitors to be able to edit by hand by hacking their cookies.
Session data, being stored on your server, does not need to be transmitted with each page; clients just
need to send an ID and the data is loaded from the local file. Finally, sessions can be any size you
want because they are held on your server, whereas many web browsers have a limit on how big
cookies can be to stop rogue web sites chewing up gigabytes of data with meaningless cookie
information.
k. FILE AND DIRECTORY ACCESS
• read- write
The fopen() function is used to open files in PHP.
The first parameter of this function contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened:
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
he following example generates a message if the fopen() function is unable to open the specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");
fclose($file);
?>
Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
Note: After a call to this function the file pointer has moved to the next line.
Example
The example below reads a file line by line, until the end of file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
Note: After a call to this function the file pointer moves to the next character.
Example
The example below reads a file character by character, until the end of file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
• append files
If we want to add on to a file we need to open it up in append mode. The code below does just that.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file.
PHP - File Write: Appending Data
Using the testFile.txt file we created in the File Write lesson , we are going to append on some more
data.
PHP Code:
$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 only thing that is different is that the file pointer is placed at the end
of the file in append mode, so all data is added to the end of the file.
The contents of the file testFile.txt would now look like this:
• file modes
Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it
doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it
doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn't
exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already
exists
Syntax
chmod(file,mode)
Parameter Description
file Required. Specifies the file to check
mode Required. Specifies the new permissions.
The mode parameter consists of four numbers:
• 1 = execute permissions
• 2 = write permissions
• 4 = read permissions
Example
<?php
// Read and write for owner, nothing for everybody else
chmod("test.txt",0600);
Syntax
fileowner(filename)
Parameter Description
filename Required. Specifies the file to check
Example
<?php
echo fileowner("test.txt");
?>
• directory
The mkdir() function creates a directory.
Syntax
mkdir(path,mode,recursive,context)
Parameter Description
path Required. Specifies the name of the directory to create
mode Optional. Specifies permissions. By default, the mode is 0777 (widest possible
access).
The mode parameter consists of four numbers:
• 1 = execute permissions
• 2 = write permissions
• 4 = read permissions
recursive Optional. Specifies if the recursive mode is set (added in PHP 5)
context Optional. Specifies the context of the file handle. Context is a set of options that
can modify the behavior of a stream (added in PHP 5)
Example
<?php
mkdir("testing");
?>
• uploading files
HTML Code:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
Here is a brief description of the important parts of the above code:
• input name="uploadedfile" - uploadedfile is how we will access the file in our PHP script.
PHP Code:
$target_path = "uploads/";
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
If the upload is successful, then you will see the text "The file filename has been uploaded". This is
because move_uploaded_file returns true if the file was moved, and false if it had a problem.
If there was a problem then the error message "There was an error uploading the file, please try
again!" would be displayed.
• string types
String variables are used for values that contain characters.
After we have created a string variable we can manipulate it. A string can be used directly in a
function or it can be stored in a variable.
In the example below, we create a string variable called txt, then we assign the text "Hello world!" to
it. Then we write the value of the txt variable to the output:
Example
<?php
$txt="Hello world!";
echo $txt;
?>
Function Description
?>
ereg — Regular expression match
Example:-
<?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
echo "$regs[3].$regs[2].$regs[1]";
} else {
echo "Invalid date format: $date";
}
?>
eregi_replace — Replace regular expression case insensitive
Example:-
<?php
$pattern = '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1<span class="search">\\2</span>';
$body = eregi_replace($pattern, $replacement, $body);
?>
eregi — Case insensitive regular expression match
Example:-
<?php
$string = 'XYZ';
if (eregi('z', $string)) {
echo "'$string' contains a 'z' or 'Z'!";
}
?>
split — Split string into array by regular expression
<?php
// Delimiters may be slash, dot, or hyphen
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>
spliti — Split string into array by regular expression case insensitive
<?php
$string = "aBBBaCCCADDDaEEEaGGGA";
$chunks = spliti ("a", $string, 5);
print_r($chunks);
?>
The above example will output:
Array
(
[0] =>
[1] => BBB
[2] => CCC
[3] => DDD
[4] => EEEaGGGA
)
sql_regcase — Make regular expression for case insensitive match
<?php
echo sql_regcase("Foo - bar.");
?>
The above example will output:
[Ff][Oo][Oo] - [Bb][Aa][Rr].
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event
occurred.
Syntax
date(format,timestamp)
Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time
• Validating a date
n. PHP DEBUGGING
• customized errors
PHP Exception Handling
Exceptions are used to change the normal flow of a script if a specified error occurs.
What is an Exception
With PHP 5 came a new object oriented way of dealing with errors.
Exception handling is used to change the normal flow of the code execution if a specified error
(exceptional) condition occurs. This condition is called an exception.
If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.
<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
The code above will get an error like this:
Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6