B.SC WebApplications Development Using PHP &MYSQL
B.SC WebApplications Development Using PHP &MYSQL
Sc
WebApplications Development
using PHP &MYSQL
P.Y.KUMAR
B.Sc
UNIT-I
The building blocks of PHP: Variables, Data Types, Operators
and Expressions, Constants. Flow Control Functions in PHP:
Switching Flow, Loops, Code Blocks and Browser Output.
Working with Functions: Creating functions, Calling functions,
Returning the values from User- Defined Functions, Variable
Scope, Saving state between Function calls with the static
statement, arguments of functions
UNIT-II
Working with Arrays: Creating Arrays, Some Array-Related
Functions. Working with Objects: Creating Objects, Accessing
g
Object Instances, Working with Strings, Dates and Time:
or
Formatting strings with PHP, Manipulating Strings with PHP,
s.
Using Date and Time Functions in PHP.
UNIT-III
te
da
Working with Forms: Creating Forms, Accessing Form Input
with User defined Arrays, Combining HTML and PHP code on
up
UNIT-IV
w
PHP stands for Hypertext Preprocessor. PHP is a powerful and widely-used open source
server-side scripting language to write dynamically generated web pages. PHP scripts are
executed on the server and the result is sent to the browser as plain HTML.
g
PHP can be integrated with the number of popular databases, including MySQL,
or
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
s.
PHP can be embedded within normal HTML web pages. That means inside your HTML
documents you'll have PHP statements like this:
te
da
Example
<html>
up
<head>
<title>PHP Application</title>
nu
</head>
<body>
<?php
.a
?>
w
</body>
</html>
w
If you're familiar with other server-side languages like ASP.NET or JSP, you might be
wondering what makes PHP so special. There are several advantages why one should choose
PHP over other languages. Here are some of them:
Easy to learn: PHP is easy to learn and use. For beginner programmers who just
started out in web development, PHP is often considered as the best and preferable
choice of scripting language to learn.
Open source: PHP is an open-source project — the language is developed and
maintained by a worldwide community of developers who make its source code freely
available to download and use. There are no costs associated with using PHP for
individual or commercial projects, including future updates.
Portability: PHP runs on various platforms such as Microsoft Windows, Linux, Mac
OS, etc. and it is compatible with almost all servers used today such Apache, IIS, etc.
Fast Performance: Scripts written in PHP usually execute faster than those written in
other scripting languages like ASP.NET or JSP.
g
Vast Community: Since PHP is supported by the worldwide community, finding
or
help or documentation for PHP online is extremely easy.
s.
Explain about Standard PHP Syntax?
te
A PHP script starts with the <?php and ends with the ?> tag.
da
The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to
up
treat the enclosed code block as PHP code, rather than simple HTML.
Example
nu
<?php
// Some code to be executed
.a
Every PHP statement end with a semicolon (;) — this tells the PHP engine that the end of the
w
PHP files are plain text files with .php extension. Inside a PHP file you can write HTML like
you do in regular HTML pages as well as embed PHP codes for server side execution.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A Simple PHP File</title>
</head>
<body>
<h1><?php echo "Hello, world!"; ?></h1>
</body>
</html>
The above example shows how you can embed PHP codes within HTML to create well-
formed dynamic web pages. If you view the source code of the resulting web page in your
browser, the only difference you will see is the PHP code <?php echo "Hello, world!"; ?> has
been replaced with the output "Hello, world!".
What happened here is? when you run this code the PHP engine executed the instructions
between the <?php … ?> tags and leave rest of the thing as it is. At the end the web server
send the final output back to your browser which is completely in HTML.
A comment is simply text that is ignored by the PHP engine. The purpose of comments is to
make the code more readable. It may help other developer (or you in the future when you edit
the source code) to understand what you were trying to do with the PHP.
g
Example
or
<?php
s.
// This is a single line comment
# This is also a single line comment
echo "Hello, world!";
te
da
?>
However to write multi-line comments, start the comment with a slash followed by an
up
asterisk (/*) and end the comment with an asterisk followed by a slash (*/), like this:
nu
Example
<?php
.a
/*
This is a multiple line comment block
w
one line
*/
w
Variables are used to store data, like string of text, numbers, etc. Variable values can change
over the course of a script. Here're some important things to know about variables:
• In PHP, a variable does not need to be declared before adding a value to it. PHP
automatically converts the variable to the correct data type, depending on its value.
• After declaring a variable it can be reused throughout the code.
• The assignment operator (=) used to assign value to a variable.
In the above example we have created two variables where first one has assigned with a
string value and the second has assigned with a number. Later we've displayed the variables
values in the browser using the echo statement. The PHP echo statement is often used to
output data to the browser. We will learn more about this in upcoming chapter.
g
or
These are the following rules for naming a PHP variable:
All variables in PHP start with a $ sign, followed by the name of the variable.
s.
A variable name must start with a letter or the underscore character _.
A variable name cannot start with a number. te
da
A variable name in PHP can only contain alpha-numeric characters and
underscores(A-z, 0-9, and _).
A variable name cannot contain spaces.
up
A constant is a name or an identifier for a fixed value. Constant are like variables except that
.a
one they are defined, they cannot be undefined or changed (except magic constants).
w
Constants are very useful for storing data that doesn't change while the script is running.
Common examples of such data include configuration settings such as database username and
w
Constants are defined using PHP's define() function, which accepts two arguments: the name
of the constant, and its value. Once defined the constant value can be accessed at any time
just by referring to its name. Here is a simple example:
Example
<?php
// Defining constant
define("SITE_URL", "https://www.tutorialrepublic.com/");
// Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>
The values assigned to a PHP variable may be of different data types including simple string
and numeric types to more complex data types like arrays and objects.
PHP supports total eight primitive data types: Integer, Floating point number or Float, String,
Booleans, Array, Object, resource and NULL. These data types are used to construct
variables. Now let's discuss each one of them in detail.
PHP Integers
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers can be
specified in decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or octal (base 8 -
prefixed with 0) notation, optionally preceded by a sign (- or +).
Example
<?php
g
$a = 123; // decimal number
or
var_dump($a);
echo "<br>";
s.
$b = -123; // a negative number
var_dump($b);
echo "<br>";
te
da
$c = 0x1A; // hexadecimal number
var_dump($c);
echo "<br>";
up
?>
.a
PHP Strings
w
Strings are sequences of characters, where every character is the same as a byte.
w
A string can hold letters, numbers, and special characters and it can be as large as up to 2GB
w
(2147483647 bytes maximum). The simplest way to specify a string is to enclose it in single
quotes (e.g. 'Hello world!'), however you can also use double quotes ("Hello world!").
Example
<?php
$a = 'Hello world!';
echo $a;
echo "<br>";
$b = "Hello world!";
echo $b;
echo "<br>";
$c = 'Stay here, I\'ll be back.';
echo $c;
?>
PHP Floating Point Numbers or Doubles
Floating point numbers (also known as "floats", "doubles", or "real numbers") are decimal or
fractional numbers, like demonstrated in the example below.
Example
<?php
$a = 1.234;
var_dump($a);
echo "<br>";
$b = 10.2e3;
var_dump($b);
echo "<br>";
$c = 4E-10;
var_dump($c);
?>
g
PHP Booleans
or
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).
s.
Example
<?php te
da
// Assign the value TRUE to a variable
$show_error = true;
up
var_dump($show_error);
?>
nu
PHP Arrays
.a
An array is a variable that can hold more than one value at a time. It is useful to aggregate a
series of related items together, for example a set of country or city names.
w
An array is formally defined as an indexed collection of data values. Each index (also known
w
Example
<?php
$colors = array("Red", "Green", "Blue");
var_dump($colors);
echo "<br>";
$color_codes = array(
"Red" => "#ff0000",
"Green" => "#00ff00",
"Blue" => "#0000ff"
);
var_dump($color_codes);
?>
PHP Objects
An object is a data type that not only allows storing data but also information on, how to
process that data. An object is a specific instance of a class which serve as templates for
objects. Objects are created based on this template via the new keyword.
Every object has properties and methods corresponding to those of its parent class. Every
object instance is completely independent, with its own properties and methods, and can thus
be manipulated independently of other objects of the same class.
Example
<?php
// Class definition
class greeting{
// properties
g
public $str = "Hello World!";
or
// methods
function show_greeting(){
s.
return $this->str;
}
}
// Create object from class te
da
$message = new greeting;
var_dump($message);
up
?>
nu
PHP NULL
The special NULL value is used to represent empty variables in PHP. A variable of type
.a
NULL is a variable without any data. NULL is the only possible value of type null.
w
Example
w
<?php
w
$a = NULL;
var_dump($a);
echo "<br>";
$b = "Hello World!";
$b = NULL;
var_dump($b);
?>
When a variable is created without a value in PHP like $var; it is automatically assigned a
value of null. Many novice PHP developers mistakenly considered both $var1 = NULL; and
$var2 = ""; are same, but this is not true. Both variables are different — the $var1 has null
value while $var2 indicates no value assigned to it.
PHP Resources
A resource is a special variable, holding a reference to an external resource.
Resource variables typically hold special handlers to opened files and database connections.
Example
<?php
// Open a file for reading
$handle = fopen("note.txt", "r");
var_dump($handle);
echo "<br>";
// Connect to MySQL database server with default setting
$link = mysql_connect("localhost", "root", "");
var_dump($link);
?>
Q) What is Operators in PHP?
Operators are symbols that tell the PHP processor to perform certain actions. For example,
the addition (+) symbol is an operator that tells PHP to add two variables or values, while the
greater-than (>) symbol is an operator that tells PHP to compare two values.
g
The following lists describe the different operators used in PHP.
or
PHP Arithmetic Operators
s.
The arithmetic operators are used to perform common arithmetical operations, such as
te
addition, subtraction, multiplication etc. Here's a complete list of PHP's arithmetic operators:
da
Operator Description Example Result
up
The following example will show you these arithmetic operators in action:
Example
<?php
$x = 10;
$y = 4;
echo($x + $y); // 0utputs: 14
echo($x - $y); // 0utputs: 6
echo($x * $y); // 0utputs: 40
echo($x / $y); // 0utputs: 2.5
echo($x % $y); // 0utputs: 2
?>
UNIT-1
PHP Assignment Operators
= Assign $x = $y $x = $y
g
/= Divide and assign quotient $x /= $y $x = $x / $y
or
%= Divide and assign modulus $x %= $y $x = $x % $y
s.
te
The following example will show you these assignment operators in action:
da
Example
up
<?php
$x = 10;
echo $x; // Outputs: 10
nu
$x = 20;
$x += 30;
.a
$x -= 20;
w
$x *= 25;
echo $x; // Outputs: 125
$x = 50;
$x /= 10;
echo $x; // Outputs: 5
$x = 100;
$x %= 15;
echo $x; // Outputs: 10
?>
The comparison operators are used to compare two values in a Boolean fashion.
UNIT-1
Operator Name Example Result
g
or
> Greater than $x > $y True if $x is greater than $y
s.
>= Greater than or equal to $x >= $y True if $x is greater than or equal to $y
Example
nu
<?php
$x = 25;
.a
$y = 35;
w
$z = "25";
var_dump($x == $z); // Outputs: boolean true
w
The following example will show you these increment and decrement operators in action:
Example
g
<?php
or
$x = 10;
echo ++$x; // Outputs: 11
s.
echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10
te
da
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
up
?>
w
The following example will show you these logical operators in action:
Example
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
echo "$year is a leap year.";
} else{
g
echo "$year is not a leap year.";
or
}
?>
s.
PHP String Operators
te
There are two operators which are specifically designed for strings.
da
Operator Description Example Result
up
The following example will show you these string operators in action:
w
w
Example
w
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>
PHP Array Operators
Non-
!== $x !== $y True if $x is not identical to $y
identity
g
or
The following example will show you these array operators in action:
s.
Example
te
da
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
up
PHP 7 introduces a new spaceship operator (<=>) which can be used for comparing two
expressions. It is also known as combined comparison operator.
The spaceship operator returns 0 if both operands are equal, 1 if the left is greater, and -1 if
the right is greater. It basically provides three-way comparison as shown in the following
table:
The following example will show you how spaceship operator actually works:
Example
<?php
g
// Comparing Integers
or
echo 1 <=> 1; // Outputs: 0
echo 1 <=> 2; // Outputs: -1
s.
echo 2 <=> 1; // Outputs: 1
// Comparing Floats
echo 1.5 <=> 1.5; // Outputs: 0
te
da
echo 1.5 <=> 2.5; // Outputs: -1
echo 2.5 <=> 1.5; // Outputs: 1
// Comparing Strings
up
Like most programming languages, PHP also allows you to write code that perform different
w
actions based on the results of a logical or comparative test conditions at run time. This
means, you can create test conditions in the form of expressions that evaluates to either true
w
or false and based on these results you can perform certain actions.
There are several statements in PHP that you can use to make decisions:
The if statement
The if...else statement
The if...elseif ....else statement
The switch .. case statement
We will explore each of these statements in the coming sections.
UNIT-1
The if Statement
The if statement is used to execute a block of code only if the specified condition evaluates to
true. This is the simplest PHP's conditional statements and can be written like:
if(condition)
{
// Code to be executed
}
The following example will output "Have a nice weekend!" if the current day is Friday:
Example
<?php
g
$d = date("D");
or
if($d == "Fri"){
echo "Have a nice weekend!";
s.
}
?>
te
da
The if...else Statement
up
You can enhance the decision making process by providing an alternative choice through
adding an else statement to the if statement. The if...else statement allows you to execute one
nu
block of code if the specified condition is evaluates to true and another block of code if it is
evaluates to false. It can be written, like this:
.a
if(condition){
w
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!"
Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
UNIT-1
The if...elseif...else Statement
The if...elseif...else a special statement that is used to combine multiple if...else statements.
if(condition){
// Code to be executed if condition is true
} elseif(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday, otherwise it will output "Have a nice
g
day!"
or
Example
s.
<?php
$d = date("D");
if($d == "Fri"){ te
da
echo "Have a nice weekend!";
} elseif($d == "Sun"){
up
The ternary operator provides a shorthand way of writing the if...else statements. The ternary
w
operator is represented by the question mark (?) symbol and it takes three operands: a
condition to check, a result for ture, and a result for false.
Example
<?php
if($age < 18){
echo 'Child'; // Display Child if age is less than 18
} else{
echo 'Adult'; // Display Adult if age is greater than or equal to 18
}
?>
UNIT-1
Using the ternary operator the same code could be written in a more compact way:
Example
<?php echo ($age < 18) ? 'Child' : 'Adult'; ?>
The ternary operator in the example above selects the value on the left of the colon (i.e.
'Child') if the condition evaluates to true (i.e. if $age is less than 18), and selects the value on
the right of the colon (i.e. 'Adult') if the condition evaluates to false.
Switch…Case
The switch-case statement is an alternative to the if-elseif-else statement, which does almost
the same thing. The switch-case statement tests a variable against a series of values until it
finds a match, and then executes the block of code corresponding to that match.
g
switch(n){
or
case
s.
label1:
// Code to be executed if
n=label1 break; te
da
case label2:
// Code to be executed if
up
n=label2 break;
...
nu
default:
// Code to be executed if n is different from all labels
.a
}
w
Consider the following example, which display a different message for each day.
w
Example
w
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
UNIT-1
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?>
g
The switch-case statement differs from the if-elseif-else statement in one important way. The
or
switch statement executes line by line (i.e. statement by statement) and once PHP finds a case
statement that evaluates to true, it's not only executes the code corresponding to that case
s.
statement, but also executes all the subsequent case statements till the end of the switch block
automatically.
te
da
To prevent this add a break statement to the end of each case block. The break statement tells
PHP to break out of the switch-case statement block once it executes the code associated with
the first true case.
up
Loops are used to execute the same block of code again and again, until a certain condition is
met. The basic idea behind a loop is to automate the repetitive tasks within a program to save
.a
the time and effort. PHP supports four different types of loops.
w
while — loops through a block of code until the condition is evaluate to true.
w
do…while — the block of code executed once and then condition is evaluated. If the
w
condition is true the statement is repeated as long as the specified condition is true.
for — loops through a block of code until the counter reaches a specified number.
foreach — loops through a block of code for each element in an array.
You will also learn how to loop through the values of array using foreach() loop at the end of
this chapter. The foreach() loop work specifically with arrays.
The while statement will loops through a block of code until the condition in the while
statement evaluate to true.
UNIT-1
while(condition){
// Code to be executed
}
The example below define a loop that starts with $i=1. The loop will continue to run as long
as $i is less than or equal to 3. The $i will increase by 1 each time the loop runs:
Example
<?php
$i = 1;
while($i <= 3){
$i++;
echo "The number is " . $i . "<br>";
}
g
?>
or
PHP do…while Loop
s.
The do-while loop is a variant of while loop, which evaluates the condition at the end of each
te
loop iteration. With a do-while loop the block of code executed once, and then the condition
is evaluated, if the condition is true, the statement is repeated as long as the specified
da
condition evaluated to is true.
up
do{
// Code to be executed
}
nu
while(condition);
.a
The following example define a loop that starts with $i=1. It will then increase $i with 1, and
w
print the output. Then the condition is evaluated, and the loop will continue to run as long as
$i is less than, or equal to 3.
w
w
Example
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
The while loop differs from the do-while loop in one important way — with a while loop, the
condition to be evaluated is tested at the beginning of each loop iteration, so if the conditional
expression evaluates to false, the loop will never be executed.
UNIT-1
With a do-while loop, on the other hand, the loop will always be executed once, even if the
conditional expression is false, because the condition is evaluated at the end of the loop
iteration rather than the beginning.
The for loop repeats a block of code until a certain condition is met. It is typically used to
execute a block of code for certain number of times.
g
initialization — it is used to initialize the counter variables, and evaluated once
or
unconditionally before the first execution of the body of the loop.
s.
condition — in the beginning of each iteration, condition is evaluated. If it evaluates
to true, the loop continues and the nested statements are executed. If it evaluates to
false, the execution of the loop ends.
te
increment — it updates the loop counter with a new value. It is evaluate at the end of
da
each iteration.
up
The example below defines a loop that starts with $i=1. The loop will continued until $i is
less than, or equal to 5. The variable $i will increase by 1 each time the loop runs:
nu
Example
.a
<?php
w
}
w
?>
foreach($array as $value){
// Code to be executed
}
The following example demonstrates a loop that will print the values of the given array:
UNIT-1
Example
<?php
$colors = array("Red", "Green", "Blue");
// Loop through colors array
foreach($colors as $value){
echo $value . "<br>";
}
?>
There is one more syntax of foreach loop, which is extension of the first.
g
// Code to be executed
or
}
s.
Example
<?php
$superhero = array( te
da
"name" => "Peter Parker",
"email" => "[email protected]",
up
"age" => 18
);
nu
}
w
?>
Q)
w
A code block in PHP is a group of one or more lines of code that are grouped together and
usually enclosed within curly braces { }. Code blocks are commonly used in:
• Functions
• Conditional statements (if, else)
• Loops (while, for, foreach)
Explanation:
• The { ... } part after the if and else contains code blocks.
• These code blocks execute only when the condition is true or false, respectively.
Browser Output is the visible result shown in a web browser after PHP code is executed
on the server.
g
<?php
$name = "Kumar";
or
echo "Welcome, " . $name . "!";
?>
s.
Output in Browser:
te
da
Welcome, Kumar!
up
Explanation:
echo
• PHP code is not shown in the browser — only the result is.
.a
PHP has a huge collection of internal or built-in functions that you can call directly within
your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc.
Please check out PHP reference section for a complete list of useful PHP built-in functions.
In addition to the built-in functions, PHP also allows you to define your own functions. It is a
way to create reusable code packages that perform specific tasks and can be kept and
maintained separately form main program. Here are some advantages of using functions:
UNIT-1
Functions reduces the repetition of code within a program — Function allows you
to extract commonly used block of code into a single component. Now can you can
perform the same task by calling this function wherever you want without having to
copy and paste the same block of code again and again.
Functions makes the code much easier to maintain — Since a function created
once can be used many times, so any changes made inside a function automatically
implemented at all the places without touching the several files.
Functions makes it easier to eliminate the errors — When the program is
subdivided into functions, if any error occur you know exactly what function causing
the error and where to find it. Therefore, fixing errors becomes much easier.
Functions can be reused in other application — Because a function is separated
from the rest of the script, it's easy to reuse the same function in other applications
just by including the php file containing those functions.
g
The following section will show you how easily you can define your own function in PHP.
or
Creating and Invoking Functions
s.
te
The basic syntax of creating a custom function can be give with:
da
function functionName(){
// Code to be executed
}
up
The declaration of a user-defined function start with the word function, followed by the name
nu
of the function you want to create followed by parentheses i.e. () and finally place your
function's code between curly brackets {}.
.a
Example
<?php
w
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>
Note:A function name must start with a letter or underscore character not with a number,
optionally followed by the more letters, numbers, or underscore characters. Function names
are case-insensitive.
UNIT-1
Functions with Parameters
You can specify parameters when you define your function to accept input values at run time.
The parameters work like placeholder variables within a function; they're replaced at run time
by the values (known as argument) provided to the function at the time of invocation.
You can define as many parameters as you like. However for each parameter you specify, a
corresponding argument needs to be passed to the function when it is called.
The getSum() function in following example takes two integer values as arguments, simply
add them together and then display the result in the browser.
g
or
Example
s.
<?php
// Defining function
function getSum($num1, $num2){
$sum = $num1 + $num2; te
da
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
up
// Calling function
getSum(10, 20);
nu
?>
You can also create functions with optional parameters — just insert the parameter name,
followed by an equals (=) sign, followed by a default value, like this.
Example
<?php
// Defining function
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello,
world!</p>";
}
// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>
UNIT-1
As you can see the third call to customFont() doesn't include the second argument. This
causes PHP engine to use the default value for the $size parameter which is 1.5.
Returning Values from a Function
A function can return a value back to the script that called the function using the return
statement. The value may be of any type, including arrays and objects.
Example
<?php
// Defining function
function getSum($num1, $num2){
$total = $num1 + $num2;
return $total;
}
g
// Printing returned value
or
echo getSum(5, 10); // Outputs: 15
?>
s.
A function can not return multiple values. However, you can obtain similar results by
te
returning an array, as demonstrated in the following example.
da
Passing Arguments to a Function by Reference
In PHP there are two ways you can pass arguments to a function: by value and by reference.
up
By default, function arguments are passed by value so that if the value of the argument within
the function is changed, it does not get affected outside of the function. However, to allow a
nu
Example
w
<?php
/* Defining a function that multiply a number
w
However, you can declare the variables anywhere in a PHP script. But, the location of the
declaration determines the extent of a variable's visibility within the PHP program i.e. where
the variable can be used or accessed. This accessibility is known as variable scope.
By default, variables declared within a function are local and they cannot be viewed or
manipulated from outside of that function, as demonstrated in the example below:
Example
<?php
// Defining function
function test(){
$greet = "Hello World!";
g
echo $greet;
or
}
test(); // Outputs: Hello World!
s.
echo $greet; // Generate undefined variable error
?>
te
da
Similarly, if you try to access or import an outside variable inside the function, you'll get an
undefined variable error, as shown in the following example:
up
Example
nu
<?php
$greet = "Hello World!";
.a
// Defining function
function test(){
w
echo $greet;
}
w
As you can see in the above examples the variable declared inside the function is not
accessible from outside, likewise the variable declared outside of the function is not
accessible inside of the function. This separation reduces the chances of variables within a
function getting affected by the variables in the main program.
UNIT-1
The global Keyword
There may be a situation when you need to import a variable from the main program into a
function, or vice versa. In such cases, you can use the global keyword before the variables
inside a function. This keyword turns the variable into a global variable, making it visible or
accessible both inside and outside the function, as show in the example below:
Example
<?php
$greet = "Hello World!";
// Defining function
function test(){
global $greet;
echo $greet;
g
}
or
test(); // Outpus: Hello World!
echo $greet; // Outpus: Hello World!
s.
// Assign a new value to variable
$greet = "Goodbye";
test(); // Outputs: Goodbye
te
da
echo $greet; // Outputs: Goodbye
?>
Q) Saving State Between Function Calls Using static in PHP
up
In PHP, the static keyword allows a local variable inside a function to retain its value
nu
Syntax:
w
function myFunction() {
static $var = initial_value;
w
counter(); // Count: 1
counter(); // Count: 1
counter(); // Count: 1
?>
Explanation:
Each time the function is called, $count is reset to 0. So the output is always 1.
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
?>
Explanation:
g
• So $count increases with each call: 1, 2, 3...
or
s.
Q) Explain about PHP arrays?
An array is a data structure that stores one or more similar type of values in a single value.
te
For example if you want to store 100 numbers then instead of defining 100 variables its easy
to define an array of 100 length.
da
There are three different kind of arrays and each array value is accessed using an ID c which
up
Numeric array − An array with a numeric index. Values are stored and accessed in
nu
linear fashion.
Associative array − An array with strings as index. This stores element values in
.a
association with key values rather than in a strict linear index order.
w
Multidimensional array − An array containing one or more arrays and values are
w
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function
reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as
$value ) { echo "Value is
$value <br />";
}
foreach( $numbers as
$value ) { echo "Value is
$value <br />";
}
?>
</body>
</html>
g
This will produce the following result −
or
Value is 1
Value is 2
s.
Value is 3
Value is 4
Value is 5
Value is one
te
da
Value is two
Value is
threeValue
up
is four
Value is five
nu
Associative Arrays
.a
The associative arrays are very similar to numeric arrays in term of functionality but they are
w
different in terms of their index. Associative array will have their index as string so that you
can establish a strong association between key and values.
w
To store the salaries of employees in an array, a numerically indexed array would not be the
w
best choice. Instead, we could use the employees names as the keys in our associative array,
and the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would
not return any value.
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
g
or
</body>
</html>
s.
This will produce the following result −
Multidimensional Arrays
w
A multi-dimensional array each element in the main array can also be an array. And each
w
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
w
Example
In this example we create a two dimensional array to store marks of three students in three
subjects −
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"mohammad" =>
array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" =>
array (
"physics"
=> 30,
"maths" => 32,
"chemistry" => 29
),
"zara" =>
array (
"physics"
=> 31,
"maths" => 22,
g
"chemistry" => 39
)
or
);
s.
/* Accessing multi-dimensional
array values */ echo "Marks for
mohammad in physics : " ; te
da
echo $marks['mohammad']['physics'] . "<br />";
up
?>
</body>
w
</html>
w
reset($character);
This function is useful when you are performing multiple manipulations on an
array, such as sorting, extracting values, and so forth.
g
existing array, as in this example:
or
array_push($existingArray, "element 1", "element 2", "element
s.
3");
te
✓ array_pop() This function removes (and returns) the last element of an
existing array, as in this example:
da
$last_element = array_pop($existingArray);
up
an existing array, as in this example, where the value of the element in the
first position of $existingArray is assigned to the
w
variable $first_element:
w
$first_element = array_shift($existingArray);
✓ array_merge() This function combines two or more existing arrays, as
in this example:
$valuesArray = array_values($existingArray);
✓ shuffle() This function randomizes the elements of a given array. The
syntax of this function is simply as follows:
shuffle($existingArray);
g
Get The Length of a String
The PHP strlen() function returns the length of a string.
or
The example below returns the length of the string "Hello world!":
s.
Example
te
da
<html>
up
<body>
<?php
nu
</body>
</html>
w
Example
<html>
<body>
<?php
echo str_word_count("Hello world!");
?>
</body>
</html>
The output of the code above will be: 2.
Reverse a String
The PHP str_replace() function replaces some characters with some other characters in a
string.
The example below replaces the text "world" with "Dolly":
<html>
g
<body>
or
<?php
echo str_replace("world", "Dolly", "Hello world!");
s.
?>
</body>
</html> te
da
The output of the code above will be: Hello Dolly!
up
Example
.a
Replace the characters "world" in the string "Hello world!" with "Peter":
w
<html>
w
<body>
w
<?php
echo str_replace("world","Peter","Hello world!");
?>
</body>
</html>
<p>In this example, we search for the string "Hello World!", find the value "world"
and then replace the value with "Peter".</p>
In this example, we search for the string "Hello World!", find the value "world" and then
replace the value with "Peter".
Definition and Usage
The str_replace() function replaces some characters with some other characters in a string.
Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-
insensitive search.
g
Syntax
or
str_replace(find,replace,string,count)
s.
Parameter Description
find te
Required. Specifies the value to find
da
replace Required. Specifies the value to replace the
up
Syntax
w
str_repeat(string,repeat)
Parameter Description
repeat Required. Specifies the number of times the string will be repeated.
Must be greater or equal to 0
Example:
<html>
<body>
<?php echo str_repeat("shashish",8);
?>
</body>
</html>
g
Syntax
or
str_shuffle(string)
s.
Parameter Description
string te
Required. Specifies the string to shuffle
da
<html>
up
<body>
<?php
nu
each time.</p>
w
</body>
</html>
w
w
Output:
dolerW Hllo
Try to refresh the page. This function will randomly shuffle all characters each time.
Syntax
str_split(string,length)
Parameter Description
<html>
<body>
<?php print_r(str_split("Hello"));
?>
</body>
</html>
Output:
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )
g
PHP str_word_count() Function
or
Definition and Usage
s.
The str_word_count() function counts the number of words in a string.
te
da
Syntax
str_word_count(string,return,char)
up
Parameter Description
nu
Possible values:
w
w
Example:
<html>
<body>
<?php
echo str_word_count("Hello world!");
?>
</body>
</html>
Output:
Syntax
strcasecmp(string1,string2)
Parameter Description
g
string2 Required. Specifies the second string to compare
or
Example:
s.
<html>
<body> te
da
<?php
echo strcasecmp("Hello world!","HELLO WORLD!");
?>
up
</html>
.a
Output:
w
0
w
Syntax
strcmp(string1,string2)
Parameter Description
<?php
echo strcmp("Hello world!","Hello world!");
?>
</body>
</html>
Output:
g
or
PHP strtolower() Function
s.
Definition and Usage
Parameter Description
nu
<html>
<body>
w
<?php
w
</body>
</html>
Output:
hello world.
Syntax
strtoupper(string)
Parameter Description
<html>
<body>
<?php
echo strtoupper("Hello WORLD!");
?>
</body>
</html>
Output:
HELLO WORLD!
g
or
Definition and Usage
s.
The substr() function returns a part of a string.
Syntax
substr(string,start,length) te
da
Parameter Description
up
length Optional. Specifies the length of the returned string. Default is to the end of the
string.
Output:
World
PHP provides many functions that will transform a string argument, subtly or radically, as you'll
soon see.
g
also picked up white space at the beginning and end of your data.
or
The trim() function shaves any white space characters, including newlines, tabs, and spaces,
s.
from both the start and end of a string. It accepts the string to be modified, returning the cleaned-up
version. For example:
<?php
te
da
$text = "\t\tlots of room to breathe ";
echo "<pre>$text</pre>";
// prints " lots of room to breathe ";
up
$text = trim($text);
echo "<pre>$text</pre>";
// prints "lots of room to breathe";
nu
?>
.a
PHP provides two functions that allow you first to apply formatting, whether to round doubles to a
given number of decimal places, define alignment within a field, or display data according to
w
different number systems. In this section, you will look at a few of the formatting options provided
by printf() and sprintf().
w
Within the format control string (the first argument), we have included a special code, known as
a conversion specification.
A conversion specification begins with a percent (%) symbol and defines how to treat the
corresponding argument to printf(). You can include as many conversion specifications as you
want within the format control string, as long as you send an equivalent number of arguments
to printf().
The first conversion specification corresponds to the first of the additional arguments to printf(),
or 55. The second conversion specification corresponds to 66. The f following the percent symbol
requires that the data be treated as a floating-point number. This part of the conversion
specification is the type specifier.
g
Table 10.1. Type Specifiers
or
SpecifierDescription
d Display argument as a decimal number
s.
b Display an integer as a binary number
c Display an integer as ASCII equivalent
f
o te
Display an integer as a floating-point number (double)
Display an integer as an octal number (base 8)
da
s Display argument as a string
x Display an integer as a lowercase hexadecimal number (base 16)
X Display an integer as an uppercase hexadecimal number (base 16)
up
Listing 10.1 uses printf() to display a single number according to some of the type specifiers
nu
1: <?php
2: $number = 543;
w
g
or
s.
te
da
When specifying a color in HTML, you combine three hexadecimal numbers between 00 and FF,
representing the values for red, green, and blue. You can use printf() to convert three decimal
up
$green = 204;
$blue = 204;
printf("#%X%X%X", $red, $green, $blue);
.a
specifier is an integer that should be placed after the percent sign that begins a conversion
w
specification (assuming that no padding specifier is defined). The following fragment outputs a list
of four items, all of which sit within a field of 20 spaces. To make the spaces visible on the browser,
we place all our output within a pre element:
<?php
echo "<pre>";
printf("%20s\n", "Books");
printf("%20s\n", "CDs");
printf("%20s\n", "DVDs");
printf("%20s\n", "Games");
printf("%20s\n", "Magazines");
echo "</pre>";
?>
By default, output is right-aligned within the field you specify. You can make it left-aligned by
prepending a minus () symbol to the field width specifier:
g
printf("%-20s\n", "Left aligned");
or
Q) Explain about classes and objects in PHP?
s.
We can imagine our universe made of different objects like sun, earth, moon etc. Similarly
te
we can imagine our car made of different objects like wheel, steering, gear etc. Same way
there is object oriented programming concepts which assume everything as an object and
da
implement a software using different objects.
up
Before we go in detail, lets define important terms related to Object Oriented Programming.
nu
object.
w
In order to create a class, we group the code that handles a certain topic into one place. For
example, we can group all of the code that handles the users of a blog into one class, all of
thecode that is involved with the publication of the posts in the blog into a second class, and
all the code that is devoted to comments into a third class.
For the example given below, we are going to create a Car class into which we will group all
of the code which has something to do with cars.
class Car
{
g
// The code
or
}
□ We declare the class with the class keyword.
s.
□ We write the name of the class and capitalize the first letter.
integers, and booleans (true/false values), like any other variable. Let's add some properties to
the Car class.
nu
class Car {
public
.a
$comp;
public $color =
w
'beige'; public
$hasSunRoof = true;
w
}
w
We created the object $bmw from the class Car with the new keyword.
The process of creating an object is also known as instantiation.
We can create more than one object from the same class.
$bmw = new Car ();
In order to get a property, we write the object name, and then dash greater
than (->),and then the property name.
g
Note that the property name does not start with the $ sign; only the object
or
name startswith a $.
s.
Result: beigebeige
For example, in order to set the color to 'blue' in the bmw object:
nu
and in order to set the value of the $comp property for both objects:
.a
In order to get the color of the $bmw object, we use the following line of code:
Result: blue
We can also get the company name and the color of the second car object.
Result: beige
Mercedes Benz
How to add methods to a class?
The classes most often contain functions. A function inside a class is called a method. Here
we add the method hello() to the class with the prefix public.
class Car {
public
$comp;
public $color =
'beige'; public
$hasSunRoof = true;
g
We put the public keyword in front of a method.
or
The naming convention is to start the function name with a lower case letter.
s.
We can approach the methods similar to the way that we approach the properties, but we first need to
te
create at least one object from the class.
Result:
.a
beepbeep
w
<?php
// Declare the class
w
class Car {
// properties
public $comp;
public $color = 'beige';
public $hasSunRoof = true;
// method that
says hello public
function hello()
{
return "beep";
}
}
// Create an instance
$bmw = new Car ();
$mercedes = new Car ();
// Get the values
echo $bmw -> color; // beige echo "<br />";
echo $mercedes -> color; // beige echo "<hr />";
g
echo $mercedes -> hello();
or
// beep
s.
Q) Saving State Between Function Calls with the 'static' Statement ?
te
If you declare a variable within a function in conjunction with the
static statement, the variable remains local to the function, and the
da
function “remembers” the value of the variable from execution to
execution.
up
Example:
<?php
nu
function keep_track()
{
.a
STATIC $count = 0;
$count++;
w
print $count;
w
keep_track();
keep_track();
keep_track();
?>
// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>
g
Q)Explain about date and time functions.
or
The date/time functions allow you to get the date and time from the server
s.
where your PHP script runs. You can then use the date/time functions to
format the date and time in several ways.
The PHP Date() Function:-
te
The PHP date() function convert a timestamp to a more readable date and
da
time.
The computer stores dates and times in a format called UNIX Timestamp,
up
Ex:-
<?php
.a
$today = date("d/m/Y");
echo $today;
w
?>
Formatting the Dates and Times with PHP:-
w
echo($timestamp);
?>
The above example produce the following output.
g
1394003958
or
We can convert this timestamp to a human readable date
s.
through passing it to the previously introduce date() function.
Example:-
<?php te
da
$timestamp = 1394003958;
echo(date("F d, Y h:i:s", $timestamp));
up
?>
Example:-
<?php
// Create the timestamp for a particular
date
echo mktime(15, 20, 12, 5, 10, 2014);
?>
The PHPStrtotime() function:-
strtotime — passing any English textual datetime description
into a Unix timestamp.
Example :-
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
g
The date_sunset() function to return the sunset time for a
or
specified day and location.
Ex:-
s.
<?php
echo("Date: " . date("D M d Y"));
echo("<br>Sunrise time: "); te
da
echo(date_sunrise(time()));
echo("<br>Sunset time: ");
echo(date_sunset(time()));
up
?>
nu
g
or
s.
te
da
Listing 10.4. Acquiring Date Information with getdate()
1: <?php
2: $date_array = getdate(); // no argument passed so today's
up
5: }
6: ?>
.a
7: <hr/>
8: <?php
9: echo "<p>Today's date:
w
".$date_array['mon']."/".$date_array['mday']."/".
w
10: $date_array['year']."</p>";
11: ?>
w
Format
A am or pm (lowercase) am
A AM or PM (uppercase) AM
D Day of month (number with leading zeroes) 28
D Day of week (three letters) Tue
E Timezone identifier America/Los_Angeles
F Month name February
H Hour (12-hour formatleading zeroes) 06
H Hour (24-hour formatleading zeroes) 06
G Hour (12-hour formatno leading zeroes) 6
G Hour (24-hour formatno leading zeroes) 6
I Minutes 45
J Day of the month (no leading zeroes) 28
L Day of the week (name) Tuesday
L Leap year (1 for yes, 0 for no) 0
M Month of year (numberleading zeroes) 2
M Month of year (three letters) Feb
N Month of year (numberno leading zeroes) 2
S Seconds of hour 26
S Ordinal suffix for the day of the month th
R Full date standardized to RFC 822 Tue, 28 Feb 2006 06:45:26
(http://www.faqs.org/rfcs/rfc822.html) -0800
U Time stamp 1141137926
Y Year (two digits) 06
Y Year (four digits) 2006
Z Day of year (0365) 28
Z Offset in seconds from GMT -28800
g
or
s.
te
da
up
nu
.a
w
w
w
UNIT III
1. Working with Forms:
Creating Forms, Accessing Form Input with User defined
Arrays, Combining HTML and PHP code on a single Page,
Using Hidden Fields to save state, Redirecting the user,
Sending Mail on Form Submission, Working with File
Uploads.
g
variables, passing session IDs in the Query String,
or
Destroying Sessions and Unsetting Variables, Using Sessions
s.
in an Environment with Registered Users.
te
3.Working with Files and Directories: Including Files with
da
include(), Validating Files, Creating and Deleting Files,
Opening a File for Writing, Reading or Appending, Reading
up
1. GET method
2. POST method
g
Get and Post methods are the HTTP request methods used
or
inside the <form> tag to send form data to the server.
s.
HTTP protocol enables the communication between the client and
te
the server where a browser can be the client, and an application
running on a computer system that hosts your website can be the
da
server.
GET method
up
The GET method is used to submit the HTML FORM data. This
data is collected by the predefined $_GET variable for processing.
nu
POST method
Similar to the GET method, the POST method is also used to
.a
submit the HTML form data. But the data submitted by this
w
Note that the "post" method is more secure than the "get"
w
method because the data sent using the POST method is not
visible to user.
$_REQUEST variable
<tr>
<td>GENDER
g
<input type="radio" name="gender" value="M">MALE
or
<input type="radio" name="gender" value="F">FEMALE
<tr>
s.
<td>AREA OF INTERESTS
<input type="checkbox" name="interests[]" value="cricket">cricket
te
<input type="checkbox" name="interests[]" value="football">foot ball
da
<input type="checkbox" name="interests[]" value="volleyball">volley ball
<tr>
<td><input type="submit">
up
</td></table>
nu
</form>
<?php
$stnum=$_POST['sno'];
w
$sname=$_POST['sn
ame'];echo "<br>";
echo "name is
".$sname;
$sclass=$_POST['studentc
lass'];
echo "<br>"; echo "class
is".$sclass;
$gen=$_POST['g
ender'];
echo "<br>"; echo"gender is".$gen;
$intr=$_POST['interests']; echo "<br>";
foreach($intr as $chk1)
{
echo"intrests".$chk1.",";
}?>
When we run the forms1.php the BELOW out put is formed
g
or
s.
te
da
up
nu
.a
w
w
w
<td><input type="submit"></td>
Create hidden3.php
<? php
$a=$_POST['snum'];
$b=$_POST['stname'];
echo "your number is".$a; echo "<br>";
echo "<br>";
echo "your name is".$b;
?>
g
or
s.
te
da
up
nu
.a
w
w
w
g
or
s.
Q) Accessing Form Input with User-Defined Arrays
<html> te
da
<head>
<title>A simple HTML form</title>
</head>
up
<body>
<form action="send_simpleform.php" method="POST">
<p><strong>Name:</strong><br/>
nu
</form>
</body>
w
</html>
Reading Input from a Form
w
<?php
echo "<p>Welcome <b>".$_POST["user"]."</b>!</p>";
echo "<p>Your message
is:<br/><b>".$_POST["message"]."</b></p>";
?>
g
<title>An HTML form including a SELECT element</title>
or
</head>
<body>
s.
<form action="send_formwithselect.php" method="POST">
<p><strong>Name:</strong><br/>
<input type="text" name="user"/>
<p><strong>Select Some Products:</strong><br/>te
da
<select name="products[]" multiple="multiple">
<option value="Sonic Screwdriver">Sonic Screwdriver</option>
<option value="Tricoder">Tricorder</option>
up
</body>
</html>
w
<?php
w
g
Q) Sending mail on form submission
or
Before sending email , we must make sure whether the system is properly
s.
configured
te
System configuration for the mail ( ) function :
da
We can use the mail ( ) function to send mail, a few directives
up
properly.
nu
[mail function ]; for win 32 only SMTP = localhost ; for win 32 only
w
php.
<html>
<head>
<title> email form </ title>
</head >
<body>
<form action = “ sendmail.php” method = “post”>
<p> name :<br> <input type = “text” size =”25” name =
“name”> </p>
<p> e-mail addres :<br>
<input type = “ text” size = “25” name= “email”> </p>
<p> message :<br>
<textarea name = “message” cols = “30” rows= “5”></text
area > </p >
< p > < input type = “ submit” value = “send” > < /p >
< /form >
< /body >
< / html >
Now, create a script that sends this form to recipient
g
< title > sending mail < / title >
or
</ head >
< body >
s.
<? php
echo “ < p > thankyou”;
te
$ _post [“ name”]. for ur message </p>” ;
echo “ < p > your mail address is” .$_post [“email“ ] </p>” ;
da
echo “ < p > your message was : < br >” ;
echo $_post [ “ message “ ] .“ < /p>”;
up
?>
w
</body >
< /html >
g
or
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
s.
temporary directory and then relocated to a target destination by
a PHP script
te
da
First we need to create the HTML .HTML forms that include file
upload fields must include an ENCTYPE ARGUMENT:
up
ENCTYPE= ”mulitipart/form-data”
nu
.a
g
or
s.
te
da
up
nu
.a
w
w
w
Working With Files and Directories
Topics:
Include statement
Validating files
Getting date information about file
Opening files
Reading from files
Writing or appending to files
Locking files
Working with directories
g
or
Running unix commands with php functions
s.
Including files with include ()
te
The include() statement enables you to incorporate other files into your
da
PHP document. The include() requires a single argument, a relative path to
the file to be included.
The following example creates a simple PHP script that uses include()
up
<?php
include (“myinclude.php”);
.a
?>
w
?>
If we run the above PHP code the following output is displayed. I
have been included
Included files in PHP can return a value in the same way as functions do.
Example:
<?php
$res=include (“returnvalue.php”);
echo “the included file returned”. $res;
?>
An include file that returns a value returnvalue.php
<? Php
$r=(4+4);
return $r;
?>
Output:- the included file returned 8.
Validating Files:-
✓ checking a file for existence with file _exists ().
✓ we can test for the existence of a file with file_exists() function.
✓ The function requires file name as its argument. If file is found
the function returns true otherwise false.
g
if (file_exists(“test.txt”))
or
{
s.
echo “the file exists”;
}
te
da
Checking A File Or Directory:-
up
✓ you can confirm that the entity you are testing is a file using
is_file() function.
nu
✓ This is_file() function requires file path and returns boolean value.
.a
if(is_file(“test.txt”))
{
w
}
w
We can check that the entity we are testing is a directory using is_dir()
if(is_dir(“/tmp”))
{
echo “/tmp is a directiory”;
}
The is_readable() function tells you whether you can read a file.
It accepts file path as argument and returns a Boolean value.
if(is_readable(“test.txt”))
}
The is_writable() function tells whether you have proper
permission to write a file.This function also accepts file path and
returns a Boolean vale.
if(is_writable(“test.txt”))
g
or
echo “this file is writable”;
s.
}
te
The is_executable() function tells you whether you can execute the
da
file. The function accepts file path and returns a boolean value.
Q) Getting Date information about file
up
Some times we need to know when a file was last written or accessed.
nu
function.
w
Ex:
$atime=fileatime(“test.txt”);
echo “test.txt was last accesed on”.date(“D d m y”,$atime);
Ex:- $t=filemtime(“test.txt”);
echo “test.txt was last accesed on”.date(“D d m y”,$t);
PHP enables you to test the change time of a document with
filectime() function.
Ex:- $ctime=filectime(“test.txt”);
echo “test.txt was last accesed on”.date(“D d m y”,$ctime);
Q) Operations on Files
Creating And Deleting Files:-
If a file does not exist,we can create it with touch() function.
Given a string representing filepath ,touch() creates an empty file of that
name.
If the file already exists its contents are not disturbed but modification date
will be updated.
touch(“myfile.txt”);
g
we can remove an existing file with unlink() function.unlink() function also
or
accepts file path.
s.
unlink(“myfile.txt”);
te
Opening a File for Writing,Reading or Appending:-
da
Before we work with files ,we first open it for reading or writing or to
perform both tasks.
up
The fopen() function requires a file resource so that we can use later.
w
$fp=fopen(“test.txt”,”r”);
To open a file for writing
$fp=fopen(“test.txt”,”w”);
To open a file for appending
$fp=fopen(“test.txt”,”a”);
fopen() function returns false if file cannot be opened for some reason.
After opening and working with a file, you should close it by using the
The feof() function does this by returning true when end of file been
reached and false otherwise.
g
or
The feof() function requires file resource as its argument.
s.
Ex:-opening and reading a file line by line.
<?php
te
da
$filename=”test.txt”;
up
$fp=fopen($filename,”r”) or
nu
while(!feof($fp)) {
.a
$line=
w
fgets($
w
fp,102
4);
w
echo
$line.
”<br>”
;
}
?>
<?php
$filename=”test.txt”;
$fp=fopen($filename,”r”) or die(“could not open file”);
while(!feof($fp))
{
$char=fgets($fp); echo $char.”<br>”;
}
?>
The process for writing and appending to a file are same, the difference
lies in the mode you call fopen() function.
g
or
When you write to a file, you use the mode argument “w” ,when you call
fopen().
s.
$fp=fopen(“test.txt”,”w”);
te
da
When we append to file ,use the mode “a” in fopen().
up
$fp=fopen(“test.txt”,”a”);
nu
fwrite($fp,”hello world”);
fputs($fp,”hello world”);
ex:-
<?php
$filename=”test.txt”;
$fp=fopen($filename) or die(“could not open”);
fwrite($fp,”hello world”);
fclose($fp);
echo “Appending………”;
$fp=fopen($filename,”a”) or die(“could not open”);
fputs($fp,”and another thing\n”);
fclose($fp);
?>
g
LOCK_SH 1 Shared Allow other processes to read the file
or
not writing.
s.
LOCK_EX 2 Exclusive Prevents other processes for reading
and writing
LOCK_UN 3 Release te
Release a shared or exclusive lock.
da
We should call flock () directly after calling fopen() and then call it
up
fclose($fp);
?>
w
w
mkdir(“testdir”,07555);
Removing directory with rmdir():-
g
The readdir() function requires a directory handle and returns a string
containing the item name.If the end of directory is reached, readdir()
or
returns false.
s.
Ex:-
<?php
$dirname=”vig”;
te
da
$dh=opendir($dirname) or die(“can not open”);
up
while(!($file=readdir($dh)==false))
{
nu
if(is_dir(“dirname/$file”))
{
.a
echo “Dir”;
w
}
w
else
w
echo $file.”<br>”;
}
closedir($dh);
?>
Running unix commands with php Running
Commands with exec():-
The exec() function is one of several functions we can use to pass
commands
to shell. The below example uses exec() function to produce a directory
listing with shell based command.
<?php
exec(“ls”,$out-array,$res);
echo “Returned:”.$res.”<br>”;
foreach($out_array as $o)
{
echo $o.”<br>”;
}
?>
Running command with system() or passthru():-
The system() function differs from exec() in that it outputs
information directly to the browser without programmatic
intervention.
g
but it behaves differently.When using passthru() any output from
or
shell command is not buffered on its way back to you.
s.
Q) What is Exception Handling in PHP?
te
Exception handling in PHP is a way to gracefully manage errors in your program.
da
Instead of stopping the entire script when an error occurs, PHP allows you to "catch"
the error and take action — such as showing a friendly error message, logging the
error, or retrying the operation.
up
nu
Syntax:
try {
// Code that may throw an exception
} catch (Exception $e) {
// Code to handle the exception
} finally {
// (Optional) Code that always runs
}
Simple Example:
<?php
function divide($a, $b)
{
if ($b == 0)
{
throw new Exception("Division by zero is not
allowed.");
}
return $a / $b;
}
try
{
echo divide(10, 2) . "<br>"; // 5
echo divide(10, 0); // This will throw an exception
}
catch (Exception $e)
{
echo "Caught exception: " . $e->getMessage();
}
Finally
{
echo "<br>Execution completed.";
}
g
?>
or
s.
Output:
5
te
Caught exception: Division by zero is not allowed.
Execution completed.
da
Real-world Example: File Open
up
<?php
try {
nu
Topics:-
g
Creating Cookie with PHP
or
What is a Cookie?
s.
✓ A cookie is often used to identify a user.
te
✓ A cookie is a small file that the server embeds on the user's
da
computer.
✓ Each time the same computer requests a page with a
up
browser, it will send the cookie too. With PHP, you can
both create and retrieve cookie values.
nu
(OR)
Syntax
setcookie(name, value, expire, path, domain, secure,
httponly);
Only the name parameter is required. All other parameters are optional.
Parameter Description
name The name of the cookie.
value The value of the cookie. Do not store sensitive information
g
since this value is stored on the user's computer.
or
expires The expiry date in UNIX timestamp format. After this time
s.
cookie will become inaccessible. The default value is 0.
path
te
Specify the path on the server for which the cookie will be
available. If set to /, the cookie will be available within the entire
da
domain.
up
domain Specify the domain for which the cookie is available to e.g
www.example.com.
nu
secure This field, if present, indicates that the cookie should be sent
only if a secure HTTPS connection exists.
.a
w
w
w
Example : cookies.php
<?php
$cookie_name = "COMPUTERS";
$cookie_value = "CLUSTER PAPER";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); //
86400 = 1 day
?>
<html>
<body>
<?php if(!isset($_COOKIE[$cookie_name]))
{
echo "Cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "Cookie '" . $cookie_name . "' is set!<br>"; echo
"Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Output:
g
or
s.
te
da
up
nu
.a
w
w
w
Example2 :checkcookie.php
<?php
setcookie("test_cookie", "test");
?>
<html>
<body>
<?php if(count($_COOKIE) > 0)
{
echo "Cookies are enabled.";
}
else
{
echo "Cookies are disabled.";
}
?>
</body>
</html>
Output:
g
or
s.
Q) Removing Cookies
te
You can delete a cookie by calling the same setcookie() function
da
with the cookie name and any value (such as an empty string)
however this time you need the set the expiration date in the
up
<?php
.a
?>
w
w
Q) Setting a Cookie with PHP ?
You can set a cookie in a PHP script in two ways. First, you could use
the header() function to set the Set-Cookie header.
The header() function requires a string that will then be included in
the header section of the server response. Because headers are sent
automatically for you, header() must be called before any output at all
is sent to the browser:
g
thatsetcookie().
or
The setcookie() function does what its name suggestsit outputs a Set-
s.
Cookie header. For this reason, it should be called before any other
content is sent to the browser. The function accepts the cookie
te
name, cookie value, expiration date in UNIX epoch format, path,
domain, and integer that should be set to 1 if the cookie is only to be
da
sent over a secure connection. All arguments to this function are
optional apart from the first (cookie name) parameter.
up
<?php
.a
if (isset($_COOKIE["vegetable"]))
{ echo "<p>Hello again, you have chosen:
w
".$_COOKIE["vegetable"].".</p>";
}
w
We set the cookie name to "vegetable" on line 2 and the cookie value to "artichoke". We
use the time() function to get the current time stamp and add 3600 to it (there are 3,600
seconds in an hour). This total represents our expiration date. We define a path of "/", which
means that a cookie should be sent for any page within our server environment. We set the
domain argument to ".yourdomain.com" (you should make the change relevant to your own
domain or use localhost), which means that a cookie will be sent to any server in that group.
Finally, we pass 0 to setcookie(), signaling that cookies can be sent in an insecure
environment.
Passing setcookie() an empty string ("") for string arguments or 0 for integer fields causes
these arguments to be skipped.
By the Way
With using a dynamically created expiration time in a cookie, as in Listing 12.1, note the
expiration time is created by adding a certain number of seconds to the current system time of
the machine running Apache and PHP. If this system clock is not accurate, it is possible that it
may send in the cookie an expiration time that has already passed.
You can view your cookies in most modern web browsers. Figure 12.1 shows the cookie
information stored for Listing 12.1. The cookie name, content, and expiration date appear as
expected; the domain name will differ when you run this script on your own domain.
g
or
s.
te
da
up
nu
.a
w
w
w
For more information on using cookies, and the setcookie() function in particular, see the
PHP Manual entry at http://www.php.net/setcookie.
Q) PHP Session
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.
g
or
➢ A session is started with the session_start() function.
s.
➢ Session variables are set with the PHP global variable:
$_SESSION.
te
da
Now, let's create a new page called "session1.php". In this page,
we start a new PHP session and set some session variables:
up
<?php session_start();
?>
nu
<html>
<body>
.a
<?php
$ses=$_SESSION["user"] = "COMPUTER CLUSTER";
w
Also notice that all session variable values are stored in the global
$_SESSION variable:
Session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
g
</html>
or
s.
te
da
up
nu
.a
w
w
w
<?php session_start();
?>
<html>
<body>
<?php
// remove all session variables session_unset();
// destroy the session session_destroy();
echo”session destroy”;
?>
</body>
</html>
g
You can use session_destroy() to end a session, erasing all session
or
variables. The session_destroy() function requires no arguments. You
should have an established session for this function to work as
s.
expected. The following code fragment resumes a session and
abruptly destroys it:
session_start(); session_destroy(); te
da
up
nu
When you move on to other pages that work with a session, the
session you have destroyed will not be available to them, forcing
.a
The items you decide to store in the user's session should be those
items you can imagine using quite a bitand that would be inefficient
to continually extract from the database. For example, suppose that
you have created a portal in which users are assigned a certain level,
such as administrator, registered user, anonymous guest, and so
forth. Within your display modules, you would always want to check
g
to verify that the user accessing the module has the proper
or
permissions to do so. Thus, "user level" would be an example of a
value stored in the user's session, so that the authentication script
s.
used in the display of the requested module only has to check a
session variablethere would be no need to connect to, select, and
query the database. te
da
Working with User Preferences
up
could set specific preferences that would affect the way they viewed
your site. For example, you may allow your users to select from a
.a
predetermined color scheme, font type and size, and so forth. Or, you
may allow users to turn "off" (or "on") the visibility of certain content
w
groupings.
w
w
g
or
s.
Cookie Session
Cookies are client-side files
on a local computer that te
da
Sessions are server-side files that
hold user information.
contain user data.
up
Cookies end on the lifetime When the user quits the browser or logs
set by the user. out of the programmed, the session is
nu
over.
.a
g
Echo “copy right by N Murali Krishna Mtech ”;
or
?>
File: include1.html
s.
<html>
<body>
<h1>Welcome to my home page!</h1> te
da
<p>Some text.</p>
<p>Some more text.</p>
up
</html>
require():-
The include() and require() statement allow you to include the code
.a
produces the same result as copying the script from the file specified
and pasted into the location where it is called.
w
You can save a lot of time and work through including files — Just
w
g
or
fclose()
Opening a File with PHP fopen() Function
s.
To work with a file you first need to open the file. The PHP fopen() function
is used to open a file.
The basic syntax:- te
da
fopen(filename, mode)
The first parameter passed to fopen() specifies the name of the file you
up
want to open, and the second parameter specifies in which mode the file
should be opened.
nu
For example:
<?php
.a
{
echo "File opened successfully.";
w
fclose($handle);
}
?>
The file may be opened in one of the following modes:
w Open the file for writing only and clears the contents of file. If
the file does not exist, PHP will attempt to create it.
Modes What it does
w+ Open the file for reading and writing and clears the contents of
file. If the file does not exist, PHP will attempt to create it.
a Append. Opens the file for writing only. Preserves file content
by writing to the end of the file. If the file does not exist, PHP
will attempt to create it.
g
Now that you have understood how to open and close files. In the following
or
section you will learn how to read data from a file. PHP has several
functions for reading data from a file. You can read from just one
s.
character to the entire file with a single operation. Reading Fixed Number
of Characters
te
The fread() function can be used to read a specified number of characters
da
from a file.
The basic syntax:-
up
<?php
$file = "data.txt";
.a
{
w
g
or
// Write data to the file
s.
fwrite($handle, $data);
like this:
<?php
w
$file = "note.txt";
w
w
g
/* Some code to be executed */
or
// Closing the file handle
fclose($handle);
s.
}
else
{ te
da
echo "ERROR: File does not exist.";
}
up
?>
PHP Delete File - unlink()
nu
unlink ( filename) ;
w
Example
w
<?php
unlink('data.txt');
w
g
$dir = "testdir";
or
// Check the existence of directory
s.
if(!file_exists($dir))
{
// Attempt to create directory te
da
if(mkdir($dir))
{
up
else
{
.a
}
w
else
w
{
echo "ERROR: Directory already exists.";
}
?>
Copying Files from One Location to Another
We can copy a file from one location to another by calling
PHP copy() function with the file's source and destination paths as
arguments. If the destination file already exists it'll be overwritten.
Here's an example which creates a copy of "example.txt" file inside
backup folder.
<?php
// Source file path
$file = "example.txt";
// Destination file path
$newfile = "backup/example.txt";
// Check the existence of file
if(file_exists($file))
{
// Attempt to copy file
if(copy($file, $newfile))
{
echo "File copied successfully.";
}
else
{
echo "ERROR: File could not be copied.";
}
}
else
{
g
echo "ERROR: File does not exist.";
or
}
s.
?>
To make this example work, the target directory which is backup and
te
the source file i.e. "example.txt" has to exist already; otherwise PHP
da
will generate an error.
System():-
system — Execute an external program and display the output.
nu
Description
string system ( string $command [, int &$return_var ] )
.a
Parameters :-
command
w
return_var
If the return_var argument is present, then the return status of
w
Exec():-
exec — Execute an external program.
Description:-
string exec ( string $command [, array &$output [, int &$return_var ]]
)
exec() executes the given command.
<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?>
Passthru():-
passthru — Execute an external program and display raw output.
Description
g
void passthru ( string $command [, int &$return_var ] )
or
example:-
<?php
s.
$filename = "backup-" . date("d-m-Y");
te
$cmd = "mysqldump -u root dudh_society >c:/Backup/$filename.sql";
passthru( $cmd );
da
if(passthru($cmd) == true)
{
up
else
{
echo "Backup failed";
.a
}
?>
w
w
MySQL MySQLi
g
PHP MySQL Connect
or
Since PHP 5.5, mysql_connect() extension is deprecated. Now it is
s.
recommended to use one of the 2 alternatives.
mysqli_connect()
PDO::__construct()
PHP mysqli_connect() te
da
PHP mysqli_connect() function is used to connect with MySQL
database. It returns resource if connection is established or null.
up
Syntax
resource mysqli_connect (server, username, password)
nu
.a
PHP mysqli_close()
w
Syntax
w
g
(e.g. localhost), or IP address of the MySQL server, whereas
or
the username and password parameters specifies the credentials to
access MySQL server, and the database parameter, if provided will
s.
specify the default MySQL database to be used when performing
queries.
te
da
<?php
$link = mysqli_connect("localhost", "root", "",”shdcupdates”);
up
// Check connection
if($link === false){
die("ERROR: Could not connect the data base. " .
nu
mysqli_connect_error());
}
.a
?>
Q)How to create a MySQL Database Using PHP.
w
g
PHP mysqli_query() function to finally create our table.
or
Example:-
<?php
s.
/* Attempt MySQL server connection. Assuming you are running
MySQL
te
server with default setting (user 'root' with no password) */
da
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
up
)";
if(mysqli_query($link, $sql)){
echo "Table created successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
g
} else{
or
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
s.
}
// Close connection
mysqli_close($link); te
da
?>
up
nu
name;
Let's make a SQL query using the SELECT statement, after that we
w
g
echo "<th>first_name</th>";
or
echo "<th>last_name</th>";
s.
echo "<th>email</th>";
echo "</tr>";
te
while($row = mysqli_fetch_array($result)){
da
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
up
}
echo "</table>";
w
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
+----+------------+-----------+----------------------+
| id | first_name | last_name | email |
+----+------------+-----------+----------------------+
| 1 | Peter | Parker | [email protected] |
| 2 | John | Rambo | [email protected] |
| 3 | Clark | Kent | [email protected] |
g
| 4 | John | Carter | [email protected] |
or
| 5 | Harry | Potter | [email protected] |
+----+------------+-----------+----------------------+
s.
The PHP code in the following example will delete the records of
those persons from the persons table whose first_name is equal to
John. te
da
Example Program:-
<?php
up
// Check connection
w
// Close connection
mysqli_close($link);
?>
Q)Creating a Menu in PHP
Step 1: Plan Your Menu Items
• Home
• About
• Services
• Contact
g
or
Step 2: Write the HTML + PHP Code
s.
<?php
// Step 1: Define the menu as an associative array
$menu = array(
"Home" => "index.php", te
da
"About" => "about.php",
"Services" => "services.php",
up
<!DOCTYPE html>
<html>
.a
<head>
<title>PHP Menu Example</title>
w
<style>
w
list-style-type: none;
background-color: #333;
overflow: hidden;
margin: 0;
padding: 0;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 20px;
text-decoration: none;
}
li a:hover {
background-color: #111;
}
</style>
</head>
<body>
<!-- Step 3: Loop through the PHP menu array to generate HTML -->
<ul>
<?php
foreach ($menu as $name => $link) {
echo "<li><a href='$link'>$name</a></li>";
}
?>
</ul>
<h2>Welcome to My Website!</h2>
</body>
g
</html>
or
Output in Browser:
s.
A horizontal menu bar with:
te
da
[ Home ] [ About ] [ Services ] [ Contact ]
Explanation:
Step Code Purpose
.a
You can add logic to highlight the active page like this:
$currentPage = basename($_SERVER['PHP_SELF']);