WT Unit 1
WT Unit 1
Sl no Content Pg no
1 Introduction to PHP 1-2
Overview of PHP
Characteristics of PHP
Advantages of PHP
Disadvantages of PHP
4 Array 12-16
Indexed arrays
Associative arrays
Multidimensional arrays
5 Strings 17-18
6 Operator 18-23
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Categorizing operators
Unary Operators
Binary Operators
Ternary Operators
C 1.29 HTML code for reading input value from the user 39
button
C 1.48 PHP code for reading the content of a file using fread() 59
Introduction to PHP
PHP is a server scripting language, and a powerful tool for making dynamic
and interactive Web pages.
PHP was originally created by Rasmus Lerdorf in 1995, who added web forms that
communicate with database
Overview of PHP
Advantages of PHP
Page 1
CSE Dept., CMREC
Disadvantages of PHP
Security : Since it is open sourced, so all people can see the source code, if
there are bugs in the source code, it can be used by people to explore the
weakness of PHP.
Not suitable for large applications: Hard to maintain since it is not
very modular.
Weak type: Implicit conversion may surprise unwary programmers and
lead to unexpected bugs. For example, the strings "1000" and "1e3"
compare equal because they are implicitly cast to floating point
numbers.
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
Declaring variables
$variablename=value;
Rules for variables declaration
Variable always starts with the $ sign, followed by the variable name.
Variable name must start with a letter or the underscore character.
Variable name cannot start with a number.
Variable name can only allow alpha-numeric characters and underscores
(A- z, 0-9, and _ ) other special character not allowed.
Variable names are case sensitive ($var and $VAR are two
different variables).
Scope of variables:
Scope can be defined as the range of availability a variable has to the program
in which it
is declared. PHP variables can be one of four scope types:
Local variables
Global variables
Static variables
Local variables
A variable declared in a function is considered local.
C 1.2 PHP Code for demonstrating scope of local variables
<?php
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x.";
}
assignx();
print "\$x outside of function is $x.";
?>
This will produce the following result.
$x inside function is 0.
Global$xoutsidevariablesoffunction is 4.
Page 3
CSE Dept., CMREC
Static Variables
<?php
function keep_track() { STATIC $count = 0;
$count++; print $count; print " ";
}
keep_track(); keep_track(); keep_track();
?>
This will produce the following result.
Page 4
CSE Dept., CMREC
1
2
3
Data types
PHP has built-in Data Types which is divided into three catagories Scalar
types,Compound types and Special types. PHP has total eight (8) different data
types to work with.
Scalar types
boolean
integer
float
string
Compound types
array
object
Special types
resources
NULL
Boolean Type
In PHP the boolean data type is a primitive data type they have only two
possible values true and false. This is a fundamental data type and very common
in computer programs.
Page 5
CSE Dept., CMREC
<?php
$isVisited = False;
$isVisited = userVisited();
if ($isVisited) {
} else {
?>
Integer Type
Integer is a whole number. PHP integer is the same as the long data type in C. It is
a number between -2,147,483,648 and +2,147,483,647. Integers can be specified
in three different notations in PHP. Decimal, hexadecimal and octal. Octal values
are preceded by 0, hexadecimal by 0x.
Rules for integers
Page 6
CSE Dept., CMREC
<?php
$w = 2300;
var_dump($w);
number var_dump($x);
number var_dump($y);
number var_dump($z);
?>
int(2300)
int(-560)
int(44)
int(22)
Page 7
CSE Dept., CMREC
<?php
$var1 = 2.786;
$var2 = 2.2e3;
$var3 = 1E-10;
$var4 = 12345678923445;
var_dump($var1);
var_dump($var2);
var_dump($var3);
var_dump($var4);
?>
float(2.786)
float(2200)
float(1.0E-10)
float(12345678923445)
String Type
String is a series of single characters such as "Hello PHP". Most of working with
Web pages is about working with strings. In PHP a string must be delimited by one
of four syntaxes: single quotes, double quotes, heredocs, and nowdocs.
Page 8
CSE Dept., CMREC
Array Type
In simple word array is complex data type which hold collection of related
data elements.Each of the elements can be accessed by an index.
C 1.9 PHP Array Type Example
<?php
print_r($months);
?>
Array
Page 9
CSE Dept., CMREC
Object Type
In simple word object are instances of class definitions. Objects are user defined
data types normaly used to define properties/attributes of object. First we need
to declear a class of object that can contain properties and methods.
Page 10
CSE Dept., CMREC
class Books{
*/ var $title;
$this->price = $price_par;
function getPrice(){
function setTitle($title_par){
$this->title = $title_par;
function getTitle(){
$book->setPrice(123);
$book->getPrice();
?>
Page 11
CSE Dept., CMREC
Resource Type
Resources are special data types. They hold a reference to an external
resource (such as database connections).
NULL Type
NULL is a special type that only have one possible value and that's null. This type
is also treated as a language constant in PHP and is case-insensitive. PHP considers
all undefined variables to be of type NULL.
C 1.11 PHP Code for NULL Type
<?php
$var="Hello world!";
$var=null;
var_dump($var);
?>
NULL
Array:
An array is a data structure that stores one or more similar type of values in
a single value.
In PHP, the array() function is used to create an array:
array();
Page 12
CSE Dept., CMREC
Indexed arrays
PHP index is represented by number which starts from 0.Number, string and
object can be stored in the PHP array. All PHP array elements are assigned
to an index number by default.
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
<html>
<body>
<?php
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
Page 13
CSE Dept., CMREC
Output:
In the above example, the PHP creates an indexed array named $cars,
assigns three elements to it, and then prints a text containing the
array values:
Associative arrays
Associative arrays are arrays that use named keys that are assigned to them.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is " . $age['Pet
</body>
</html>
output:
Page 14
CSE Dept., CMREC
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
</body>
</html>
output:
Multidimensional arrays
Page 15
CSE Dept., CMREC
C 1.15 PHP code snippet to create a two-dimensional array and store elements in
it.
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
<!DOCTYPE html>
<html>
<body>
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
Page 16
CSE Dept., CMREC
PHP string
A PHP string is a sequence of characters i.e. used to store and manipulate text.
There are 2 ways to specify string in PHP.
C 1.16 PHP code to demonstrate the working of single quote and double quote
<?php
$count = 5;
echo "<p>The count is $count.\n</p>";// Substitutes variable with its value echo '<p>The count is $count.
echo '<p>The count is '.$count.'.</p>'; // Use string concatenation (.) echo '<p>The count is ', $count, '.</
Page 17
CSE Dept., CMREC
OUTPUT:
OPERATORS:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Page 18
CSE Dept., CMREC
The basic assignment operator in PHP is "=". It means that the left operand gets set
to the value of the assignment expression on the right.
Comparison operators:
The PHP comparison operators are used to compare two values (number or string):
Page 19
CSE Dept., CMREC
Increment/Decrement operators
Logical operators
Page 20
CSE Dept., CMREC
String operators
PHP has two operators that are specially designed for strings.
Array operators
Page 21
CSE Dept., CMREC
In general, operators have a set precedence, or order, in which they are evaluated.
Operators also have associativity, which is the order in which operators of the
same precedence are evaluated. This order is generally left to right (called left for
short), right to left (called right for short), or not relevant.
Operator Precedence
2+4*3
The addition and multiplication operators have different precedence, with
multiplication higher than addition. So the multiplication happens before
the addition, giving 2 + 12, or 14, as the answer.
To force a particular order, operands can be grouped with the appropriate operator in
parentheses. In our previous example, to get the value 18, use this expression:
(2 + 4) * 3
In this table, operators with the lowest precedence are at the bottom, and
precedence decreases going down in the table.
Page 22
CSE Dept., CMREC
Operators
Additional Associativity non
Information
clone new —associative left
clone and new
array ()
” arithmetic right
++ —— (int) (float) (strinq) (array) (object) (bool) @ increment/decrement and types right
ins t ance
types non-associative
of
arithmetic left
/96
comparison non—associative
comparison non-associative
bitwise OR left
logical OR left
ternary left
as siqnment right
logical left
and
logical left
xor
logical left
or
many uses (comma) left
Page 23
CSE Dept., CMREC
The simplest expressions are literal values and variables. A literal value
evaluates to itself, while a variable evaluates to the value stored in the variable.
More complex expressions can be formed using simple expressions and operators.
A statement in PHP is any expression that is followed by a semicolon (;).
Any sequence of valid PHP statements that is enclosed by the PHP tags is a valid
PHP program.
CONTROL STRUCTURES:
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:
Page 24
CSE Dept., CMREC
<?php
$ t = date("H");
</body>
</html>
OUTPUT:
Have a good day!
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:
Page 25
CSE Dept., CMREC
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
} else {
?>
</body>
</html>
OUTPUT:
Page 26
CSE Dept., CMREC
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is
less than 10, and "Have a good day!" if the current time is less than 20.
Otherwise it will output "Have a good night!":
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
echo "<p>The hour (of the server) is ". $t;
echo ", and will give the following message:</p>";
</body>
</html>
Page 27
CSE Dept., CMREC
OUTPUT:
The hour (of the server) is 04, and will give the following message:
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Page 28
CSE Dept., CMREC
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red";
</body>
</html>
OUTPUT:
Your favorite color is red!
Page 29
CSE Dept., CMREC
PHP Loops
Often when a code is written, the programmer wants the same block of code to run
over and over again in a row. Instead of adding several almost equal code-lines in a
script, we can use loops to perform a task like this.
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will
continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase
by 1 each time the loop runs ($x++):
Page 30
CSE Dept., CMREC
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
</body>
</html>
Output:
The number is:
1 The number is:
2 The number is:
3 The number is:
4 The number is:
5
The do...while loop will always execute the block of code once, it will then
check the condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop
will write some output, and then increment the variable $x with 1. Then the
Page 31
CSE Dept., CMREC
condition is checked (is $x less than, or equal to 5?), and the loop will continue
to run as long as $x is less than, or equal to 5:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>
Output:
The number is:
1 The number
is: 2 The
number is: 3 The
number is: 4
The number is:
5
Page 32
CSE Dept., CMREC
The for loop is used when the programmer knows in advance how many times the
script should run.
Syntax
Parameters:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>";
}
?>
</body>
</html>
Page 33
CSE Dept., CMREC
OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
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, until it reaches the last
array element.
Page 34
CSE Dept., CMREC
Output:
red
green
blue
yellow
Functions
PHP function is a piece of code that can be reused many times. It can take input as
argument list and return value. There are thousands of built-in functions in PHP.
Syntax
function functionName() {
code to be executed;
}
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() { echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
Page 35
CSE Dept., CMREC
Output:
Hello world!
Arguments are specified after the function name, inside the parentheses.
Any number of arguments can be added, separated by a comma.
<?php
function familyName($fname) { echo "$fname Stark.<br>";
}
</body>
</html> Output: Jani Stark Hege Stark Stale Stark
Kai Jim Stark Borge Stark
Page 36
CSE Dept., CMREC
PHP allows a programmer to call function by value and reference both. In case of
PHP call by value, actual value is not modified if it is modified inside the function.
<?php
function adder($str2) {
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
Output:
11
Page 37
CSE Dept., CMREC
Code Reusability: PHP functions are defined only once and can be invoked many
times, like in other programming languages.
Less Code: It saves a lot of code because there is no need to write the logic many
times. By the use of function, write the logic only once and reuse it.
Reading data from web form controls like text boxes, radio buttons, lists etc.
The <form> Element
The HTML <form> element defines a form that is used to collect user input:
<form>
.
form elements
.
</form>
Form elements are different types of input elements, like text fields,
checkboxes, radio buttons, submit buttons, and more.
Page 38
CSE Dept., CMREC
C 1.29 HTML code for reading input value from the user
<!DOCTYPE html>
<html>
<body>
<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>
</body>
</html> output: First name:
Last name:
Page 39
CSE Dept., CMREC
<!DOCTYPE html>
<html>
<body>
<form>
</form>
</body>
</html>
Output:
Male
Female Other
<input type="submit"> defines a button for submitting the form data to a form-
handler.
The form-handler is typically a server page with a script for processing input data.
Page 40
CSE Dept., CMREC
<!DOCTYPE html>
<html>
<body>
<p>If user clicks the "Submit" button, the form-data will be sent to a page called "/action_page.
</body>
</html> output: First name:
Mickey
Last name:
Mouse
Submit
If user clicks the "Submit" button, the form-data will be sent to a page
called "/action_page.php".
Page 41
CSE Dept., CMREC
The action attribute defines the action to be performed when the form is submitted.
Normally, the form data is sent to a web page on the server when the user clicks on
the submit button.
In the example above, the form data is sent to a page on the server called
"/action_page.php". This page contains a server-side script that handles the form
data:
Syntax
<form action="/action_page.php">
If the action attribute is omitted, the action is set to the current page.
The target attribute specifies if the submitted result will open in a new
browser tab, a frame, or in the current window.
The default value is "_self" which means the form will be submitted in the
current window.
To make the form result open in a new browser tab, use the value "_blank":
Syntax
The method attribute specifies the HTTP method (GET or POST) to be used
when submitting the form data:
or
Page 42
CSE Dept., CMREC
Contd…
Page 43
CSE Dept., CMREC
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
OUTPUT:
* required field.
Name: *
E-mail: *
Website:
Comment:
Submit
Page 44
CSE Dept., CMREC
PHP allows to upload single and multiple files through few lines of code only.
PHP file upload features allows to upload binary and text files both. Moreover, a
programmer can have the full control over the file to be uploaded through PHP
authentication and file operation functions.
PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of
$_FILES global, the programmer can get file name, file type, file size, temp file
name and errors associated with file.
Page 45
CSE Dept., CMREC
File: uploadform.html
<form action="uploader.php" method="post" enctype="multipart/form-data">
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/> </form>
File: uploader.php
<?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!";
}
?>
Page 46
CSE Dept., CMREC
MySql:
MySQL is a open-source database system (free to download and use) on the web
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
MySQL uses standard SQL
MySQL compiles on a number of platforms, supports many operating systems
with many languages like PHP, PERL, C, C++, JAVA, etc.
MySQL is quicker than other databases so it can work well even with the large data set.
Dynamic: Since MySql is implemented at server side and PHP is a server side scripting
language, dynamic pages with customized features can be created.
User friendly: PHP provides a user-friendly and interactive website or web application
and also enables visitors to freely interact while producing a very flexible and
dynamic content.
Ease of use: PHP and MySql are easy to learn as compared to the
other programming languages. The PHP syntax can easily be parsed.
Page 47
CSE Dept., CMREC
Before data in the MySQL database can be accessed,connect PHP program to the server.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
PHP mysql_close()
PHP mysql_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false.
Syntax:
mysql_close($conn);
Page 48
CSE Dept., CMREC
reg_date TIMESTAMP
)"; email VARCHAR(50),
Page 49
CSE Dept., CMREC
C 1.39 PHP Code to check whether data/record is inserted into table properly or not.
Syntax
SELECT * FROM table_name
C 1.40 PHP code to check whether a record with id=3 is deleted or not.
if ($conn->query($sql) === TRUE) { echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
Page 50
CSE Dept., CMREC
Page 51
CSE Dept., CMREC
Creating a Session
In order to create a session, the PHP session_start function must be first called and then store
user values in the $_SESSION array variable.
<?php
function if(isset($_SESSION['page_count']))
$_SESSION['page_count'] += 1;
else
$_SESSION['page_count'] = 1;
Output:
The session_destroy() function is used to destroy the whole Php session variables.
In order to destroy only a session single item, use the unset() function.
Page 52
CSE Dept., CMREC
<?php
session_destroy(); //destroy entire session
?>
<?php
unset($_SESSION['product']); //destroy product session item
?>
session_destroy removes all the session data including cookies associated with the session.
unset only frees the individual session variables.
PHP Cookies
Http is a stateless protocol. cookies allow us to track the state of the application using small
files stored on the user’s computer.
The path were the cookies are stored depends on the browser.
Definition: A cookie is a small file with the maximum size of 4KB that the web server stores
on the client computer.
Once a cookie has been set, all page requests that follow return the cookie name and value.
A cookie can only be read from the domain that it has been issued from.
Page 53
CSE Dept., CMREC
Here,
3) Other page requests from the user will return the cookie name and value
Syntax
Creating Cookies
<?php
?>
where,
?>
Output:
Page 54
CSE Dept., CMREC
Delete Cookies
In order to destroy a cookie before its expiry time, then set the expiry time to a time
that has already passed.
Create a new filed named cookie_destroy.php with the following code
<?php
?>
PHP provides a convenient way of working with files via its rich collection of built in functions.
Adopting a naming conversion such as lower case letters only for file naming is a good
practice that ensures maximum cross platform compatibility.
Page 55
CSE Dept., CMREC
It comes in handy when we want to know if a file exists or not before processing it.
This function can also be used when creating a new file and user wants to ensure that
the file does not already exist on the server.
<?php
file_exists($filename);
?>
HERE,
“file_exists()” is the PHP function that returns true if the file exists and false if it does
not exist.
“$file_name” is the path and name of the file to be checked
Page 56
CSE Dept., CMREC
C 1.47 PHP code uses file_exists function to determine if the file my_settings.txt exists.
<?php
if (file_exists('my_settings.txt'))
else
?>
The fopen function is used to open files. It has the following syntax
<?php
fopen($file_name,$mode,$use_include_path,$context);
?>
HERE,
Page 57
CSE Dept., CMREC
<?php
?>
HERE,
PHP provides various functions to read data from file. There are different functions that allows to
read all file data, read data line by line and read data character by character.
Page 58
CSE Dept., CMREC
fread()
fgets()
fgetc()
C 1.48 PHP code for reading the content of a file using fread()
<?php
$filename = "c:\\file1.txt";
Output:
Page 59
CSE Dept., CMREC
The PHP fgets() function is used to read single line from the file.
?>
Output
The PHP fgetc() function is used to read single character from the file. To get all data using
fgetc() function, use !feof() function inside the while loop.
C 1.50 PHP code to demonstrate the working of opening of a file in read mode using fgetc()
<?php
feof($fp)) {
echo fgetc($fp);
fclose($fp);
?>
Output:
Page 60
CSE Dept., CMREC
• Function readfile() => is a simple function used to read the data from a file without
doing any further text processing like calculating the size of data.
• Function fread() => also do the same thing but with the difference that the
programmer can specify the size of the data to be read from the file. This can be
helpful when there are larger files and user wants to read some chunks of data from it.
<?php
fclose($handle); ?>
The PHP fwrite() function is used to write and append data into file.
$fp = fopen('data.txt', 'a');//opens file in append mode fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data'); fclose($fp);
echo "File appended successfully";
?>
Output: data.txt
Page 61
CSE Dept., CMREC
Deleting a file
The unlink function is used to delete the file. The code below illustrates the implementation.
if (!unlink('my_settings_backup.txt'))
else
?>
Page 62
CSE Dept., CMREC
<?php
$fp = fopen("file", "rb");
$data = fread($fp, 4);
// 4 is the byte size of a whole on a 32-bit PC.
$number = unpack("i", $data);
echo $number[1];
?>
Page 63