4th Unit Web

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 43

Unit 4 - NOTES FOR WEB ESSENTIALS (2021 REG)

IT 3401 WEB ESSENTIALS UNIT 4

UNIT IV
SERVER-SIDE PROCESSING AND SCRIPTING – PHP

PHP - Working principle of PHP - PHP Variables - Constants - Operators – Flow Control
and Looping -Arrays - Strings - Functions - File Handling - File Uploading – Email Basics
- Email with attachments -PHP and HTML - Simple PHP scripts - Databases with PHP

4.1 PHP Basics


• PHP stands for Hypertext Preprocessor. It is an open-source server-side scripting
language used for dynamic web development and can be embedded into HTML
codes.
• A PHP script is usually embedded into another language, such as HTML codes since
a browser does not understand PHP.
Syntax:

<?php
//Write Script here
>

A small PHP “Hello World” program


<?php
echo "Hello world";
?>
The Structure of PHP
Using Comments
There are two ways in which you can add comments to your PHP code.
This is a single line comment
• // echo "X equals $x";
• You can also use this type of comment directly after a line of code to describe its
action, like this:
• $x += 10; // Increment $x by 10
A multiline comment
<?php
/* This is a section
of multiline comments

4.1
IT 3401 WEB ESSENTIALS UNIT 4

which will not be


interpreted */
?>
PHP Syntax:
• PHP is quite a simple language with roots in C and Perl, yet it looks more like Java.
• It is also very flexible.
Semicolons
PHP commands ends with a semicolon:
$x += 10;
Probably the most common cause of errors you will encounter with PHP is forgetting this
semicolon.
This causes PHP to treat multiple statements like one statement.
The $ symbol
The $ symbol has come to be used in many different ways by different programming
languages. In PHP, however, place a $ in front of all variables.
This is required to make the PHP parser faster, as it instantly knows whenever it comes across
a variable.
Three different types of variable assignment
<?php
$mycounter = 1;
$mystring = "Hello";
$myarray = array("One", "Two", "Three");
?>

4.2 WORKING PRINCIPLES OF PHP


Step 1: The client requests the webpage on the browser.
Step 2: The server (where PHP software is installed) then checks for the .php file associated
with the request.
Step 3: If found, it sends the file to the PHP interpreter (since PHP is an interpreted language),
which checks for requested data into the database.
Step 4: The interpreter then sends back the requested data output as an HTML webpage (since
a browser does not understand .php files).

4.2
IT 3401 WEB ESSENTIALS UNIT 4

Step 5: The web server receives the HTML file from the
interpreter. Step 6: And it sends the webpage back to the browser.

4.2.1 Variables
String variables
Assigning a string value to a variable:
$username = "Fred Smith";
echo $username;
Or you can assign it to another variable like this:
$current_user = $username;
Your first PHP program
<?php // test1.php
$username = "Fred Smith";
echo $username;
echo "<br>";
$current_user = $username;
echo $current_user;
?>
Now you can call it up by entering the following into your browser’s address bar:
http://localhost/test1.php
Numeric variables
Variables don’t contain just strings—they can contain numbers, too.
$count = 17;

4.3
IT 3401 WEB ESSENTIALS UNIT 4

You could also use a floating-point number (containing a decimal point); the syntax is the
same:
$count = 17.5;
In PHP, you would assign the value of $count to another variable or perhaps just echo it to the
web browser
Variable naming rules
When creating PHP variables, you must follow these four rules:
• Variable names must start with a letter of the alphabet or the _ (underscore) character.
• Variable names can contain only the characters a–z, A–Z, 0–9, and _ (underscore).
• Variable names may not contain spaces. If a variable must comprise more than one word, it
should be separated with the _ (underscore) character (e.g., $user_name).
• Variable names are case-sensitive. The variable $High_Score is not the same as the variable
$high_score.
4.2.2 Operators
• Operators are the mathematical, string, comparison, and logical commands such as
plus, minus, multiply, and divide.
• echo 6 + 2;
Arithmetic Operators

Assignment operators
• These operators are used to assign values to variables. They start with the very simple
= and move on to +=, −=, and so on
• Thus, if $count starts with the value 5, the statement:
$count += 1;

4.4
IT 3401 WEB ESSENTIALS UNIT 4

• sets $count to 6, just like the more familiar assignment statement:


$count = $count + 1;

Comparison Operators

Logical Operators
Example
if ($hour > 12 && $hour < 14) dolunch();

4.5
IT 3401 WEB ESSENTIALS UNIT 4

• Variable Assignment
The syntax to assign a value to a variable is always variable = value. Or, to reassign the value
to another variable, it is other variable = variable.
There are also a couple of other assignment operators that you will find useful. For example,
we’ve already seen:
$x += 10;
which tells the PHP parser to add the value on the right (in this instance, the value 10) to the
variable $x. Likewise, we could subtract as follows:
$y −= 10;
• Adding or subtracting 1 is such a common operation that PHP provides special
operators for it. You can use one of the following in place of the += and −= operators:
++$x;
−−$y;
• In conjunction with a test (an if statement), you could use the following code:
• if (++$x == 10) echo $x;
• This tells PHP to first increment the value of $x and then test whether it has the value
10; if it does, output its value. But you can also require PHP to increment (or, in the
following example, decrement) a variable after it has tested the value, like this:
• if ($y−− == 0) echo $y;
String concatenation
• String concatenation uses the period (.) to append one string of characters to another.
• The simplest way to do this is as follows:
echo "You have " . $msgs . " messages.";

4.6
IT 3401 WEB ESSENTIALS UNIT 4

• Assuming that the variable $msgs is set to the value 5, the output from this line of
code will be:
You have 5 messages.
• Just as you can add a value to a numeric variable with the += operator, you can
append one string to another using .= like this:
$bulletin .= $newsflash;
• Escaping characters
• Sometimes a string needs to contain characters with special meanings that might be
interpreted incorrectly.
• $text = 'My spelling's atroshus'; // Erroneous syntax
• To correct this, you can add a backslash directly before the offending quotation
mark to tell PHP to treat the character literally and not to interpret it:
$text = 'My spelling\'s still atroshus';
Variable Typing
• PHP is a very loosely typed language. This means that variables do not have to be
declared before they are used .
• PHP always converts variables to the type required by their context when they are
accessed.
Automatic conversion from a number to a string
• <?php
• $number = 12345 * 67890;
• echo substr($number, 3, 1);
• ?>
Automatically converting a string to a number
• <?php
• $pi = "3.1415927";
• $radius = 5;
• echo $pi * ($radius * $radius);
• ?>
4.2.3 Constants
• Constants are similar to variables, holding information to be accessed later. A
constant is an identifier (name) for a simple value. The value cannot be changed
during the script.

4.7
IT 3401 WEB ESSENTIALS UNIT 4

• A valid constant name starts with a letter or underscore (no $ sign before the constant
name).
Predefined Constants
PHP comes ready-made with dozens of predefined constants.
Magic constant Description
LINE The current line number of the file.
FILE Thefullpath and filename of the file.
DIR The directory of the file.
FUNCTION The function name.
CLASS The class name.
METHOD The class method name.
NAMESPACE The name of the current namespace (case-sensitive).
when you need to insert a line of code to see whether the program flow reaches
it: echo "This is line " . LINE . " of file " . FILE ;
Create a PHP Constant
PHP constant can be create,
• Using the define() function.
• Using const keyword
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
Example
1)
<?php
define("MESSAGE",“Welcome IT");
echo MESSAGE;
?>

4.8
IT 3401 WEB ESSENTIALS UNIT 4

2)
<?php
define("MESSAGE",“Welcome IT“,true);
echo MESSAGE;
Echo message;
?>

Using const keyword


• PHP introduced a keyword const to create a constant.
• The const keyword defines constants at compile time.
• The constant defined using const keyword are case-sensitive.
<?php
const MESSAGE="Hello II IT";
echo MESSAGE;
?>
• There is another way to print the value of constants using constant() function instead
of using the echo statement.
The syntax for the following constant function:
constant (name)
• Example
<?php
define("MSG", “IT department");
echo MSG;
echo constant("MSG");
?>
Difference between echo and print
• echo and print are more or less the same.
• They are both used to output data to the screen.
• The differences are small: echo has no return value while print has a return value of 1
so it can be used in expressions.
• echo can take multiple parameters while print can take one argument.

4.9
IT 3401 WEB ESSENTIALS UNIT 4

• echo is marginally faster than print.


4.3.4 Flow Control and Looping
• Conditionals
Conditionals alter program flow.
There are three types of non-looping conditionals:
• if statement,
• switch statement, and
• ? operator
if Statement
An if statement with curly braces
<?php
if ($bank_balance < 100)
{
$money = 1000;
$bank_balance += $money;
}
?>
• else Statement
An if ... else statement with curly braces
<?php
if ($bank_balance < 100)
{
$money = 1000;
$bank_balance += $money;
}
else
{
$savings += 50;
$bank_balance −= 50;
}

4.10
IT 3401 WEB ESSENTIALS UNIT 4

?>
elseif Statement
An if ... elseif ... else statement with curly braces
<?php
if ($bank_balance < 100)
{
$money = 1000;
$bank_balance += $money;
}
elseif ($bank_balance > 200)
{
$savings += 100;
$bank_balance −= 100;
}
else
{
$savings += 50;
$bank_balance −= 50;
}
?>
Switch Statement
<?php
switch ($page)
{
case "Home":
echo "You selected Home";
break;
case "About":
echo "You selected About";
break;

4.11
IT 3401 WEB ESSENTIALS UNIT 4

case "News":
echo "You selected News";
break;
case "Login":
echo "You selected Login";
break;
case "Links":
echo "You selected Links";
break;
}?>
• The ? Operator
• The ? operator is passed an expression that it must evaluate, along with two
statements to execute: one for when the expression evaluates to TRUE, the other for
when it is FALSE.
Using the ? operator
<?php
echo $fuel <= 1 ? "Fill tank now" : "There's enough fuel";
?>
Looping Statement
• A while loop
<?php
$fuel = 10;
while ($fuel >
1)
{
echo "There's enough fuel";
}
?>
A while loop to print the 12 times table
<?php
$count = 1;
while ($count <= 12)

4.12
IT 3401 WEB ESSENTIALS UNIT 4

{
echo "$count times 12 is " . $count * 12 . "<br>";
++$count;
}
?>
• do ... while Loops
A do ... while loop for printing the times table for 12
<?php
$count = 1;
do
{
echo "$count times 12 is " . $count * 12 . "<br>";
++$count;
}
while ($count <= 12);
?>
for Loops
Outputting the times table for 12 from a for loop
<?php
for ($count = 1 ; $count <= 12 ; ++$count)
{
echo "$count times 12 is " . $count * 12;
echo “<br>";
}
?>
Break and continue
The break statement can also be used to jump out of a loop.
<?php
for ($x= 0;$x< 10;$x++)
{ if ($x== 4)
{ break;
}

4.13
IT 3401 WEB ESSENTIALS UNIT 4

echo "The number is: $x <br>";


}
?>
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
<?php
for ($x = 0;$x< 10; $x++)
{ if ($x== 4)
{ continue;
}
echo "The number is: $x <br>";
}
?>

4.2.5 PHP Arrays


• Numerically Indexed Arrays
• PHP indexed array is an array which is represented by an index number by default.
• All elements of array are represented by an index number which starts from 0.
• PHP indexed array can store numbers, strings or any object. PHP indexed array is also
known as numeric array
• It can be defined in two
ways: 1st way:
$size=array("Big","Medium","Short");
2nd way:
$size[0]="Big";
$size[1]="Medium";
$size[2]="Short";
Example 1
<?php
$size=array("Big","Medium","Short");
echo "Size: $size[0], $size[1] and
$size[2]";
?>
Example 2
<?php
IT 3401 WEB ESSENTIALS UNIT 4

4.14
IT 3401 WEB ESSENTIALS UNIT 4

$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
Example 3
<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
<?php
$paper[0] = "Copier";
$paper[1] = "Inkjet";
$paper[2] = "Laser";
$paper[3] = "Photo";
echo($paper);
?>
Adding items to an array and retrieving them
<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laser";
$paper[] = "Photo";
for ($j = 0 ; $j < 4 ; ++$j)
echo "$j: $paper[$j]<br>";
?>
PHP Associative Array
• Can reference the items in an array by name rather than by number.
• PHP allows you to associate name/label with each array elements in PHP using =>
symbol.

4.15
IT 3401 WEB ESSENTIALS UNIT 4

Adding items to an associative array and retrieving them


<?php
$paper['copier'] = "Copier & Multipurpose";
$paper['inkjet'] = "Inkjet Printer";
$paper['laser'] = "Laser Printer";
$paper['photo'] = "Photographic Paper";
echo $paper['laser'];
?>
• Assignment Using the array Keyword
Adding items to an array using the array keyword
<?php
$p1 = array("Copier", "Inkjet", "Laser", "Photo");
echo "p1 element: " . $p1[2] . "<br>";
$p2 = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
echo "p2 element: " . $p2['inkjet'] . "<br>";
?>
• The foreach ... as Loop
Walking through a numeric array using foreach ... as
<?php
$paper = array("Copier", "Inkjet", "Laser", "Photo");
$j = 0;
foreach($paper as $item)
{
echo "$j: $item<br>";
++$j;

4.16
IT 3401 WEB ESSENTIALS UNIT 4

}
?>
Walking through an associative array using foreach ... as
<?php
$paper = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
The foreach ... as Loop | 135
foreach($paper as $item => $description)
echo "$item: $description<br>";
?>
Multidimensional Arrays
PHP - Two-dimensional Arrays
A two-dimensional array is an array of arrays.

Name Stock Sold

Volvo 22 18

BMW 15 13

Saab 5 2

Land 17 15
Rover

$cars =array ( array("Volvo",22,18),


array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
To display
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";

4.17
IT 3401 WEB ESSENTIALS UNIT 4

echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";


echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body>
</html>
4.2.6 Array Function
is_array
To check whether a variable is an array, you can use the is_array function like this:
echo (is_array($fred)) ? "Is an array" : "Is not an array";
count
To count all the elements in the top level of an array, use a command such as the following:
echo count($fred);
To know how many elements there are altogether in a multidimensional array, you can use a
statement such as:
echo count($fred, 1);
The s4econd parameter is optional and sets the mode to use.

4.18
IT 3401 WEB ESSENTIALS UNIT 4

• sort
• Sorting is so common that PHP provides a built-in function. In its simplest form, you
would use it like this:
sort($fred);
sort($fred, SORT_NUMERIC);
sort($fred, SORT_STRING);
You can also sort an array in reverse order using the rsort function, like this:
rsort($fred, SORT_NUMERIC);
rsort($fred, SORT_STRING);
Shuffle
There may be times when you need the elements of an array to be put in random order, such as
when you’re creating a game of playing cards: shuffle($cards);
Like sort, shuffle acts directly on the supplied array and returns TRUE on success or FALSE
on error.
Explode
to split up a sentence into an array containing all its words.
Functions
• Some of the built-in functions that use one or more arguments.
Three string functions
<?php
echo strrev(" .dlrow olleH"); // Reverse string
echo str_repeat("Hip ", 2); // Repeat string
echo strtoupper("hooray!"); // String to uppercase
?>
• This example uses three string functions to output the following text:
Hello world. Hip Hip HOORAY!
PHP User Defined Functions
• Besides the built-in PHP functions, it is possible to create your own functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.

4.19
IT 3401 WEB ESSENTIALS UNIT 4

Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:
Defining a Function
The general syntax for a function is:
function function_name([parameter [, ...]])
{
// Statements
}
A function name must start with a letter or an underscore. Function names are NOT case-
sensitive.
<?php
function writeMsg()
{
Echo "Hello world!";
}

writeMsg(); // call the function


?>
PHP Function Arguments
• Information can be passed to functions through arguments. An argument is just like a
variable.

<!DOCTYPE html>
<html>
<body>
<?php
function add($a,$b)
{
echo $a+$b;
}
add(12,34)

4.20
IT 3401 WEB ESSENTIALS UNIT 4

?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
function add($a,$b)
{ return $a+$b;
}
echo add(12,23);
?>
</body>
</html>

• Returning an Array
There are also ways of getting multiple values from a function.
The first method is to return them within an array. You can use an array to return function
values.
Returning multiple values in an array

4.21
IT 3401 WEB ESSENTIALS UNIT 4

<?php
$names = fix_names("WILLIAM", "henry",
"gatES"); echo $names[0] . " " . $names[1] . " " .
$names[2]; function fix_names($n1, $n2, $n3)
{
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2));
$n3 = ucfirst(strtolower($n3));
return array($n1, $n2, $n3);
}
?>
Passing by Reference
• In PHP, prefacing a variable with the & symbol tells the parser to pass a reference to
the variable’s value, not the value itself.
<?php
$a1 = "WILLIAM";
$a2 = "henry";
$a3 = "gatES";
fix_names($a1, $a2, $a3);
echo $a1 . " " . $a2 . " " . $a3;
function fix_names(&$n1, &$n2, &$n3)
{
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2));
$n3 = ucfirst(strtolower($n3));
}
?>
• Returning Global Variables
• can also give a function access to an externally created variable by declaring it a
global variable from within the function.
<?php

4.22
IT 3401 WEB ESSENTIALS UNIT 4

$a1 = "WILLIAM";
$a2 = "henry";
$a3 = "gatES";
fix_names();
echo $a1 . " " . $a2 . " " . $a3;
function fix_names()
{
global $a1,$a2,$a3;
$a1 = ucfirst(strtolower($a1));
$a2 = ucfirst(strtolower($a2));
$a3 = ucfirst(strtolower($a3));
}
?>
• A string is a sequence of characters, like "Hello world!".
4.2.7 PHP String Functions
strlen() - Return the Length of a String
The PHP strlen() function returns the length of a string.
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
• str_word_count() - Count Words in a String
The PHP str_word_count() function counts the number of words in a string.
Example
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
strrev() - Reverse a String
The PHP strrev() function reverses a string.

4.23
IT 3401 WEB ESSENTIALS UNIT 4

Example
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
strpos() - Search For a Text Within a String
The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE.
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a string.
Example
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
4.3 FILE HANDLING
Checking Whether a File Exists
• To determine whether a file already exists, you can use the file_exists function, which
returns either TRUE or FALSE, and is used like this:
if (file_exists("testfile.txt"))
echo "File exists";
• PHP readfile() Function
The readfile() function reads a file and writes it to the output buffer.
<html>
<body>

4.24
IT 3401 WEB ESSENTIALS UNIT 4

<?php
echo readfile("webexample.txt");
?>

</body>
</html>
PHP Open File - fopen()
• A better method to open files is with the fopen() function.
• 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.
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>

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 "webexample.txt" file to the
end: fread($myfile,filesize("webexample.txt"));
PHP Close File - fclose()
The fclose() function is used to close an open file.

4.25
IT 3401 WEB ESSENTIALS UNIT 4

The fclose() requires the name of the file (or a variable that holds the filename) we want to
close:
<?php
$myfile = fopen("webexample.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:
Example
<?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.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); while(!
feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP Read Single Character - fgetc()
The fgetc() function is used to read a single character from a file.

4.26
IT 3401 WEB ESSENTIALS UNIT 4

The example below reads the "webdictionary.txt" file character by character, until end-of-file
is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
• Copying Files
Let’s try out the PHP copy function to create a clone of testfile.txt. <?php // copyfile.php
copy('testfile.txt', 'testfile2.txt') or die("Could not copy file");
echo "File successfully copied to 'testfile2.txt'";
?>
4.4 FILE UPLOADING
• PHP allows you to upload single and multiple files through few lines of code only.
PHP $_FILES
• The PHP global $_FILES contains all the information of file. By the help of $_FILES
global, we can get file name, file type, file size, temp file name and errors associated
with file.
Here, we are assuming that file name is filename.
• $_FILES['filename']['name’]
returns file name.
• $_FILES['filename']['type’]
returns MIME type of the file.
• $_FILES['filename']['size’]
returns size of the file (in bytes).
• $_FILES['filename']['tmp_name’]
returns temporary file name of the file which was stored on the server.

4.27
IT 3401 WEB ESSENTIALS UNIT 4

• $_FILES['filename']['error’]
returns error code associated with this file.
basename()
The basename() function returns the filename from a path.
Syntax
basename(string $filename , suffix)
basename( $_FILES['fileToUpload']['name']);
move_uploaded_file() function
• The move_uploaded_file() function moves the uploaded file to a new
location. Syntax
bool move_uploaded_file ( string $filename , string $destination )
<?php
$target_path = "e:/";
$target_path = $target_path.basename($_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
<form action="uploader.php" method="post“>
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
PHP and HTML
• When it comes to integrating PHP code with HTML content, you need to enclose the
PHP code with the PHP start tag <?php and the PHP end tag ?>.
• The code wrapped between these two tags is considered to be PHP code, and thus it'll
be executed on the server side before the requested file is sent to the client browser.

4.28
IT 3401 WEB ESSENTIALS UNIT 4

The overall structure of the PHP page combined with HTML and PHP code should look like
this:
<!DOCTYPE html>
<html>
<head>
<title>...</title>
</head>
<body>
HTML...
<?php PHP code ... ?>
HTML...
<?php PHP code ... ?>
HTML...
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>How to put PHP in HTML - Simple Example</title>
</head>
<body>
<h1><?php echo "This message is from server side." ?></h1>
</body>
</html>
• This will output the current date and time, so you can use PHP code between the
HTML tags to produce dynamic output from the server.
• It’s important to remember that whenever the page is executed on the server side, all
the code between the <?php and ?> tags will be interpreted as PHP, and the output
will be embedded with the HTML tags.

<html>

4.29
IT 3401 WEB ESSENTIALS UNIT 4

<head>
<title>How to put PHP in HTML- Date Example</title>
</head>
<body>
<div>This is pure HTML message.</div>
<div>Next, we’ll display today’s date and day by PHP!</div>
<div>
<?php
echo 'Today’s date is <b>' . date('Y/m/d') . '</b> and it’s a <b>'.date('l').'</b> today!';
?>
</div>
<div>Again, this is static HTML content.</div>
</body>
</html>
Embedding HTML into PHP
<?php
echo "<html>\n";
echo "<head>\n";
echo "<title>My Second PHP Example</title>\n";
echo "</head>\n";
echo "<body>\n";
echo "<p>Some Content</p>\n";
echo "</body>\n";
echo "</html>\n";
?>
4.5 E-Mail Basics
• PHP makes use of mail() function to send an email.
• This function requires three mandatory arguments that specify the recipient's email
address, the subject of the message and the actual message additionally there are other
two optional parameters.
mail( to, subject, message, headers, parameters );

4.30
IT 3401 WEB ESSENTIALS UNIT 4

Sending email
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "[email protected]";
$subject = "This is subject";

$message = "<b>This is HTML message.</b>";


$message .= "<h1>This is headline.</h1>";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

$header = "From:[email protected] \r\n";


$header .= "Cc:[email protected] \r\n";

4.31
IT 3401 WEB ESSENTIALS UNIT 4

$retval = mail ($to,$subject,$message,$header);


if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
</body>
</html>
4.5.1 Sending Attachments with email
We have to manually format the email to send
attachments with the native PHP mail() function:
• Open a file
• Read the file into a variable
• Encode the data for safe transit
• Get a random number
• Define the main header
• Define the message section.
• Define the attachment section
• Send the email out – mail("TO", "SUBJECT", $body, $head);

# Read the file into a variable


$size = filesize("/tmp/test.txt");
$content = fread( $file, $size);

# encode the data for safe transit


$encoded_content = chunk_split( base64_encode($content));

# Get a random 32 bit number using time() as seed.


$num = md5( time() );

4.32
IT 3401 WEB ESSENTIALS UNIT 4

# Define the main headers.


// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$header = "From:[email protected] \r\n";
$header .= "Cc:[email protected] \r\n";

# Define the message section


$header .= "Content-Type: text/plain\r\n";
$header .= "Content-Transfer-Encoding:8bit\r\n\n";
$header .= "$message\r\n";
$header .= "--$num\r\n";

# Define the attachment section


$header .= "Content-Type: multipart/mixed; ";
$header .= "name=\"test.txt\"\r\n";
$header .= "Content-Transfer-Encoding:base64\r\n";
$header .= "Content-Disposition:attachment; ";
$header .= "filename=\"test.txt\"\r\n\n";
$header .= "$encoded_content\r\n";
$header .= "--$num--";
# Send email now
$result = mail ( $to, $subject, "", $header );
if( $result == true ){
echo "Message sent successfully...";
}else{
echo "Sorry, unable to send mail...";
}
?>

4.33
IT 3401 WEB ESSENTIALS UNIT 4

4.6 PHP and HTML -PHP SCRIPTS


A sample PHP script block would, therefore, appear in an HTML file as follows:

<?php
echo '<p>This is a PHP script</p>';
?>

Testing the PHP Installation


Before embarking on even the simplest of examples, the first step on the road to learning PHP
is to verify that the PHP module is functioning on your web server.
To achieve this, we will create a small PHP script and upload it to the web server. To do this
start up your favorite editor and enter the following PHP code into it:

<?php
phpInfo();
?>

 This PHP script calls the built-in PHP phpInfo() function, the purpose of which to
output information about the PHP pre-processing module integrated into your web
server.
 Save this file as phpInfo.php and upload it to a location on your web server where it
will be accessible via a web browser.
 Once you have done this open a browser and go to the URL for this file. If all is well
with your PHP installation you will see several pages of detailed information about
your PHP environment covering topics such as how and when the PHP module was
built, the version of the module and numerous configuration settings.
 If you do not see this information it is possible you do not have the PHP module
integrated into your web server. If you use a web hosting company, check with them
to see if your particular hosting package includes PHP support (sometimes PHP
support is only provided with premium hosting packages so you may need to
upgrade). If you run your own web server consult the documentation for your
particular type of server (Apache, Microsoft IIS etc) for details on integrating the PHP
module.
A healthy PHP installation should result in output similar to the following:

Embedding PHP into an HTML File


As you may have realized, by testing the PHP module on your web server you have already
crafted your first PHP script. We will now go on to create another script that is embedded
into an HTML page. Open your editor and create the following HTML file:

<html>

4.34
IT 3401 WEB ESSENTIALS UNIT 4

<head>
<?php
echo '<title>My First PHP Script</title>';
?>
</head>
<body>
<?php
echo '<p>This content was generated by PHP</p>';
?>
<p>And this content is static HTML</p>
</body>
</html>

Save this file as example.php and upload it to your web server.

Embedding HTML into a PHP Script


In the previous example we embedded some PHP scripts into an HTML web page. We can
reverse this by putting the HTML tags into the PHP commands. The following example
contains a PHP script which is designed to output the HTML necessary to display a simple
page. As with the previous examples, create this file, upload it to your web server and load it
into a web browser:

<?php
echo "<html>\n";
echo "<head>\n";
echo "<title>My Second PHP Example</title>\n";
echo "</head>\n";
echo "<body>\n";
echo "<p>Some Content</p>\n";
echo "</body>\n";
echo "</html>\n";
?>

When you load this into your browser it will be as if all that was in the file was HTML, and if
you use the view page source feature of your browser the HTML is, infact, all you will see.
This is because the PHP pre-processor simply created the HTML it was told to create when it
executed the script:

<html>
<head>
<title>My Second PHP Example</title>
</head>

4.35
IT 3401 WEB ESSENTIALS UNIT 4

<body>
<p>Some Content</p>
</body>
</html>

4.7 Databases with PHP

MySQL
MySQL is an open-source relational database management system (RDBMS). It is the most
popular database system used with PHP. MySQL is developed, distributed, and supported
by Oracle Corporation.
 The data in a MySQL database are stored in tables which consists of columns and
rows.
 MySQL is a database system that runs on a server.
 MySQL is ideal for both small and large applications.
 MySQL is very fast, reliable, and easy to use database system.It uses standard
SQL
 MySQL compiles on a number of platforms.
Downloading MySQL Database
MySQL can be downloaded for free from this link.
How to connect PHP with MySQL Database?
PHP 5 and later can work with a MySQL database using:
1. MySQLi extension.
2. PDO (PHP Data Objects).

Difference between MySQL and PDO


 PDO works on 12 different database systems, whereas MySQLi works only with
MySQL databases.
 Both PDO and MySQLi are object-oriented, but MySQLi also offers a procedural
API.
 If at some point of development phase, the user or the development team wants to
change the database then it is easy to that in PDO than MySQLi as PDO supports
12 different database systems.He would have to only change the connection string
and a few queries. With MySQLi,he will need to rewrite the entire code including
the queries.
There are three ways of working with MySQl and PHP
1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO

Connecting to MySQL database using PHP


There are 3 ways in which we can connect to MySQl from PHP as listed above and described
below:
 Using MySQLi object-oriented procedure: We can use the MySQLi object-
oriented procedure to establish a connection to MySQL database from a PHP
script.
Syntax:

4.36
IT 3401 WEB ESSENTIALS UNIT 4

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Creating connection
$conn = new mysqli($servername, $username, $password);

// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Output:

Explanation: We can create an instance of the mysqli class providing all the necessary
details required to establish the connection such as host, username, password etc. If the
instance is created successfully then the connection is successful otherwise there is some
error in establishing connection.
Using MySQLi procedural procedure : There is also a procedural approach of MySQLi to
establish a connection to MySQL database from a PHP script as described below.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Creating connection
$conn = mysqli_connect($servername, $username, $password);

// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Output:

Explanation: In MySQLi procedural approach instead of creating an instance we can use the
mysqli_connect() function available in PHP to establish a connection. This function takes the
information as arguments such as host, username , password , database name etc. This

4.37
IT 3401 WEB ESSENTIALS UNIT 4

function returns MySQL link identifier on successful connection or FALSE when failed to
establish a connection.
 Using PDO procedure: PDO stands for PHP Data Objects. That is, in this
method we connect to the database using data objects in PHP as described below:
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Output:

Explanation:The exception class in PDO is used to handle any problems that may occur in
our database queries. If an exception is thrown within the try{ } block, the script stops
executing and flows directly to the first catch(){ } block.
Closing A Connection
When we establish a connection to MySQL database from a PHP script , we should also
disconnect or close the connection when our work is finished. Here we have described the
syntax of closing the connection to a MySQL database in all 3 methods described above. We
have assumed that the reference to the connection is stored in $conn variable.
 Using MySQLi object oriented procedure
Syntax
$conn->close();
 Using MySQLi procedural procedure
Syntax
mysqli_close($conn);
 Using PDO procedure
Syntax
$conn = null;

PART A

4.38
IT 3401 WEB ESSENTIALS UNIT 4

PART A

1) Define PHP

 stands for Hypertext Preprocessor. It is an open-source server-side scripting language


used for dynamic web development and can be embedded into HTML codes.
 A PHP script is usually embedded into another language, such as HTML codes since
a browser does not understand PHP.
2) How to access string variables.

Assigning a string value to a variable:


$username = "Fred Smith";
echo $username;
Or you can assign it to another variable like this:
$current_user = $username;
3) Write the rule for variable naming.

 Variable names must start with a letter of the alphabet or the _ (underscore) character.
• Variable names can contain only the characters a–z, A–Z, 0–9, and _ (underscore).
• Variable names may not contain spaces. If a variable must comprise more than
one word, it should be separated with the _ (underscore) character (e.g.,
$user_name).
• Variable names are case-sensitive. The variable $High_Score is not the same as
the variable $high_score.
4) How to define assignment operators

• These operators are used to assign values to variables. They start with the very simple
= and move on to +=, −=, and so on
• Thus, if $count starts with the value 5, the statement:
o $count += 1;
5) Write one example for string concatenation.

• String concatenation uses the period (.) to append one string of characters to
another.
• The simplest way to do this is as follows:
echo "You have " . $msgs . " messages.";
• Assuming that the variable $msgs is set to the value 5, the output from this line of
code will be:
You have 5 messages.

4.39
IT 3401 WEB ESSENTIALS UNIT 4

• Just as you can add a value to a numeric variable with the += operator, you can
append one string to another using .= like this:
$bulletin .= $newsflash;
6) Write two method for creating PHP constant.

PHP constant can be create,


• Using the define() function.
• Using const keyword
7) Write the difference between echo and print.

• echo and print are more or less the same.


• They are both used to output data to the screen.
• The differences are small: echo has no return value while print has a return value of 1
so it can be used in expressions.
echo can take multiple parameters while print can take one argument
8) State the use of ? operator.

• The ? operator is passed an expression that it must evaluate, along with two
statements to execute: one for when the expression evaluates to TRUE, the other for
when it is FALSE.
9) List possible data types available in PHP.

10) What do you mean by expression? Give examples.


Anything that has a value is an expression. In a typical assignment statement ($x=100), a
literal value, a function or operands processed by operators is an expression, anything that
appears to the right of assignment operator (=)
Syntax
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression

4.40
IT 3401 WEB ESSENTIALS UNIT 4

11) Write the uses of text manipulation with regular expression in PHP.
PHP processes text data easily and efficiently, enabling straightforward searching,
substitution, extraction and concatenation of strings.
Text manipulation in PHP is usually done with regular expressions — a series of
characters that serve as pattern-matching templates (or search criteria) in strings, text
files and databases.
This feature allows complex searching and string processing to be performed using
relatively simple expressions
12) How to Include PHP in a Web Page?
There are 4 ways of including PHP in a web page
<html>
<head>
<title>Hello World</title>
<body>
<?php echo "Hello, World!";?>
</body>
13) Write a simple PHP script

Here is PHP script which is embedded in HTML using level one header with the
PHP output text. The name of this file is called hello.php.
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>

PART B
1) Write the working principle of PHP

2) Explain about constants and operators.

3) Write a program for file handling and file uploading

4) Write a program using functions ,string,arrays

PART C
1) Write a program for classroom management system using database and arrays.

2) Write a program using file handling and file uploading

4.41

You might also like