WP Module 3
WP Module 3
WP Module 3
PHP 5 Syntax
• A PHP script is executed on the server, and the plain HTML result is sent
back to the browser.
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
• The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP scripting code.
example
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
• we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "
echo" to output the text "Hello World!" on a web page:
• PHP statements end with a semicolon (;).
Comments in PHP
echo $x;
echo "<br>";
echo $y;
?>
2) PHP Integer
• Integers are whole numbers, without a decimal point, like 4195.Rules for
integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based),
hexadecimal (16-based) or octal (8-based).
In the following example $x is an integer. The PHP var_dump() function
returns the data type and value:
• Example
• <?php
$x = 5985;
var_dump($x);
?>
3)PHP Float
• A float (floating point number) is a number with a decimal point
or a number in exponential form. In the following example $x is
a float. The PHP var_dump() function returns the data type and
value:
• Example
• <?php
$x = 10.365;
var_dump($x);
?>
4)PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• $x = true;
$y = false;
• Booleans are often used in conditional testing.
Compound data types-
1)PHP array :
An array stores multiple values in one single variable. In the
following example $cars is an array. The PHP var_dump()
function returns the data type and value:
• Example
• <?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
2)PHP Object
An object is a data type which stores data and information on how to process that data. In PHP,
an object must be explicitly declared. First we must declare a class of object.
For this, we use the class keyword. A class is a structure that can contain properties and
methods:
• Example
• <?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
• Constants are like variables except that once they are defined
they cannot be changed or undefined.
• A constant is an identifier (name) for a simple value. The value
cannot be changed during the script.
• A valid constant name starts with a letter or underscore (no $
sign before the constant name). Unlike variables, constants are
automatically global across the entire script.
• Create a PHP Constant : To create a constant, use the define()
function.
• Syntax
• define(name, value, case-insensitive)
• Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should
be case-insensitive. Default is false
PHP Operators
• Operators are used to operate on values. There are four
classifications of operators:
1. Arithmetic
2. Assignment
3. Comparison
4. Logical
Arithmetic Operators
Assignment Operators
Comparison operators
Logical Operators
Control Structures
• PHP Conditional Statements:
• Very often when you write code, you want to perform different actions
for different conditions. You can use conditional statements in your
code to do this.
• In PHP we have the following conditional statements:
• if statement - use this statement to execute some code only if a
specified condition is true.
• if...else statement - use this statement to execute some code if a
condition is true and another code if the condition is false.
• if...elseif....else statement - use this statement to select one of several
blocks of code to be executed.
• switch statement - use this statement to select one of many blocks of
code to be executed.
PHP - The if Statement
The if statement executes some code if one 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 (HOUR) is less
than 20:
• Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
PHP - The if...else Statement
The if....else statement executes some code if a condition is true and another code if that
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");
• Example
This example decrements a variable value on each iteration of
the loop and the counter increments until it reaches 10 when the
evaluation is false and the loop ends.
Example- while loop
• <html>
• <body>
• <?php
• $i = 0;
• $num = 50;
• while( $i < 10) {
• $num--;
• $i++;
• }
• echo ("Loop stopped at i = $i and num = $num" );
• ?>
• </body>
• </html>
output
• This will produce the following result −
• Loop stopped at i = 10 and num = 40
The do...while loop statement
• The do...while statement will execute a block of code at least
once - it then will repeat the loop as long as a condition is true.
• Syntax
• do {
• code to be executed;
•}
• while (condition);
example • <html>
• <body>
• The following example will • <?php
increment the value of i at • $i = 0;
least once, and it will continue
• $num = 0;
incrementing the variable i as
long as it has a value of less • do {
than 10 . • $i++;
• This will produce the •}
following result − • while( $i < 10 );
• Loop stopped at i = 10 • echo ("Loop stopped at i = $i" );
• ?>
• </body>
• </html>
The for loop statement
The for statement is used when you know how many times you
want to execute a statement or a block of statements.
• Syntax
for (initialization; condition; increment){
code to be executed; }
• Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to
TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
• The following example has a function with two arguments ($fname and $year):
• Example
• <?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
PHP Default Argument Value
• The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as argument:
• Example
• <?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values
• To let a function return a value, use the return statement:
• Example
• <?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
</body>
</html>
Form Handling
• When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form
data is sent with the HTTP POST method.
• To display the submitted data you could simply echo all the variables. The "
welcome.php" looks like this:
• <html>
<body>
</body>
</html>
• The output could be something like this:
Welcome John
Your email address is [email protected]
The same result could also be achieved using the HTTP GET
method:
• <html>
<body>
</body>
</html>
• and "welcome_get.php" looks like this:
• <html>
<body>
</body>
</html>
PHP 5 Form Validation
The validation rules for the form above
are as follows:
• Text Fields
• The name, email, and website fields are text input elements, and
the comment field is a textarea. The HTML code looks like this:
• Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></
textarea>
• Radio Buttons
• The gender fields are radio buttons and the HTML code looks
like this:
• Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
PHP 5 Sessions
• What is a PHP Session?
• A session is a way to store information (in variables) to be used
across multiple pages.
• When you work 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 or what you
do, because the HTTP address doesn't maintain state.
• Session variables solve this problem by storing user information
to be used across multiple pages (e.g. username, favorite color,
etc). By default, Sessions end when the user closes the browser,
or when the web server deletes the session information.
Start a PHP Session
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.
• Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
• <?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
PHP - Cookies
• Cookies are text files stored on the client computer and they are
kept of use tracking purpose. PHP transparently supports HTTP
cookies.
• There are three steps involved in identifying returning users −
• Server script sends a set of cookies to the browser. For example
name, age, or identification number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it
sends those cookies information to the server and server uses
that information to identify the user.
Setting Cookies with PHP
• PHP provided setcookie() function to set a cookie. This function
requires upto six arguments and should be called before <html>
tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments :
• Name − This sets the name of the cookie and is stored in an
environment variable called HTTP_COOKIE_VARS. This variable is
used while accessing cookies.
• Value − This sets the value of the named variable and is the
content that you actually want to store.
• Expiry − This specify a future time in seconds since 00:00:00
GMT on 1st Jan 1970. After this time cookie will become
inaccessible. If this parameter is not set then cookie will
automatically expire when the Web Browser is closed.
• Path − This specifies the directories for which the cookie is
valid. A single forward slash character permits the cookie to be
valid for all directories.
• Domain − This can be used to specify the domain name in very
large domains and must contain at least two periods to be valid.
• Security − This can be set to 1 to specify that the cookie should
only be sent by secure transmission using HTTPS otherwise set
to 0 which mean cookie can be sent by regular HTTP.
Following example will create two cookies name and age these cookies will
be expired after one hour.
• <?php
• setcookie("name", "John Watkin", time()+3600, "/","", 0);
• setcookie("age", "36", time()+3600, "/", "", 0);
• ?>
• <html>
• <head>
• <title>Setting Cookies with PHP</title>
• </head>
• <body>
• <?php echo "Set Cookies"?>
• </body>
• </html>
Accessing Cookies with PHP
• PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.
• <html>
• <head>
• <title>Accessing Cookies with PHP</title>
• </head>
• <body>
• <?php
• echo $_COOKIE["name"]. "<br />";
• /* is equivalent to */
• echo $HTTP_COOKIE_VARS["name"]. "<br />";
• echo $_COOKIE["age"] . "<br />";
• /* is equivalent to */
• echo $HTTP_COOKIE_VARS["age"] . "<br />";
• ?>
• </body>
• </html>
Deleting Cookie with PHP
• Officially, to delete a cookie you should call setcookie() with the name argument
only but this does not always work well, however, and should not be relied on.
• It is safest to set the cookie with a date that has already expired −
• <?php
• setcookie( "name", "", time()- 60, "/","", 0);
• setcookie( "age", "", time()- 60, "/","", 0);
• ?>
• <html>
• <head>
• <title>Deleting Cookies with PHP</title>
• </head>
• <body>
• <?php echo "Deleted Cookies" ?>
• </body>
• </html>
PHP 5 File Handling
The PHP code to read the file and write it to the
output buffer is as follows
• <!DOCTYPE html> • AJAX = Asynchronous
<html> JavaScript and XML CSS =
<body> Cascading Style Sheets HTML
= Hyper Text Markup
<?php Language PHP = PHP
echo readfile("webdictionary. Hypertext Preprocessor SQL =
txt"); Structured Query Language
?> SVG = Scalable Vector
Graphics XML = EXtensible
</body> Markup Language
</html>
PHP Open File - fopen()
• A better method to open files is with the fopen() function. This
function gives you more options than the readfile() function.
• We will use the text file, "webdictionary.txt",
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
• The first parameter of fopen() contains the name of the file to
be opened and the second parameter specifies in which mode
the file should be opened. The following example also
generates a message if the fopen() function is unable to open
the specified file:
Example AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets HTML =
Hyper Text Markup Language PHP = PHP
Hypertext Preprocessor SQL = Structured
• <!DOCTYPE html> Query Language SVG = Scalable Vector
Graphics XML = EXtensible Markup
<html> Language
<body>
<?php
$myfile = fopen("webdictionary.txt", "r")
or die("Unable to open file!");
echo fread($myfile,filesize("
webdictionary.txt"));
fclose($myfile);
?>
</body>
</html>
The file may be opened in one of the following modes:
PHP Read File - fread()
• The fread() function reads from an open file.
• The first parameter of fread() contains the name of the file to
read from and the second parameter specifies the maximum
number of bytes to read.
• The following PHP code reads the "webdictionary.txt" file to the
end:
• fread($myfile,filesize("webdictionary.txt"));
PHP Close File - fclose()
• The fclose() function is used to close an open file. The fclose()
requires the name of the file (or a variable that holds the
filename) we want to close:
• <?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Read Single Line - fgets()
• The fgets() function is used to read a single line from a file.
• The example below outputs the first line of the "webdictionary.
txt" file:
• <?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
echo fgets($myfile);
fclose($myfile);
?>
PHP Check End-Of-File - feof()
• 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.
• PHP Read Single Character - fgetc():
• The fgetc() function is used to read a single character from a file.
• PHP Create File - fopen():
• The fopen() function is also used to create a file. Maybe a little
confusing, but in PHP, a file is created using the same function used
to open files.
PHP Write to File - fwrite()
• The fwrite() function is used to write to a file. The first parameter
of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
• <?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
• Notice that we wrote to the file "newfile.txt" twice. Each time we
wrote to the file we sent the string $txt that first contained "John
Doe" and second contained "Jane Doe". After we finished writing,
we closed the file using the fclose() function.
• If we open the "newfile.txt" file it would look like this:
• John Doe
Jane Doe
PHP 5 File Upload
• A PHP script can be used with a HTML form to allow users to
upload files to the server. Initially files are uploaded into a
temporary directory and then relocated to a target destination by
a PHP script.
• Information in the phpinfo.php page describes the temporary
directory that is used for file uploads as upload_tmp_dir and the
maximum permitted size of files that can be uploaded is stated
as upload_max_filesize. These parameters are set into PHP
configuration file php.ini
The process of uploading a file follows these steps −
• The user opens the page containing a HTML form featuring a text
files, a browse button and a submit button.
• The user clicks the browse button and selects a file to upload from
the local PC.
• The full path to the selected file appears in the text filed then the user
clicks the submit button.
• The selected file is sent to the temporary directory on the server.
• The PHP script that was specified as the form handler in the form's
action attribute checks that the file has arrived and then copies the
file into an intended directory.
• The PHP script confirms the success to the user.
• An uploaded file could be a text file or image file or any document.
Create The HTML Form
• <!DOCTYPE html>
<html>
<body>
</body>
</html>
• Some rules to follow for the HTML form above:
• Make sure that the form uses method="post"
• The form also needs the following attribute: enctype="multipart/form-
data". It specifies which content-type to use when submitting the form
• Without the requirements above, the file upload will not work.
• Other things to notice:
• The type="file" attribute of the <input> tag shows the input field as a file-
select control, with a "Browse" button next to the input control
• The form above sends data to a file called "upload.php", which we will
create next.
Create The Upload File PHP Script
• The "upload.php" file contains the code for uploading a file:
• <?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
PHP script explained:
• $target_dir = "uploads/" - specifies the directory where the file is
going to be placed
• $target_file specifies the path of the file to be uploaded
• $uploadOk=1 is not used yet (will be used later)
• $imageFileType holds the file extension of the file (in lower case)
• Next, check if the image file is an actual image or a fake image
END