PHP Programming: (Department Elective-III)
PHP Programming: (Department Elective-III)
OBJECTIVES:
Learn How to:
Write PHP programs that access form data.
Use the “echo” and “print” to send output to the browser.
Learn how to create and use PHP variables.
Learn how to show PHP errors on web pages.
OUTCOMES:
The main learning outcomes are:
Understand process of executing a PHP-based script on a webserver.
Be able to develop a form containing several fields and be able to process the data provided on the form by
a user in a PHP-based script.
Understand basic PHP syntax for variable use, and standard language constructs, such as conditionals and
loops.
Understand the syntax and use of PHP object-oriented classes.
Understand the syntax and functions available to deal with file processing for files on the server as well as
processing web URLs.
Understand the paradigm for dealing with form-based data, both from the syntax of HTML forms, and how
they are accessed inside a PHP-based script.
CO-PO MAPPING:
UNIT II
Arrays-What is an Array, Creating an array, Accessing array Element, Types of arrays,array
functions.
Functions-What is a function, Define a function, Call by value and Call by reference, Recursive
functions
UNIT III
UNIT IV
Introduction to OOPS-Introduction Objects, Declaring a class, properties and methods,
Inheritance ,Polymorphism & encapsulation, constructor, Destructor, Extending classes, using
$this, Using access specifiers, Abstract method and class, using interface.
UNIT V
PHP Advanced Concepts- Using Cookies, Using HTTP Headers, Using Sessions, Using
Environment and Configuration variables.
Working with Date and Time-Displaying Human-Readable Dates and Times, Finding the Date
for a Weekday, Getting the Day and Week of the Year, Determining Whether a Given Year Is a
Leap Year, Obtaining the Difference Between Two Dates, Determining the Number of Days in
the Current Month, Determining the Number of Days in Any Given Month.
UNIT VI
Creating and Using Forms- Understanding Common Form Issues, GET vs. POST, Validating
form input, Working with multiple forms, and Preventing Multiple Submissions of a form.
PHP and Database Access- Basic Database Concepts, Connecting to a MYSQL database,
Performing basic database operations-create, Insert, Retrieving and Displaying results,
Modifying, Updating and Deleting data.
TEXT BOOKS:
1. Beginning PHP and MySQL, 3rdEdition, Jason Gilmore, Apress Publications (Dream
tech.).
2. PHP 5 Recipes A problem Solution Approach Lee Babin, Nathan A Good, Frank
M.Kromann and Jon Stephens.
REFERENCES:
1. Open Source Web Development with LAMP using Linux, Apache, MySQL, Perl and
PHP, J.Lee and B.Ware(Addison Wesley) Pearson Education.
2. PHP 6 Fast and Easy Web Development, Julie Meloni and Matt Telles, CengageLearning
Publications.
Or
Or
Or
A Web page is a document for the World Wide Web that is identified by
a unique uniform resource locator (URL).
A Web page can be accessed and displayed on a monitor or mobile
device through a Web browser. The data found in a Web page is
usually in HTML or XHTML format.
Prepared By: Dept Of CSE, RGMCET Page 3
PHP PROGRAMMING
UI Logics
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result –
Hello, World!
If you examine the HTML output of the above example, you'll
notice that the PHP code is not present in the file sent from the server
to your Web browser. All of the PHP present in the Web page is
processed and stripped from the page; the only thing returned to the
client from the Web server is pure HTML output.
All PHP code must be included inside one of the three special
markup tags,are recognized by the PHP Parser.
<?php PHP code goes here ?>
<? PHP code goes here ?>
<% PHP code goes here %>
<script language = "php"> PHP code goes here </script>
A most common tag is the <?php...?> .
PHP is whitespace insensitive
Whitespace is the stuff you type that is typically invisible on the
screen, including spaces, tabs, and carriage returns (end-of-line
characters).
$ php test.php
It will produce the following result − Hello PHP!!!!!
IMPORTANT POINTS:
1. Every statement in PHP should be terminated by ‘;’.
2. PHP file extension should be .php.
3. PHP script should place within the script declaration tags.
<?php
………
………
?>
SOFTWARES REQUIRED FOR TO WORK WITH PHP:
1. Browser - Internet Explorer
2. Server - Apache
3. Server side script - PHP
4. Database - MYSQL
TOOLS TO WORK WITH PHP:
1. XAMPP - Cross Apache MYSQL PHP Perl
2. WAMPP - Window Apache MYSQL PHP Perl
3. LAMPP - Linux Apache MYSQL PHP Perl
4. MAMPP - Macintosh Apache MYSQL PHP Perl
HOW TO DOWNLOAD & INSTALL XAMPP TOOL?
1. Go to Google
2. XAMPP download in Google Search
3. Select appropriate version of XAMPP based on OS
4. Click on download
INSTALLATION
5. Double click on downloaded file
……..
?>
5. Save again php file
Notice that an error is the same as a warning error i.e. in the notice
error does not stop execution of the script. Notice that the error
occurs when you try to access the undefined variable, and then
produce a notice error.
Example
<?php
$a="Uday ";
echo "Notice Error !!";
echo $b;
?>
Output: In the above code we defined a variable which named $a.
But we call another variable i.e. $b, which is not defined. So there
will be a notice error produced but execution of the script does not
stop, you will see a message Notice Error !!. Like in the following
image:
2. WARNING
Warning errors will not stop execution of the script. The main
reason for warning errors are to include a missing file or using
the incorrect number of parameters in a function.
Example
<?php
echo "Warning Error!!";
include ("Welcome.php");
?>
Output: In the above code we include a welcome.php file, however
the welcome.php file does not exist in the directory. So there will be
a warning error produced but that does not stop the execution of
the script i.e. you will see a message Warning Error !!.
3. FATAL ERROR
Fatal errors are caused when PHP understands what you've
written; however what you're asking it to do can't be done. Fatal
errors stop the execution of the script. If you are trying to access
the undefined functions, then the output is a fatal error.
Example
<?php
function fun1(){
echo "Uday Kumar";
}
fun2();
echo "Fatal Error !!";
?>
Output: In the above code we defined a function fun1 but we call
another function fun2 i.e. func2 is not defined. So a fatal error will
be produced that stops the execution of the script. Like as in the
following image.
4. PARSE ERROR
The parse error occurs if there is a syntax mistake in the
script; the output is Parse errors. A parse error stops the
execution of the script. There are many reasons for the occurrence
of parse errors in PHP. The common reasons for parse errors are as
follows:
Common reason of syntax errors are:
a. Unclosed quotes
b. Missing or Extra parentheses
c. Unclosed braces
d. Missing semicolon
Example
Prepared By: Dept Of CSE, RGMCET Page 18
PHP PROGRAMMING
<?php
echo "C#";
echo "PHP"
echo "C";
?>
Output: In the above code we missed the semicolon in the second
line. When that happens there will be a parse or syntax error which
stops execution of the script, as in the following image:
include(): The include() function takes all the text in a specified file
and copies it into the file that uses the include function. If there is
any problem in loading a file then the include() function generates a
warning but the script will continue execution.
Then create a file menu.php with the following content.
<a href="http://www.tutorialspoint.com/index.htm">Home</a>
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a>
<a href="http://www.tutorialspoint.com/ajax">AJAX</a>
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />
Now create as many pages as you like and include this file to create
header. For example now your test.php file can have following
content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP
file!</p>
</body>
</html>
Output:
require(): The require() function takes all the text in a specified file
and copies it into the file that uses the include function. If there is
Example: x.php
<?php
echo "GEEKSFORGEEKS";
?>
<?php
include_once('header.inc.php');
include_once('header.inc.php');
?>
Output: GEEKSFORGEEKS
<?php
require_once('header.inc.php');
require_once('header.inc.php');
?>
Output: GEEKSFORGEEKS
TAGS IN PHP:
There are four different pairs of opening and closing tags which can
be used in php. Here is the list of tags.
1. Default syntax Or Universal Tags: The default syntax starts with
"<? php" and ends with "?>".
Example:
<?php
echo "Default Syntax";
?>
2. Short open Tags: The short tags starts with "<?" and ends with
"?>". Short style tags are only available when they are enabled in
php.ini configuration file on servers.
Example:
Prepared By: Dept Of CSE, RGMCET Page 22
PHP PROGRAMMING
<?
echo "PHP example with short-tags";
?>
3. HTML Script Tags: HTML script tags look like this :
<script language="php">
echo "This is HTML script tags.";
</script>
4. ASP Style Tags: The ASP style tags start with "<%" and ends with
"%>". ASP style tags are only available when they are enabled in
php.ini configuration file on servers.
Example:
<%
echo 'This is ASP like style';
%>
Note: The above two tags and examples are given only for reference,
but not used in practice any more.
OUTPUT FUNCTIONS IN PHP:
1. echo statement
In PHP ‘echo’ statement is a language construct and not a function,
so it can be used without parenthesis.
But we are allowed to use parenthesis with echo statement when
we are using more than one argument with it.
The end of echo statement is identified by the semi-colon (‘;’). We
can use ‘echo’ to output strings or variables.
Displaying Strings: The keyword echo followed by the string to be
displayed within quotes.
<?php
2. print statement
The PHP print statement is similar to the echo statement and can
be used alternative to echo at many times.
It is also language construct and so we may not use parenthesis:
print or print ().
The main difference between the print and echo statement is that
print statement can have only one argument at a time and thus
can print a single string. Also, print statement always returns a
value 1.
Like echo, print statement can also be used to print strings and
variables.
Displaying String of Text: We can display strings with print
statement in the same way we did with echo statements. The only
difference is we can not display multiple strings separated by
comma(,) with a single print statement. Below example shows how
to display strings with the help of PHP print statement:-
<?php
print "Hello, world!";
?>
Output: Hello, world!
Displaying Variables: Displaying variables with print statement is
also same as that of echo statement.
<?php
$text = "Hello, World!";
$num1 = 10;
$num2 = 20;
print $text."\n";
print $num1."+".$num2."=";
print $num1 + $num2;
?>
Output: Hello, World!
10+20=30
Comparison between Echo and Print in PHP:
3. var_dump
Using this function, we can display the value of a variable along
with data type.
Ex:
<?php
$x=100;
$y=”scott”;
var_dump($x);
var_dump($y);
?>
Output: int 100
string(5) scott
4. printf() :Using this function, we can print variables with the help of
format specifiers.
Example:
<?php
$x=100;
$y=”scott”;
printf(“%d”,$x);
printf(“%s”,$y);
?>
Output: 100 scott
5. print_r(): Using this function, we can display all elements of array
and properties of object.
Example:
<?php
$x=array(10,20,30);
print_r($x);
?>
Output:
Array
(
[0]10
[1]20
[2]30
)
VARIABLES:
Variable is an identifier which holds data or another one variable
and whose value can be changed at the execution time of script.
Syntax: $variablename=value;
A variable starts with the $ sign, followed by the name of the
variable
A variable name must start with a letter or the underscore
character
A variable name can't start with a number.
A variable name can only contain alpha-numeric characters and
underscores(A-z, 0-9 and _ )
Variable names are case-sensitive ($str and $STR both are two
different)
Example:
<?php
$str="Hello world!";
$a=5;
$b=10.5;
echo "String is: $str <br/>";
echo "Integer is: $x <br/>";
echo "Float is: $y <br/>";
?>
VARIABLE SCOPES
Scope of a variable is defined as its extent in program within which
it can be accessed, i.e. the scope of a variable is the portion of the
program with in which it is visible or can be accessed.
Depending on the scopes, PHP has three variable scopes:
function global_var()
{
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>
Output: Variable num inside function : 20
Variable num outside function : 20
3. Static variable: It is the characteristic of PHP to delete the
variable, ones it completes its execution and the memory is freed.
But sometimes we need to store the variables even after the
completion of function execution. To do this we use static keyword
and the variables are then called as static variables.
Example:
<?php
function static_var()
{
static $num = 5;
$sum = 2;
$sum++;
$num++;
echo $num "\n";
echo $sum "\n";
}
static_var();
static_var();
?>
Output: 6 3
7 3
Example:
<?php
function myTest()
{
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Output: 0 1 2
CONSTANTS:
Constants are name or identifier that can't be changed during the
execution of the script. In php constants are define in two ways;
1. Using define() function
2. Using const keyword
In php declare constants follow same rule variable declaration.
Constant start with letter or underscore only.
Create a PHP Constant
Create constant in php by using define() function.
Syntax: define((name, value, case-insensitive)
PHP data types are used to hold different types of data or values. PHP
supports the following data types: String, Integer, Float, Boolean,
Array, Object, NULL, and Resource.
Integer:
Integers hold only whole numbers including positive and negative
numbers, i.e., numbers without fractional part or decimal point.
They can be decimal (base 10), octal (base 8) or hexadecimal (base
16).
The default base is decimal (base 10).
The octal integers can be declared with leading 0 and the
hexadecimal can be declared with leading 0x.
The range of integers must lie between -2^31 to 2^31.
Example:
<?php
// decimal base integers
$deci1 = 50;
$deci2 = 654;
$sum = $deci1 + $deci2;
echo $sum;
?>
Output: 704
Float(or)double:
It can hold numbers containing fractional or decimal part including
positive and negative numbers.
By default, the variables add a minimum number of decimal
places.
Example:
<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;
echo $sum;
?>
Output: 705.11
String:
It can hold letters or any alphabets, even numbers are included.
These are written within double quotes during declaration.
The strings can also be written within single quotes but it will be
treated differently while printing variables.
Example:
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name';
?>
Output: The name of the Geek is Krishna
The name of the geek is $name
NULL:
These are special types of variables that can hold only one value
i.e., NULL.
We follow the convention of writing it in capital form, but its case
sensitive.
Example:
<?php
$nm = NULL;
echo $nm; // This will give no output
?>
Boolean:
Hold only two values, either TRUE or FALSE.
Successful events will return true and unsuccessful events return
false.
NULL type values are also treated as false in Boolean.
If a string is empty then it is also considered as false in boolean
data type.
Example:
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
Output: This condition is TRUE
This condition is not TRUE
Arrays:
Array is a compound data-type which can store multiple values of
same data type.
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n";
echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n";
?>
Output: First Element: 10
Second Element: 20
Third Element: 30
Objects:
Objects are defined as instances of user defined classes that can
hold both values and functions.
Resources:
Resources in PHP are not an exact data type. These are basically
used to store references to some function call or to external PHP
resources. For example, consider a database call. This is an
external resource.
COMMENTING PHP CODE
A comment is the portion of a program that exists only for the
human reader and stripped out before displaying the programs
result. There are two commenting formats in PHP −
1. Single-line comments − They are generally used for short
explanations or notes relevant to the local code. Here are the
examples of single line comments.
<?php
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only
print "An example with single line comments";
?>
returns $x
$x-- Post- Returns $x, then decrements $x
decrement by one
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
echo $x; // Outputs: 9
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>
PHP Logical Operators
The logical operators are typically used to combine conditional
statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $$x or $y is true
Ternary operator:
<?php
$a = 10;
$b = 20;
{
// if TRUE then execute this code
}
Example:
<?php
$x = 12;
if ($x > 0)
{
echo "The number is positive";
}
?>
Output: The number is positive
2. if…else Statement: 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 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:
Syntax:
if (condition)
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
Example:
<?php
$x = -12;
if ($x > 0)
echo "The number is positive";
else
echo "The number is negative";
?>
Output: The number is negative
3. if…elseif…else Statement: he if...elseif...else a special statement
that is used to combine multiple if...else statements.. We use this
when there are multiple conditions of TRUE cases.
Syntax:
if (condition)
{
// if TRUE then execute this code
}
elseif
{
// if TRUE then execute this code
}
elseif
{
// if TRUE then execute this code
}
else
{
The break statement is used to stop the automatic control flow into
the next cases and exit from the switch case.
The default statement contains the code that would execute if none
of the cases match.
Syntax:
switch(expression)
{
case value1:
code to be executed if n==statement1;
break;
case value 2:
code to be executed if n==statement2;
break;
case value 3:
code to be executed if n==statement3;
break;
case value 4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;
}
Example:
<?php
$n = "February";
switch($n)
{
case "January": echo "Its January";
break;
case "February": echo "Its February";
break;
case "March": echo "Its March";
break;
case "April": echo "Its April";
break;
case "May": echo "Its May";
break;
default: echo "Doesn't exist";
}
?>
Output: Its February
LOOPS
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 the time
and effort. PHP supports four different types of loops.
1. for loop
2. while loop
3. do-while loop
4. foreach loop
1. for loop: This type of loops is used when the user knows in
advance, how many times the block needs to execute. These type of
loops are also known as entry-controlled loops. There are three
2. while loop: The while loop is also an entry control loop like for
loops i.e., it first checks the condition at the start of the loop and if
its true then it enters the loop and executes the block of
statements, and goes on executing it as long as the condition holds
true.
Syntax:
while (if the condition is true)
{
// code is executed
}
Example:
<?php
$num = 2;
while ($num < 12)
{
$num += 2;
?>
Output: 4 6 8 10 12
Flowchart
3. do-while loop: This is an exit control loop which means that it first
enters the loop, executes the statements, and then checks the
condition. Therefore, a statement is executed at least once on using
the do…while loop. After executing once, the program is executed
as long as the condition holds true.
Syntax:
do
{
//code is executed
} while (if condition is true);
Example:
<?php
$num = 2;
do {
$num += 2;
echo $num, "\n";
} while ($num < 12);
?>
Output: 4 6 8 10 12
Flowchart:
//code to be executed
}
Example:
<?php
$arr = array (10, 20, 30, 40, 50, 60);
foreach ($arr as $value)
{
echo "$val \n";
}
$arr = array ("Ram", "Laxman", "Sita");
foreach ($arr as $value)
{
echo "$val \n";
}
?>
Output: 10 20 30 40 50 60
Ram Laxman Sita
Break:
The PHP break keyword is used to terminate the execution of a loop
prematurely. The break statement is placed inside the statement
block. It gives you full control and whenever you want to exit from the
loop you can come out. After coming out of a loop immediate
statement to the loop will be executed.
Example: In the following example condition test becomes true when
the counter value reaches 3 and loop terminates.
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )
break;
}
echo ("Loop stopped at i = $i" );
?>
Output: Loop stopped at i = 3
Continue:
The PHP continue keyword is used to halt the current iteration of a
loop but it does not terminate the loop.
Just like the break statement the continue statement is placed inside
the statement block containing the code that the loop executes,
preceded by a conditional test. For the pass encountering continue
statement, rest of the loop code is skipped and next pass starts.
Example: In the following example loop prints the value of array but
for which condition becomes true it just skip the code and next value
is printed.
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )
continue;
echo "Value is $value <br />";
}
?>
Output:
Value is 1
Value is 2
Value is 4
Value is 5
swapping Using Third Variable
<?php
$a = 45;
$b = 78;
// Swapping Logic
$third = $a;
$a = $b;
$b = $third;
echo "After swapping:<br><br>";
echo "a =".$a." b=".$b;
?>
Swapping Without using Third Variable(+ and -):
<?php
$a=234;
$b=345;
//using arithmetic operation
$a=$a+$b;
$b=$a-$b;
$a=$a-$b;
echo "Value of a: $a</br>";
{
echo $number." , ";
}
$number=$number+1;
}
?>
output: 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 ,
47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ,
Factorial of a number
<?php
$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>
Palindrome Number Program Without of Using PHP Predefined
Function :
<?php
$number = 53235;
$p = $number;
$revnum =0;
while($number != 0)
{
$revnum = $revnum*10 + $number % 10 ;
$number = (int)($number/10);
}
if($revnum==$p)
echo $p.' is palindrome number';
else
echo 'number is not palindrome';
?>
Reversing Number in PHP
Example:
<?php
$num = 23456;
$revnum = 0;
while ($num > 1)
{
$rem = $num % 10;
$revnum = ($revnum * 10) + $rem;
$num = ($num / 10);
}
echo "Reverse number of 23456 is: $revnum";
?>
UNIT II
Arrays-What is an Array, Creating an array, Accessing array Element,
Types of arrays, array functions.
Functions-What is a function, Define a function, Call by value and
Call by reference, Recursive functions
ARRAYS
Array is used to store multiple values of same type in single variable.
An array is a special variable, which can hold more than one value at
a time.
Gaurav
2. Associative Arrays in PHP
In this type of array; arrays use named keys that you assign to them.
Syntax
$age = array("Harry"=>"10", "Varsha"=>"20", "Gaurav"=>"30");
or
$age['Harry'] = "10";
$age['Varsha'] = "20";
$age['Gaurav'] = "30";
3. Multidimensional Arrays in PHP
A multidimensional array is an array containing one or more arrays.
For a two-dimensional array you need two indices to select an element
Example
<?php
$student = array( array("Harry",300,11),
array("Varsha",400,10),
array("Gaurav",200,8), array("Hitesh",220,8));
{
echo $cars[$x];
echo "<br>";
}
?>
Output: Volvo
Toyota
BMW
3. asort() - sort associative arrays in ascending order, according to the
value
Example:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
foreach($age as $x => $x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output: Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
4. ksort() - sort associative arrays in ascending order, according to the
key
Example:
<?php
Example
<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
Output: autumn
spring
winter
summer
array_search():Searches an array for a given value and returns the
key
Example
<?php
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>
Output: 2
array_shift() Removes the first element from an array, and
returns the value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of
an array
usort():
The usort() function sorts an array by a user defined comparison
function. This function assigns new keys for the elements in the array.
Existing keys will be removed.
Syntax
Parameters
Sr.No Parameter & Description
1 array(Required)
It specifies an array.
2 cmp_function(Required)
Useful defined function to compare values and to sort them.
If a = b, return 0
If a > b, return 1
If a < b, return -1
Example
<?php
function cmp_function($a, $b) {
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
}
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana" );
usort($fruits, "cmp_function");
print_r($fruits);
?>
Output: Array ( [0] => orange [1] => lemon [2] => banana )
extract():it converts array keys into variable names and array values
into variable value.
Syntax: extract(array,extract_rules,prefix)
Example:
<?php
$state = array("AS"=>"ASSAM", "OR"=>"ORRISA", "KR"=>"KERELA");
extract($state);
echo" $AS is $AS\n $KR is $KR\n $OR is $OR";
?>
Output: $AS is ASSAM
$KR is KERELA
$OR is ORRISA
Example:
<?php
$AS="Original";
$state = array("AS"=>"ASSAM", "OR"=>"ORRISA", "KR"=>"KERELA");
extract($state, EXTR_PREFIX_SAME, "dup");
echo"\$AS is $AS\n $KR is $KR\n $OR if $OR \n $dup_AS =
$dup_AS";
?>
Output: $AS is Original
$KR is KERELA
$OR is ORRISA
$dup_AS = ASSAM
current(): The current() function is used to fetch the value of the
current element in an array.
Syntax: current(array_name)
Example:
<?php
$subject= array('Language','English','Math','Science');
$result = current($subject);
echo $result;
?>
Output: Language
in_array():The in_array() function is used to check whether a value
exists in an array or not.
Syntax: in_array(search_value, array_name, mode)
Parameters:
Name Description Required / Type
Optional
search_value Value to search in the array. Required Mixed*
array_name Specifies the array to search. Required Array
mode If it is set to true, Optional Boolean
the function checks the type of the
search_value.
<?php
$number_list = array('16.10', '22.0', '33.45', '45.45');
if (in_array(22.0, $number_list))
{
echo "'22.0' found in the array";
}
?>
Output: '22.0' found in the array
prev() function behaves just like next(), except it rewinds the internal
array pointer one place instead of advancing it.
Syntax: prev(array_name)
<?php
$val1 = array('Language', 'Math', 'Science', 'Geography');
$cval = current($val1);
echo "$cval <br />";
$cval = next($val1);
echo "$cval <br />";
$cval = next($val1);
echo "$cval <br />";
$cval = prev($val1);
echo "$cval <br />";
?>
Output: Language
Math
Science
Math
range();The range() function used to create an array containing a
range of elements.
Syntax: range(low_value, high_value, step)
Parameters:
Name Description Required / Type
Optional
low_value Specify the lowest value. Required Mixed*
high_value Specify the highest value. Required Mixed*
$mode = reset($input);
print "$mode <br />";
$mode = current($input);
print "$mode <br />";
?>
Output: plane
foot
foot
end(): The end() function advances array's internal pointer to the last
element, and returns its value.
Syntax: end ( $array );
Example
<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport);
print "$mode <br />";
$mode = next($transport);
print "$mode <br />";
$mode = current($transport);
print "$mode <br />";
$mode = prev($transport);
print "$mode <br />";
$mode = end($transport);
print "$mode <br />";
$mode = current($transport);
print "$mode <br />";
?>
Output: foot
bike
bike
foot
plane
plane
FUNCTIONS
A function is a block of code written in a program to perform some
specific task. Functions take information’s as parameter, execute a
block of statements or perform operations on these parameters and
return the result.
PHP provides us with two major types of functions:
1. Built-in functions: PHP provides us with huge collection of built-in
library functions. These functions are already coded and stored in
form of functions. To use those we just need to call them as per our
requirement like, var_dump, fopen(), print_r(), gettype() and so on.
2. User Defined Functions: Apart from the built-in functions, PHP
allows us to create our own customized functions called the user-
defined functions.
Why should we use functions?
1. Reusability: If we have a common code that we would like to use at
various parts of a program, we can simply contain it within a
function and call it whenever required. This reduces the time and
effort of repetition of a single code. This can be done both within a
program and also by importing the PHP file, containing the
function, in some other program
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}
pro(2, 3, 5);
?>
Output: The product is 30
SETTING DEFAULT VALUES FOR FUNCTION PARAMETER
PHP allows us to set default argument values for function
parameters.
If we do not pass any argument for a parameter then PHP will use
the default set value for this parameter in the function call.
Example:
<?php
function defk($str, $num=12)
{
echo "$str is $num years old \n";
}
defk("Ram", 15);
defk("Adam");
?>
Output: Ram is 15 years old
Adam is 12 years old
In the above example, the parameter $num has a default value 12, if
we do not pass any value for this parameter in a function call then
this default value 12 will be considered. Also the parameter $str has
no default value, so it is compulsory.
function with the same name as whatever the variable evaluates to,
and will attempt to execute it.
Among other things, this can be used to implement callbacks,
function tables, and so forth.
Example:
function foo()
{
echo "hi<br />";
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
?>
Output: hi
}
$n = 5;
$fact = Factorial($n);
echo "Factorial = $fact";
?>
Output: Factorial = 120
UNIT III
Introduction to Strings:
Creating and accessing Strings, String Related Library functions.
File handling in Php:
Defining a File, different file operations.
STRINGS: String is a sequence of characters.For example ‘rgmcet’ or ”rgmcet”
is string.Everything inside the quotes single(‘ ‘) or double(“ “) in php can be
treated as string. There are 2 ways to specify string in PHP
1. single quoted strings: We can create a string by enclosing text in a single
quote. This type of strings does not process special characters inside quotes.
Example
<?php
$str='rgmcet';
echo ‘ welcome to $str ’;
?>
Output: welcome to $str
In the above program the echo statement prints the variable name rather than
printing the contents of the variables.this is because single quote strings in
php does not process special characters.Hence the string is unable to identify
the $ sign as start of a variable name.
2. double quoted strings: we can specify string by enclosing text within
double quotes. This type of strings can process special characters inside
quotes.
Example
<?php
echo “Hello php I am double quote String\n";
$str="rgmcet";
echo “ welcome to $str”;
?>
Output: Hello php I am double quote String
welcome to rgmcet
In the above program we can see that the double quote string is processing the
special characters according to their properties.The \n character is not printed
and is considered as a newline .Also instead of the variable name rgmcet is
printed
Example
<?php
$str="Hello "php" I am double quote String";
echo $str;
?>
Output: Parse error: syntax error, unexpected 'quote' (T_STRING) in
C:\wamp\www\string1.php on line 2
Example
<?php
$str="Hello \"php\" I am double quote String";
echo $str;
?>
Output: Hello php I am double quote String
Note: Using double quote String you can also display variable value on
webpage
CONCATENATION OF TWO STRINGS
There are two string operators. The first is the concatenation operator (‘.‘),
which returns the concatenation of its right and left arguments. The second is
the concatenating assignment operator (‘.=‘), which appends the argument on
the right side to the argument on the left side.
Example1:
<?php
$a = 'Hello';
$b = 'World!';
$c = $a.$b;
<?php
echo str_word_count("Hello world!");
?>
Output: 2
strrev(): strrev() function is used to revers any string.
Example
<?php
echo strrev("Hello world!");
?>
Output: !dlrow olleH
strtolower(): strtolower() function is used to convert uppercase latter into
lowercase latter.
Example
<?php
$str="Hello friends i am HITESH";
$str=strtolower($str);
echo $str;
?>
Output: hello friends i am hitesh
strtoupper(): PHP strtoupper() function is used to convert lowercase latter into
uppercase latter.
Example
<?php
$str="Hello friends i AM Hitesh";
$str=strtoupper($str);
echo $str;
?>
Output: HELLO FRIENDS I AM HITESH
ucwords(): ucwords() function is used to convert first letter of every word into
upper case.
Example
<?php
$str="hello friends i am hitesh";
$str=ucwords($str);
echo $str;
?>
Output: Hello Friends I Am Hitesh
ucfirst(): ucfirst() function returns string converting first character into
uppercase. It doesn't change the case of other characters.
Example
<?php
function firstUpper($string)
{
return(ucfirst($string));
}
$string="welcome to GeeksforGeeks";
echo (firstUpper($string));
?>
Output: Welcome to GeeksforGeeks
lcfirst(): lcfirst() function is used to convert first character into lowercase. It
doesn't change the case of other characters.
Example
<?php
function firstLower($string)
{
return(lcfirst($string));
}
$string="WELCOME to GeeksforGeeks";
echo (firstLower($string));
?>
Syntax: strcmp(string1,string2)
This function returns:
0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2
Example:
<?php
echo strcmp("Hello","Hello");
echo "<br>";
echo strcmp("Hello","hELLo");
?>
Output: 0
-1
Example:
<?php
echo strcmp("Hello world!","Hello world!")."<br>";
echo strcmp("Hello world!","Hello")."<br>"; // string1 is greater than string2
echo strcmp("Hello world!","Hello world! Hello!")."<br>"; // string1 is less than
string2
?>
Output: 0
7
-7
strcasecmp():Compare two strings with case-insensitive manner
Syntax: strcasecmp(string1,string2)
This function returns:
0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2
Example:
<?php
echo strcasecmp("Hello","HELLO");
echo strcasecmp("Hello","hELLo");
?>
Output: 0
0
Example:
<?php
echo strcasecmp("Hello world!","HELLO WORLD!"); // The two strings are equal
echo strcasecmp("Hello world!","HELLO"); // String1 is greater than string2
echo strcasecmp("Hello world!","HELLO WORLD! HELLO!"); // String1 is less
than string2
?>
Output: 0
7
-7
strncmp(): The strncmp() is used to compare first n character of two strings.
This function is case-sensitive which points that capital and small cases will be
treated differently, during comparison.
Syntax: strncmp( $str1, $str2, $len )
This function returns:
0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2
Example:
<?php
$str1 = "Geeks for Geeks ";
$str2 = "Geeks for Geeks ";
// Both the strings are equal
$test=strncmp($str1, $str2, 16 );
echo "$test";
?>
Output: 0
Example:
?php
// Input strings
$str1 = "Geeks for Geeks ";
$str2 = "Geeks for ";
$test=strncmp($str1, $str2, 16 );
// In this case the second string is smaller
echo "$test";
?>
Output: 6
Example:
<?php
// Input Strings
$str1 = "Geeks for ";
$str2 = "Geeks for Geeks ";
$test=strncmp($str1, $str2, 16 );
// In this case the first string is smaller
echo "$test";
?>
Output: -6
strncasecmp(): The strncmp() is used to compare first n character of two
strings. This function is case-sensitive which points that capital and small
cases will be treated differently, during comparison.
Syntax: strncasecmp( $str1, $str2, $len )
This function returns:
0 - if the two strings are equal
<0 - if string1 is less than string2
?>
Output: testing
sti
ltrim(): Removes whitespace or other characters from the left side of a string
Syntax: ltrim(string,charlist)
<?php
$str = "Hello World!";
echo $str . "<br>";
echo ltrim($str,"Hello");
?>
Output: Hello World!
World!
rtrim(): Removes whitespace or other characters from the right side of a string
Syntax: rtrim(string,charlist)
<?php
$str = "Hello World!";
echo $str . "<br>";
echo rtrim($str,"World!");
?>
Output: Hello World!
Hello
Write a PHP program to count number of characters in a given string.
<?php
$text="w3resource";
$search_char="r";
$count="0";
for($x="0"; $x< strlen($text); $x++)
{
$count=$count+1;
}
echo $count."\n";
?>
Function Description
chop() Removes whitespace or other characters from the right
end of a string
chr() Returns a character from a specified ASCII value
count_chars() Returns information about characters used in a string
echo() Outputs one or more strings
explode() Breaks a string into an array
fprintf() Writes a formatted string to a specified output stream
parse_str() Parses a query string into variables
print() Outputs one or more strings
printf() Outputs a formatted string
sprintf() Writes a formatted string to a variable
sscanf() Parses input from a string according to a format
str_getcsv() Parses a CSV string into an array
str_ireplace() Replaces some characters in a string (case-insensitive)
str_pad() Pads a string to a new length
str_replace() Replaces some characters in a string (case-sensitive)
str_shuffle() Randomly shuffles all characters in a string
str_split() Splits a string into an array
strcspn() Returns the number of characters found in a string
before any part of some specified characters are found
stripos() Returns the position of the first occurrence of a string
inside another string (case-insensitive)
stristr() Finds the first occurrence of a string inside another
string (case-insensitive)
strrchr() Finds the last occurrence of a string inside another
string
strripos() Finds the position of the last occurrence of a string
FILE HANDLING
A file is simply a resource for storing information on a computer.
Files are usually used to store information such as;
1. Configuration settings of a program
2. Simple data such as contact names against the phone numbers.
3. Images, Pictures, Photos, etc.
PHP FILE FORMATS SUPPORT
PHP file functions support a wide range of file formats that include;
1. File.txt
2. File.log
3. File.custom_extension i.e. file.xyz
4. File.csv
5. File.gif, file.jpg etc
6. Files provide a permanent cost effective data storage solution for simple
data compared to databases that require other software and skills to
manage DBMS systems.
7. You want to store simple data such as server logs for later retrieval and
analysis
Example:
<?php
$f = "C:\Windows\win.ini";
if (file_exists($f))
{
$size = filesize($f);
echo $f . " is " . $size . " bytes.";
}
else
{
echo $f . " does not exist.";
}
}
FILE HISTORY
To determine when a file was last accessed, modified, or changed, you can use
the following functions respectively: fileatime(), filemtime(), and filectime().
Example:
<?php
$dateFormat = "D d M Y g:i A";
$atime = fileatime($f);
$mtime = filemtime($f);
$ctime = filectime($f);
echo $f . " was accessed on " . date($dateFormat, $atime) . ".<br>";
echo $f . " was modified on " . date($dateFormat, $mtime) . ".<br>";
echo $f . " was changed on " . date($dateFormat, $ctime) . ".";
?>
The code here retrieves the timestamp of the last access, modifies, and change
dates and displays them,
C:Windowswin.ini was accessed on Tue 14 Jul 2009 4:34 AM.
C:Windowswin.ini was modified on Fri 08 Jul 2011 2:03 PM.
To clarify, filemtime() returns the time when the contents of the file was
last modified, and filectime() returns the time when information associated with
the file, such as access permissions or file ownership, was changed.
FILE PERMISSIONS
Before working with a file you may want to check whether it is readable or
writeable to the process. For this you’ll use the functions is_readable() and
is_writeable()
Example:
<?php
echo $f . (is_readable($f) ? " is" : " is not") . " readable.<br>";
echo $f . (is_writable($f) ? " is" : " is not") . " writeable.";
?>
Both functions return a Boolean value whether the operation can be performed
on the file. Using the ternary operator you can tailor the display to state
whether the file is or is not accessible as appropriate.
C:Windowswin.ini is readable.
C:Windowswin.ini is not writeable.
FILE OR NOT?
To make absolutely sure that you’re dealing with a file you can use the is_file()
function. is_dir() is the counterpart to check if it is a directory.
Example:
<?php
echo $f . (is_file($f) ? " is" : " is not") . " a file.<br>";
echo $f . (is_dir($f) ? " is" : " is not") . " a directory.";
?>
output:
C:Windowswin.ini is a file.
C:Windowswin.ini is not a directory.
Places the file pointer at the end of the file. If files does not exist then it
attempts to create a file.
If an attempt to open a file fails then fopen returns a value of false otherwise
it returns a file pointer which is used for further reading or writing to that
file.
<?php
$fileName = "/doc/myFile.txt";
$fp = fopen($fileName,"r");
if( $fp == false )
{
echo ( "Error in opening file" );
exit();
}
?>
fclose(): After making a changes to the opened file it is important to close it
with the fclose() function. The fclose() function requires a file pointer as its
argument and then returns true when the closure succeeds or false if it fails.
Syntax: fclose($handle);
Here,
“fclose” is the PHP function for closing an open file
“$handle” is the file pointer resource.
READING A FILE
fread():
Once a file is opened using fopen() function it can be read with a function
called fread().
This function requires two arguments. These must be the file pointer and
the length of the file expressed in bytes.
The files length can be found using the filesize() function which takes the file
name as its argument and returns the size of the file expressed in bytes.
The steps required to read a file with PHP.
file_get_contents()
This function will read the entire contents of a file into a variable without
the need to open or close the file.
Example:
<?php
$f = "c:\windows\win.ini";
$f1 = file_get_contents($f);
echo $f1;
?>
Reading a file Line by Line
fgets(): The fgets() function is used to read a single line from a file, and after a
call to this function, the file pointer has moved to the next line.
Syntax: fgets(filepointer);
Example:
<?php
$f = "c:\windows\win.ini";
$f1 = fopen($f, "r");
do
{
echo fgets($f1) . "<br>";
}while (!feof($f1));
fclose($f1);
?>
Example:
<?php
$fileName = "/doc/myFile.txt";
$fp = fopen($fileName,"r");
if( $fp == false )
{
echo ( "Error in opening file" );
exit();
}
while(!feof($fp))
{
echo fgets($fp). "<br>";
}
?>
fgetc()
Example:
<?php
$file = fopen("test2.txt","r");
while (! feof ($file))
{
echo fgetc($file);
}
fclose($file);
?>
output: Hello, this is a test file.
feof(): The function feof() checks whether the filepointer has reached its end of
the file or not.
Example:
<?php
$f = "c:\windows\win.ini";
$f1 = fopen($f, "r");
do
{
echo fgets($f1) . "<br>";
}while (!feof($f1));
fclose($f1);
?>
WRITING A FILE
fwrite()
The fwrite() function in PHP is an inbuilt function which is used to write to an
open file. The fwrite() function stops at the end of the file or when it reaches the
specified length passed as a parameter, whichever comes first.
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "$filetext" );
echo("file name: $filename");
?>
</body>
</html>
Output
file_put_contents()
This function is used to write the new contents into a file.
First, it deletes the existing contents of a file then it writes new contents.
If file is not available it creates a new file.
Example
<?php
file_put_contents(“abc.txt”,”Uday”);
?>
<?php
$myfile = fopen("gfg.txt", "w");
echo fputs($myfile, "Geeksforgeeks is a portal of geeks!", 13);
fclose($myfile);
fopen("gfg.txt", "r");
echo fread($myfile, filesize("gfg.txt"));
fclose($myfile);
?>
fputs( ): The fputs() function in PHP is an inbuilt function which is used to
write to an open file. The fputs() function stops at the end of the file or when it
reaches the specified length passed as a parameter, whichever comes first.
Syntax: fputs(filepointer, string, length)
The fputs() function in PHP accepts three parameters.
Example:
<?php
$myfile = fopen("gfg.txt", "r");
echo ftell($myfile);
fseek($myfile, "36");
echo "<br />" . ftell($myfile);
fclose($myfile);
?>
rewind( ): The rewind() is used to set the position of the file pointer to the
beginning of the file.
Syntax: rewind(filepointer)
<?php
$myfile = fopen("gfg.txt", "r+");
fwrite($myfile, 'geeksforgeeks a computer science portal');
rewind($myfile);
fwrite($myfile, 'geeksportal');
rewind($myfile);
echo fread($myfile, filesize("gfg.txt"));
fclose($myfile);
?>
COPYING A FILE
The PHP copy function is used to copy files.
Syntax:
<?php
copy($file,$copied_file);
?>
Here,
“$file” specifies the file path and name of the file to be copied.
“copied_file” specified the path and name of the copied file
Example
<?php
copy('my_settings.txt', 'my_settings_backup.txt') or die("Could not copy
file");
echo "File successfully copied to 'my_settings_backup.txt'";
?>
DELETING A FILE
The unlink function is used to delete the file.
Example
<?php
if (!unlink('my_settings_backup.txt'))
{
echo "Could not delete file";
}
else
{
echo "File 'my_settings_backup.txt' successfully deleted";
}
?>
RENAMING FILES
This function is used to rename the existing file name with the specified file
name.
Example
<?php
$file = "file.txt";
if(file_exists($file))
{
if(rename($file, "newfile.txt"))
{
echo "File renamed successfully.";
}
else
{
echo "ERROR: File cannot be renamed.";
}
}
else
{
UNIT IV
INTRODUCTION TO OOPS: INTRODUCTION OBJECTS, DECLARING
A CLASS, PROPERTIES AND METHODS, INHERITANCE
,POLYMORPHISM & ENCAPSULATION, CONSTRUCTOR,
DESTRUCTOR, EXTENDING CLASSES, USING $THIS, USING ACCESS
SPECIFIERS, ABSTRACT METHOD AND CLASS, USING INTERFACE.
Inheritance:
Polymorphism: polymorphism means the ability to have many forms. In other words,
"Polymorphism describes a pattern in Object Oriented Programming in which a class has
varying functionality while sharing a common interfaces.".
<?php
class person
?>
Example:
<?php
class GeeksforGeeks
{
public function __construct()
{
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
}
$obj = new GeeksforGeeks;
?>
Output: The class "GeeksforGeeks" was initiated.
<?php
class Mobile
var $price;
var $title;
function setPrice($par)
$this->price = $par;
function getPrice(){
$Samsung->setPrice( 90000 );
$Samsung->getPrice();
?>
Creating an Object:
class Book {
Member Functions:
After creating our objects, we can call member functions related to that object. A member function
typically accesses members of current object only.
Example:
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Example:
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
function getPrice(){
echo $this->price."<br>";
function setTitle($par){
$this->title = $par;
function getTitle(){
echo $this->title."<br>" ;
$maths->setTitle( "Algebra" );
$maths->setPrice( 7 );
$maths->getTitle();
$maths->getPrice();
?>
To add data to a class, properties, or class-specific variables, are used. These work exactly like regular
variables, except they're bound to the object and therefore can only be accessed using the object.
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
}
?>
Output: I'm a class property!
Methods are class-specific functions. Individual actions that an object will be able to perform are
defined within the class as methods.
<?php
class MyClass
$this->prop1 = $newval;
?>
Example:
<?php
class MyClass
$this->prop1 = $newval;
echo $obj->getProperty();
echo $obj2->getProperty();
echo $obj->getProperty();
echo $obj2->getProperty();
?>
//Derived Class
class B : A
{
//Derived Class
class B : A
{
public void fooB()
{
//TO DO:
}
}
//Derived Class
class C : B
{
public void fooC()
{
//TO DO:
}
}
3. Multiple inheritance
Multiple inheritance
In this inheritance, a derived class is created from more than one base class. This
inheritance is not supported by .NET Languages like C#, F# etc. and Java Language.
In the given example, class c inherits the properties and behavior of class B and class A
at same level. So, here A and Class B both are the parent classes for Class C.
//Base Class
class B
{
public void fooB()
{
//TO DO:
}
}
//Derived Class
class C : A, B
{
//TO DO:
}
}
//Derived Class
class B : A
{
public void fooB()
{
//TO DO:
}
}
//Derived Class
class C : A
{
public void fooC()
{
//TO DO:
}
}
//Derived Class
class D : B, A, C
{
public void fooD()
{
//TO DO:
}
}
8. Hierarchical Inheritance
In this inheritance, more than one derived classes are created from a single base class
and futher child classes act as parent classes for more than one child classes.
Prepared By: Dept Of CSE, RGMCET Page 14
Creating an object from an existing class is called instantiating the objec
PHP PROGRAMMING
In the given example, class A has two childs class B and class D. Further, class B and class
C both are having two childs - class D and E; class F and G respectively.
//Derived Class
class B : A
{
public void fooB()
{
Prepared By: Dept Of CSE, RGMCET Page 15
Creating an object from an existing class is called instantiating the objec
PHP PROGRAMMING
//TO DO:
}
}
//Derived Class
class C : A
{
public void fooC()
{
//TO DO:
}
}
//Derived Class
class D : C
{
public void fooD()
{
//TO DO:
}
}
//Derived Class
class E : C
{
public void fooE()
{
//TO DO:
}
}
//Derived Class
class F : B
Prepared By: Dept Of CSE, RGMCET Page 16
Creating an object from an existing class is called instantiating the objec
PHP PROGRAMMING
{
public void fooF()
{
//TO DO:
}
}
//Derived Class
class G :B
{
public void fooG()
{
//TO DO:
}
}
9. Hybrid Inheritance
Since .NET Languages like C#, F# etc. does not support multiple and multipath
inheritance. Hence hybrid inheritance with a combination of multiple or multipath
inheritances is not supported by .NET Languages.
//Base Class
class A
//TO DO:
//Base Class
class F
//TO DO:
//Derived Class
class B : A, F
//TO DO:
//Derived Class
class C : A
//TO DO:
//Derived Class
class D : C
//TO DO:
//Derived Class
class E : C
//TO DO:
Advantages of Inheritance
1. Reduce code redundancy.
4. The code is easy to manage and divided into parent and child classes.
5. Supports code extensibility by overriding the base class functionality within child
classes.
class_exist():
To check input class is existing or not in current script.
<?php
class cls
{
}
echo class_exist(“cls”);
?>
get_declared_classes():
To get all declared classes of current script with predefined classes. It returns output in the form
of array.
<?php
class cls1
{
}
class cls2
{
}
print_r(get_declared_classes());
?>
method_exist():
To check input method exists or not in specified class.
<?php
class cls
{
function fun()
{
}
}
echo method_exists(“cls”,”fun”);
?>
property_exist():
To check input property is existed or not in specified class.
<?php
class cls
{
var $x=10;
}
echo property_exists(“cls”,”x”);
?>
get_class_vars():
get_class_methods():
get_object_vars():
interface_exists():
is_subclass_of():
get_parent_class():
return:
$this:
static:
Prepared By: Dept Of CSE, RGMCET Page 23
Creating an object from an existing class is called instantiating the objec
PHP PROGRAMMING
https://www.brainbell.com/tutorials/php/abstract-interface-composition-aggregation.html
https://www.valuebound.com/resources/blog/object-oriented-programming-concepts-php-part-1
https://www.dyclassroom.com/php/php-oop-interface
https://www.phptpoint.com/php-polymorphism/
https://www.phptpoint.com/php-inheritance/
Access Modifier allows you to alter the visibility of any class member(properties and method).
In php there are three scopes for class members.
Public
Protected and
Private
<?php
class demo
public $name="ravish";
function disp()
echo $this->name."<br/>";
function show()
echo $this->name;
echo $obj->name."<br/>";
$obj->disp();
$obj->show();
?>
Output:ravish
ravish
ravish
<?php
class demo
{
protected $x=500;
protected $y=500;
function add()
{
echo $sum=$this->x+$this->y."<br/>";
}
}
class child extends demo
{
function sub()
{
echo $sub=$this->x-$this->y."<br/>";
}
}
$obj= new child;
$obj->add();
$obj->sub();
?>
Output:1000
0
Private access modifier
Private is only accessible within the class that defines it.( it can’t be access outside the class means in
inherited class).
<?php
class demo
{
private $name="shashi";
private function show()
{
echo "This is private method of parent class";
}
}
class child extends demo
{
function show1()
{
echo $this->name;
}
}
$obj= new child;
$obj->show();
$obj->show1();
?>
Output:Fatal error: Call to private method demo::show()
use of all access modifier in a single example
Create a parent class with public, private and protected properties and try to access these properties
with their child class.
<?php
class parents
{
public $name="shashi";
protected $profile="developer";
private $salary=50000;
public function show()
{
echo "Welcome : ".$this->name."<br/>";
echo "Profile : ".$this->profile."<br/>";
echo "Salary : ".$this->salary."<br/>";
}
}
class childs extends parents
{
public function show1()
{
echo "Welcome : ".$this->name."<br/>";
echo "Profile : ".$this->profile."<br/>";
echo "Salary : ".$this->salary."<br/>";
}
}
$obj= new childs;
$obj->show1();
?>
Output
Welcome:shashi
Profile:developer
Salary :
UNIT V
PHP ADVANCED CONCEPTS- USING COOKIES, USING HTTP HEADERS, USING
SESSIONS, USING ENVIRONMENT AND CONFIGURATION VARIABLES.
WORKING WITH DATE AND TIME-DISPLAYING HUMAN-READABLE DATES AND
TIMES, FINDING THE DATE FOR A WEEKDAY, GETTING THE DAY AND WEEK OF
THE YEAR, DETERMINING WHETHER A GIVEN YEAR IS A LEAP YEAR, OBTAINING
THE DIFFERENCE BETWEEN TWO DATES, DETERMINING THE NUMBER OF DAYS
IN THE CURRENT MONTH, DETERMINING THE NUMBER OF DAYS IN ANY GIVEN
MONTH.
COOKIES: A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user's computer. Each time the same computer requests a page with a browser, it
will send the cookie too. With PHP, you can both create and retrieve cookie values.
OR
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
OR
Cookies are text files stored on the client computer and they are kept of use tracking purpose
Syntax ssetcookie ( string name [, string value [, int expire [, string path [, string domain
[, bool secure]]]]] )
Parameter Description
name The name to set the cookie variable to and hence
the name to access it with
value The value of the current cookie
expire When a cookie will expire (in the form of a Unix
timestamp)
path The directory where the cookie will be available for
use
domain The domain at which the cookie will be available
secure Whether a cookie can be read on a non-SSL enable
script
setcookie($cookie_name, $cookie_value, time() + (86400 * 30));
<?php
setcookie("username", "John Carter", time()+30*24*60*60);
?>
Retrieve a Cookie: We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set or not:
<?php
echo $_COOKIE["username"];
?>
<?php
if(isset($_COOKIE["username"]))
echo "Hi " . $_COOKIE["username"];
else
echo "Welcome Guest!";
?>
Modify a Cookie Value: To modify a cookie, just set (again) the cookie using the setcookie()
function:
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
Deleting Cookie with PHP: You can delete a cookie by calling the same setcookie() function with
the cookie name and any value (such as an empty string) however this time you need the set the
expiration date in the past, as shown in the example below:
<?php
setcookie("username", "", time()-3600);
?>
A session is a way to store information (in variables) to be used across multiple pages.Unlike a
cookie, the information is not stored on the users computer.
What is a 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.Session variables solve
this problem by storing user information to be used across multiple pages (e.g. username,
favorite color, etc). By default, session variables last until the user closes the browser.So; Session
variables hold information about one single user, and are available to all pages in one
application.
Why and when to use Sessions?
You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
You want to pass values from one page to another.
You want the alternative to cookies on browsers that do not support cookies.
You want to store global variables in an efficient and more secure way compared to
passing them in the URL
You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.
Creating a Session: A session is started with the session_start() function.
<?php
session_start();
?>
Creating php session variables:Session variables are set with the PHP global variable:
$_SESSION.
<?php
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
?>
Get PHP Session Variable Values
Also notice that all session variable values are stored in the global $_SESSION variable:
<?php
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
Another way to show all the session variable values for a user session is to run the following
code:
<?php
print_r($_SESSION);
?>
O/P: Array ( [favcolor] => green [favanimal] => cat )
Modify a PHP Session Variable
To change a session variable, just overwrite it:
<?php
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
O/P: Array ( [favcolor] => yellow [favanimal] => cat )
Destroy a PHP Session
To remove all global session variables and destroy the session,
use session_unset() and session_destroy():
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo"session are unset";
?>
O/P: session are unset
It is important to notice that header() must be called before any actual output is sent (In PHP 4
and later, you can use output buffering to solve this problem):
<html>
<?php
header('Location: http://www.example.com/');
?>
Syntax: header(string,replace,http_response_code)
Parameter Description
replace Optional. Indicates whether the header should replace previous or add a
second header. Default is TRUE (will replace). FALSE (allows multiple
headers of the same type)
http_response_code Optional. Forces the HTTP response code to the specified value
(available in PHP 4.3 and higher)
</form>
</body>
</html>
The form in the previous block of code will then call the processing statement as follows:
<?php
//You will assume that this scripts main focus is to validate against a blank entry.
if (trim ($_POST['yourname']) == "")
{
header ("Location: sample12_5.html");
exit;
}
echo $_POST['yourname'];
?>
The header() function is rather nice in that it will redirect you automatically to the appropri-ate
file (providing it exists) without a single hiccup in the processing. You will simply find yourself
at the appropriate page. You can even use the header() function with the Location parameter to
send you to a page not currently on the server on which the script is located.
Sending Content Types Other Than HTML
Naturally, sometimes you will want to use the header() function to output a type of file format
that may not be an actual web page. Thankfully, the header function is more than versatile
enough to take care of this issue. To make the most out of this function, you can effectively
output other file types by simply declaring the content type you want to output.This functionality
can be handy in circumstances where you want to deploy a document to a user or perhaps even
output a dynamic image. You can use the following script to output a
JPG image to the user.
<html>
<body>
<img src="sample12_6.php" alt="" title="" style="border: none;" />
</body>
</html>
<?php
$path = "images/winter.jpg";
try
{
if (is_file ($path))
{
the same way, provided you use the proper content type (more widely known as a MIME type).
Table lists a few of the popular MIME types you may be interested in using as output.
A common use of the environment variables in PHP is for dynamic imaging. By using PHP’s
environment variables to determine the current operating system,you can make your code
slightly more portable.
Using configuration variables in PHP is for particularly with file upload scripts.
The PHP installation leaves only enough processing time to upload files that are generally 2MB
or smaller in size. By manipulating the PHP configuration files temporarily, you can increase the
limit enough to allow a script to process much larger files.
Reading Environment and Configuration Variables
PHP 5 makes reading environment and configuration variables easy. The $_ENV superglobal is
used for reading a system’s environment variables and has an argument set that is based upon the
current environment that is available to it. Because of its flexibility,there is no real set argument
list, as it is generated based on the current server environment.You can use the phpinfo()
function to determine the current environment variables, and you can retrieve them using the
getenv() function, which needs to be supplied a valid environ-ment variable name.
Reading configuration variables, on the other hand, takes place through two functions,ini_get()
and ini_get_all(). The function ini_get() will retrieve the value of a specified configuration
variable, and the function ini_get_all() will retrieve an array filled with the entire selection of
configuration variables that are available.
configuration variable for the script’s duration. Once the script finishes executing, the
configuration variable will return to its original state. The prototype for ini_set() is as follows:
string ini_set ( string varname, string newvalue )
<?php
//Setting an environment variable in php is as easy as assigning it.
echo $_ENV['COMPUTERNAME'] . "<br />"; // Echoes BABINZ-CODEZ.
$_ENV['COMPUTERNAME'] = "Hello World!";
echo $_ENV['COMPUTERNAME'] . "<br />"; //Echoes the new COMPUTERNAME.
//Of course the change is relevant only for the current script.
//Setting a configuration variable is the same in that it is in effect only for the duration of the
script.
echo ini_get ('post_max_size'); //Echoes 8MB.
//Then you set it to 200M for the duration of the script.
ini_set('post_max_size','200M');
//Any files that are to be uploaded in this script will be OK up to 200M.
?>
checkdate() Validates set of Gregorian year, month, and day values (for example,
2005, 3, 17).
date_sunrise() Returns time of sunrise for a given day and location (new in PHP 5).
date_sunset() Returns time of sunset for a given day and location (new in PHP 5).
date() Formats a local date/time, given a Unix timestamp (for example,
1111035030000 ) and a formatting string.
getdate() Given a Unix timestamp, returns an associative array containing date and
time information (defaults to current time).
gettimeofday() Returns an associative array containing information about the current
system time.
gmdate() Formats a GMT/UTC date/time. Uses the same formatting characters as
the date() function.
gmmktime() Converts a set of GMT date/time values into a Unix timestamp (analogous
to mktime()).
gmstrftime() Formats a GMT/UTC date/time according to locale settings
idate() Formats a local time/date value as an integer.
localtime() Given a Unix timestamp, returns an array of date/time values..
Day
d Day of the month, with leading zeros (two digits).
j Day of the month (no leading zeros).
S Ordinal suffix for the day of the month, two characters (st, nd, th); most
commonly used in combination with j.
l (lowercase L) Full name of the day of the week (Monday, Tuesday, and so on).
D A textual representation of a day, three letters (Mon, Tue, and so on).
w Numeric representation of the day of the week (0 = Sunday, 6 = Saturday).
Year
y Two-digit year.
Y Four-digit year.
Hour
h Hour in 12-hour format, with leading zero (two digits).
g Hour in 12-hour format (no leading zero).
H Hour in 24-hour format, with leading zero (two digits).
Minute
i Minute, with leading zero (two digits).
j Minute (no leading zero).
Second
s Second, with leading zero (two digits).
Z Integer representation of the difference in seconds between local time and
GMT/UTC (for example, 36000 for GMT+1000 and –18000 for GMT–
0500).
2005-03-14T19:38:08+10:00).
r RFC-2822 format WWW, DD MMM YYYY HH:MM:SS ±HHMM, for
example, Mon,14 Mar 2005 19:38:08 +1000).
U Seconds since the Unix epoch. Calling date('U') with no timestamp
argument produces the same output as the time() function.
'c',
'l, F jS, Y, g:i A',
'H:i:s D d M y',
);
foreach($formats as $format)
echo "<p><b>$format</b>: " . date($format, $time) . "</p>\n";
?>
Output:
U: 1110643578
r: Sun, 13 Mar 2005 02:06:18 +1000
c: 2005-03-13T02:06:18+10:00
l, F jS, Y, g:i A: Sunday, March 13th, 2005, 2:06 AM
H:i:s D d M y: 02:06:18 Sun 13 Mar 05
For example, suppose that your firm’s sales employees are supposed to turn in their monthly
sales reports on the first Tuesday of each month. The following example shows how you can
determine the date of the first Tuesday in the month following the current one.
Example2:
<?php
$nextmonth = date('Y-' . (date('n') + 1) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo 'Today is ' . date('d M Y') . '.<br />\n';
echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';
?>
Output:
Today is 15 Mar 2005.
The first Tuesday of next month is 05 Apr 2005.
Explanation:
$nextmonth = date('Y-' . (date('n') + 1) . '-01');
The inner call to date() returns an integer corresponding to the current month, to which
you add 1. You then use this as part of the argument to another date() call, which returns the
string 2005-4-01.
$nextmonth_ts = strtotime($nextmonth);:
This stores the timestamp equivalent to 2005-4-01 in $nextmonth_ts.
echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';:
Finally, you feed the $firsttue_ts timestamp to date() and output the result in dd-MM-
yyyy format.
Example3:
<?php
echo 'Today is ' . date('d M Y') . '.';
for($i = 1; $i <= 12; $i++)
{
$nextmonth = date('Y-' . (date('n') + $i) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo '\n<br />The first Tuesday in ' . date('F', $firsttue_ts)
. ' is ' . date('d M Y', $firsttue_ts) . '.';
}
?>
Output:
Today is 15 Mar 2005.
The first Tuesday of April is 05 Apr 2005.
The first Tuesday of May is 03 May 2005.
The first Tuesday of June is 07 Jun 2005.
The first Tuesday of July is 05 Jul 2005.
The first Tuesday of August is 02 Aug 2005.
The first Tuesday of September is 06 Sep 2005.
The first Tuesday of October is 04 Oct 2005.
The first Tuesday of November is 01 Nov 2005.
The first Tuesday of December is 06 Dec 2005.
The first Tuesday of January is 03 Jan 2006.
The first Tuesday of February is 07 Feb 2006.
The first Tuesday of March is 07 Mar 2006.
NOTE: The numbering of the days of the year as derived using date('z') begins with 0, which
means you will likely need to add 1 to the result before displaying it.
Getting the number of the week in the year is also quite simple: all that is required is to pass
an uppercase was a formatting character to date().
Example5:
<?php
$mydates = array('2005-01-01', '2005-01-03', '2005-05-22', '2005-05-23',
'2005-12-31');
foreach($mydates as $mydate)
echo date("D d M Y: \w\e\e\k W", strtotime($mydate)) . "<br />\n";
?>
Output:
Sat 01 Jan 2005: week 53
Mon 03 Jan 2005: week 1
Sun 22 May 2005: week 20
Example6:
<?php
NOTE: A final note regarding leap years: you should remember that years ending in 00 are leap
years only if the first two digits of the year taken as a two-digit number are evenly divisible by 4.
This means that although 2000 was a leap year (20 % 4 = 0), 1900 and 2100 are not (19 % 4 = 3;
21 % 4 = 1).
As you have already had the chance to see, altering a date by a given interval is not difficult.
Getting the difference between two dates is a bit more complicated.
Example7:
<?php
$date1 = '14 Jun 2002';
$date2 = '05 Feb 2006';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$min = ($ts2 - $ts1)/60;
$hour =$min/60;
$day = $hour/24;
printf("<p>The difference between %s and %s is %d seconds.<p>\n",$date1, $date2, $ts2
- $ts1);
printf("<p>The difference between %s and %s is %d minutes.<p>\n",$date1, $date2
,$min);
printf("<p>The difference between %s and %s is %d hours.<p>\n",$date1, $date2,
$hour);
printf("<p>The difference between %s and %s is %d days.<p>\n",$date1, $date2, $day);
?>
Output:
The difference between 14 Jun 2002 and 05 Feb 2006 is 115084800 seconds.
The difference between 14 Jun 2002 and 05 Feb 2006 is 1918140 minutes.
The difference between 14 Jun 2002 and 05 Feb 2006 is 31969 hours.
The difference between 14 Jun 2002 and 05 Feb 2006 is 1332 days.
Example8:
<?php
echo 'Number of days for the month of '.date('M'). ' is :' .date('t')."\n";
?>
Output:
Number of days for the month of Sep is: 30
Example9:
<?php
echo cal_days_in_month(CAL_GREGORIAN, 10, 2014);
echo date('t',strtotime('2014/10/01'));
?>
Output:
31
31
strptime() Given a date/time string generated with strftime() and the formatting string
used to generate it, returns a Unix timestamp (new in PHP 5.1).
strtotime() Converts an English textual date/time description into a Unix timestamp.
time() Returns the current system date and time as a Unix timestamp.
Formatting Characters for the date() Function
Character Description
Month
F Full name of the month (January, February, and so on).
M Three-letter abbreviation for the month (Jan, Feb, and so on).
m Numeric representation for the month, with leading zero (two digits).
n Numeric representation for the month (no leading zero).
Day
d Day of the month, with leading zeros (two digits).
j Day of the month (no leading zeros).
S Ordinal suffix for the day of the month, two characters (st, nd, th); most
commonly used in combination with j.
l (lowercase L) Full name of the day of the week (Monday, Tuesday, and so on).
Year
y Two-digit year.
Y Four-digit year.
Hour
h Hour in 12-hour format, with leading zero (two digits).
g Hour in 12-hour format (no leading zero).
H Hour in 24-hour format, with leading zero (two digits).
G Hour in 24-hour format (no leading zero).
a am/pm (lowercase).
A AM/PM (uppercase).
O (uppercase o) String representation of the difference in hours between local time and
GMT/UTC (for example, +1000, –0500).
Minute
Second
s Second, with leading zero (two digits).
Z Integer representation of the difference in seconds between local time and
GMT/UTC (for example, 36000 for GMT+1000 and –18000 for GMT–
0500).
To obtain a timestamp for the current system date and time, it is necessary only to call the
time() function, as shown here:
<?php
echo time();
?>
In a web browser, this produces output such as the following:
1110638611
For obtaining a human-readable date and time, PHP provides the date() function. When
called with a single argument (a formatting string), this function returns a string
representation of the current date and/or time. The optional second argument is a
timestamp.
Example1:
<?php
$time = time();
$formats = array(
'U',
'r',
'c',
how you can determine the date of the first Tuesday in the month following the current
one.
Example2:
<?php
$nextmonth = date('Y-' . (date('n') + 1) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo 'Today is ' . date('d M Y') . '.<br />\n';
echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';
?>
Output:
Today is 15 Mar 2005.
The first Tuesday of next month is 05 Apr 2005.
Explanation:
$nextmonth = date('Y-' . (date('n') + 1) . '-01');
The inner call to date() returns an integer corresponding to the current month, to which you add
1. You then use this as part of the argument to another date() call, which returns the string 2005-
4-01.
$nextmonth_ts = strtotime($nextmonth);:
This stores the timestamp equivalent to 2005-4-01 in $nextmonth_ts.
echo 'The first Tuesday of next month is ' . date('d M Y', $firsttue_ts) . '.';:
Finally, you feed the $firsttue_ts timestamp to date() and output the result in dd-MM-yyyy
format.
Example3:
<?php
echo 'Today is ' . date('d M Y') . '.';
for($i = 1; $i <= 12; $i++)
{
$nextmonth = date('Y-' . (date('n') + $i) . '-01');
$nextmonth_ts = strtotime($nextmonth);
$firsttue_ts = strtotime("Tuesday", $nextmonth_ts);
echo '\n<br />The first Tuesday in ' . date('F', $firsttue_ts)
. ' is ' . date('d M Y', $firsttue_ts) . '.';
}
?>
Output:
Today is 15 Mar 2005.
The first Tuesday of April is 05 Apr 2005.
The first Tuesday of May is 03 May 2005.
$ts = strtotime($mydate);
echo 'Day ' . date('d M Y: z', $ts) . "<br />\n";
}
?>
Output:
01 Jan 2005: Day 0
30 Jun 2005: Day 180
31 Dec 2005: Day 364
NOTE: The numbering of the days of the year as derived using date('z') begins with 0, which
means you will likely need to add 1 to the result before displaying it.
Getting the number of the week in the year is also quite simple: all that is required is to
pass an uppercase was a formatting character to date().
Example5:
<?php
$mydates = array('2005-01-01', '2005-01-03', '2005-05-22', '2005-05-23',
'2005-12-31');
foreach($mydates as $mydate)
echo date("D d M Y: \w\e\e\k W", strtotime($mydate)) . "<br />\n";
?>
Output:
Sat 01 Jan 2005: week 53
Mon 03 Jan 2005: week 1
Sun 22 May 2005: week 20
Mon 23 May 2005: week 21
Sat 31 Dec 2005: week 52
Determining Whether a Given Year Is a Leap Year
The date() function employs another one-letter argument; it uses L to determine if a given
year is a leap year.
When L is used, date() returns 1 if the year in question is a leap year and 0 if it is not.
Rather than make repeated calls to date() and strtotime(), you can wrap this in a simple
function that takes the year to be tested as an argument, as shown in the following
example.
Example6:
<?php
// takes a 2- or 4-digit year,
// returns 1 or 0
function is_leap_year($year)
{
$ts = strtotime("$year-01-01");
return date('L', $ts);
}
// test the function for a set of 11 consecutive years
for($i = 2000; $i <= 2010; $i++)
{
$output = "$i is ";
If( !is_leap_year($i) )
$output .= "not ";
$output .= "a leap year.<br />\n";
echo $output;
}
?>
How It Works
The result of the test loop is as follows:
2000 is a leap year.
2001 is not a leap year.
2002 is not a leap year.
2003 is not a leap year.
2004 is a leap year.
2005 is not a leap year.
2006 is not a leap year.
2007 is not a leap year.
2008 is a leap year.
2009 is not a leap year.
2010 is not a leap year.
NOTE: A final note regarding leap years: you should remember that years ending in 00 are leap
years only if the first two digits of the year taken as a two-digit number are evenly divisible by 4.
This means that although 2000 was a leap year (20 % 4 = 0), 1900 and 2100 are not (19 % 4 = 3;
21 % 4 = 1).
Obtaining the Difference between Two Dates
As you have already had the chance to see, altering a date by a given interval is not
difficult.
Getting the difference between two dates is a bit more complicated.
Example7:
<?php
$date1 = '14 Jun 2002';
$date2 = '05 Feb 2006';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$min = ($ts2 - $ts1)/60;
$hour =$min/60;
$day = $hour/24;
printf("<p>The difference between %s and %s is %d seconds.<p>\n",$date1, $date2, $ts2
- $ts1);
printf("<p>The difference between %s and %s is %d minutes.<p>\n",$date1, $date2 ,$min);
printf("<p>The difference between %s and %s is %d hours.<p>\n",$date1, $date2, $hour);
printf("<p>The difference between %s and %s is %d days.<p>\n",$date1, $date2, $day);
?>
Output:
The difference between 14 Jun 2002 and 05 Feb 2006 is 115084800 seconds.
The difference between 14 Jun 2002 and 05 Feb 2006 is 1918140 minutes.
The difference between 14 Jun 2002 and 05 Feb 2006 is 31969 hours.
The difference between 14 Jun 2002 and 05 Feb 2006 is 1332 days.
Determining the number of days in the current month
We are using date(‘t’) function for finding number of days in a month.
For finding number of days in current months we use both date(‘t’) and date(‘M’)
functions.
Example8:
<?php
echo 'Number of days for the month of '.date('M'). ' is :' .date('t')."\n";
?>
Output:
Number of days for the month of Sep is: 30
Determining the number of days in any given month
The cal_days_in_month() function returns the number of days in a month for a specified
year and calendar.
Syntax is
int cal_days_in_month ( int $calendar , int $month , int $year )
Example9:
<?php
echo cal_days_in_month(CAL_GREGORIAN, 10, 2014);
echo date('t',strtotime('2014/10/01'));
?>
Output:
31
31
Convert the month number to month name.
Example:
<?php
echo 'Write your code here';
$month_num = 9;
$dateObj = DateTime::createFromFormat('!m', $month_num);
$month_name = $dateObj->format('F');
echo $month_name."\n";
?>
Output:
September
Count the number of days between current day and birthday.
<?php
$target_days = mktime(0,0,0,12,31,2018);// modify the birth day 12/31/2013
$today = time();
$diff_days = ($target_days - $today);
$days = (int)($diff_days/86400);
print "Days till next birthday: $days days!"."\n";
?>
PHP FORM
A form is an HTML tag that contains graphical user interface items such
as input box, check boxes radio buttons etc.
The form is defined using the <form>...</form> tags and GUI items are
defined using form elements such as input.
WHEN AND WHY WE ARE USING FORMS?
Forms come in handy when developing flexible and dynamic applications
that accept user input.
Forms can be used to edit already existing data from the database
CREATE A FORM
We will use HTML tags to create a form. The list of things used to create a form
is
Opening and closing form tags <form>…</form>
Form submission type POST or GET
Submission URL that will process the submitted data
Input fields such as input boxes, text areas, buttons, checkboxes etc.
The code below creates a simple registration form
<html>
<head><title>Registration Form</title></head>
<body>
<form action="registration_form.php" method="POST">
First name: <input type="text" name="firstname"> <br>
Last name: <input type="text" name="lastname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Viewing the above code in a web browser displays the following form.
Here,
<form…>…</form> are the opening and closing form tags
action="registration_form.php" method="POST"> specifies the destination
URL and the submission type.
First/Last name: are labels for the input boxes
<input type=”text”…> are input box tags
<br> is the new line tag
<input type="submit" value="Submit"> is the button that when clicked
submits the form to the server for processing
UNDERSTANDING COMMON FORM ISSUES
When dealing with forms, the most important aspect to remember is that you
are limited to a certain variety of fields that can be applied to a form. The fields
that have been created are non-negotiable and work in only the way they were
created to work. It is important, therefore, to fully understand what is available
and how best to use the form features to your advantage.
Element Description
TEXT INPUT A simple text box
PASSWORD INPUT A text box that hides the characters inputted
HIDDEN INPUT A field that does not show on the form but can
contain data
SELECT A drop-down box with options
LIST A select box that can have multiple options
selected
When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form data is
sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables.
WELCOME.PHP:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
Output: Welcome Uday
Your email address is [email protected]
GET: When sending data using the GET method, all fields are appended to the
Uniform Resource Locator (URL) of the browser and sent along with the
address as data. Sending data using the GET method means that fields are
generally capped at 150 characters, which is certainly not the most effective
means of passing information. It is also not a secure means of passing data,
because many people know how to send information to a script using an
address bar.
Example
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
WELCOME_GET.PHP:
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
GET VS POST METHODS
POST
Values not visible in the URL.
Has not limitation of the length of the values since they are submitted via
the body of HTTP.
Has lower performance compared to PHP_GET method due to time spent
encapsulation the PHP_POST values in the HTTP body
Supports many different data types such as string, numeric, binary etc.
Results cannot be book marked
GET
Values visible in the URL
Has limitation on the length of the values usually 255 characters. This is
because the values are displayed in the URL. Note the upper limit of the
characters is dependent on the browser.
Has high performance compared to POST method dues to the simple
nature of appending the values in the URL.
Supports only string data types because the values are displayed in the
URL
Results can be book marked due to the visibility of the values in the URL
EXAMPLES:
Valid URL: Below code shows validation of URL
$website = input($_POST["site"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-
a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
Above syntax will verify whether a given URL is valid or not. It should allow
some keywords as https, ftp, www, a-z, 0-9,..etc..
Valid Email: Below code shows validation of Email address
$email = input($_POST["email"]);
if (!filter_var ($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid format and please re-enter valid email";
}
Above syntax will verify whether given Email address is well-formed or not.if it
is not, it will show an error message.
</html>
VALIDATE.PHP
<?php
if(isset($_POST['submit']))
{
if (empty($_POST["username"]))
echo "Name is required"."<br>";
else
{
$name = $_POST["username"];
if (!preg_match("/^[a-zA-Z ]*$/",$name))
echo "Only letters and white space allowed"."<br>";
}
if (empty($_POST["password"]))
echo "Password is required"."<br>";
else
{
$pass = $_POST["password"];
if (!preg_match("/^[a-zA-Z ]*$/",$pass))
echo "Only letters and white space allowed"."<br>";
}
if (empty($_POST["email"]))
echo "Email is required"."<br>";
else
{
$email = $_POST["email"];
if (!preg_match("/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/",$email))
echo "Invalid email format"."<br>";
or
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
echo "Invalid email format"."<br>";
}
}
?>
Example program2:
<html>
<body>
<?php
// define variables and set to empty values
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method = "post" action = "<?php echo htmlspecialchars
($_SERVER["PHP_SELF"]); ?>">
Name : <input type = "text" name = "name">
E-mail: <input type = "text" name = "email">
Time: <input type = "text" name = "website">
Classes: <textarea name="comment"rows="5"cols= "40"></textarea>
Gender:
<input type = "radio" name = "gender" value = "female">Female
<input type = "radio" name = "gender" value = "male">Male
<input type = "submit" name = "submit" value = "Submit">
</form>
<?php
echo "<h2>Your given values are as:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
WORKING WITH MULTIPAGE FORMS: Sometimes you will need to collect
values from more than one page. Most developers do this for the sake of clarity.
By providing forms on more than one page, you can separate blocks of
information and thus create an ergonomic experience for the user. The
problem, therefore, is how to get values from each page onto the next page and
finally to the processing script. Being the great developer that you are, you can
solve this problem and use the hidden input form type. When each page loads,
you must load the values from the previous pages into hidden form elements
and submit them
PAGE1.HTML
<html >
<head><title> Page1</title></head>
<body>
<form action=" page2.php" method="post">
Your Name: <input type="text"name="name" maxlength="150" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
PAGE2.HTML
<html>
<head><title> Page2</title></head>
<body>
<form action="page3.php" method="post">
Selection: <select name="selection">
<option value="nogo">make a selection...</option>
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
<option value="3">Choice 3</option>
</select><br /><br />
<input type="hidden"name="name"value="<?php echo $_POST['name']; ?>" />
<input type="submit" value="Submit" />
Prepared By: Dept Of CSE, RGMCET Page 12
PHP PROGRAMMING
</form>
</body>
</html>
PAGE3.HTML
<html>
<head><title> Page3</title></head>
<body>
<form action="page4.php" method="post">
Your Email: <input type="text" name="email" maxlength="150" /><br />
<input type="hidden"name="name"value="<?php echo $_POST['name']; ?>" />
<input type="hidden"name="selection"value="<?php echo_POST['selection'];?>"
/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
PAGE4.PHP
<html>
<head><title>Page4</title></head>
<body>
<?php
echo "Your Name: " . $_POST['name'] . "<br />";
echo "Your Selection: " . $_POST['selection'] . "<br />";
echo "Your Email: " . $_POST['remail'] . "<br />";
?>
<a href="page1.php">Try Again</a>
</body>
</html>
PREVENTING MULTIPLE SUBMISSIONS OF A FORM: One possible
occurrence that happens often is that users become impatient when waiting for
your script to do what it is doing, and hence they click the submit button on a
form repeatedly. This can cause great damage on your script because, while the
user may not see anything happening, your script is probably going ahead with
whatever it has been programmed to do. If a user continually hits the submit
button on a credit card submittal form, their card may be charged multiple
times if the developer has not taken the time to validate against such an
eventuality. You can deal with multiple submittal validation in two ways.
<html>
<head>
<script language="javascript" type="text/javascript">
function checkandsubmit()
{ //Disable the submit button.
document.test.submitbut.disabled = true;
//Then submit the form.
document.test.submit();
}
</script>
</head>
<body>
<form action="process.php"method="post"name="test"onsubmit="return
checkandsubmit ()">
Your Name: <input type="text" name="name" maxlength="150" /><br />
<input type="submit"value="Submit"id="submitbut" name"submitbut"/>
</form>
</body>
</html>
PROCESS.PHP
<?php
for ($i = 0; $i < 2000000; $i++)
{
//Thinking...
}
if ($file = fopen ("test.txt","w+"))
fwrite ($file, "Processing");
else
echo "Error opening file.";
echo $_POST['yourname'];
?>
PROCESSING THE REGISTRATION FORM DATA
The registration form submits data to itself as specified in the action
attribute of the form.
When a form has been submitted, the values are populated in the
$_POST super global array.
We will use the PHP isset function to check if the form values have been
filled in the $_POST array and process the data.
We will modify the registration form to include the PHP code that
processes the data. Below is the modified code
<html>
<head><title>Registration Form</title></head>
<body>
<?php if (isset($_POST['form_submitted'])): ?>
//this code is executed when the form is submitted
<h2>Thank You <?php echo $_POST['firstname']; ?> </h2>
<p>You have been registered as
<?php echo $_POST['firstname'] . ' ' . $_POST['lastname']; ?>
</p>
<p>Go <a href="/registration_form.php">back</a> to the form</p>
<?php else: ?>
<h2>Registration Form</h2>
<form action="registration_form.php" method="POST">
First name:
<input type="text" name="firstname">
<br> Last name:
<input type="text" name="lastname">
<input type="hidden" name="form_submitted" value="1" />
<input type="submit" value="Submit">
</form>
<?php endif; ?>
</body>
</html>
Here,
Minimum Maximum
Storage Minimum Value Maximum Value
Type (Bytes) Value Signed Unsigned Value Signed Unsigned
TINYINT 1 -128 0 127 255
SMALLINT 2 -32768 0 32767 65535
MEDIUMINT 3 -8388608 0 8388607 16777215
Minimum Maximum
Storage Minimum Value Maximum Value
Type (Bytes) Value Signed Unsigned Value Signed Unsigned
INT 4 -2147483648 0 2147483647 4294967295
BIGINT 8 -263 0 263-1 264-1
FLOAT (10,2)
This data type can store decimal values. We can store total digits 10 and
after decimal 2 digits.
DOUBLE (16,4)
We can store total number of digits are 16 and after decimal 4.
DECIMAL
Same as floating point number but cannot be unsigned.
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
echo "Connected successfully";
?>
Or
<?php
$con=mysql_connect(localhost”,”root”,””);
if($con)
echo “connected”;
else
echo “Not connected”;
?>
Example: To create a database in MySQL
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql))
echo "Database created successfully";
else
echo "Error creating database: " . mysqli_error($conn);
mysqli_close($conn);
?>
Example: To select a database in MySQL
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
$sql =mysql_select_db($conn,”myDB”);
if (mysqli_query($conn, $sql))
echo "Database selected successfully";
else
echo "Error selecting database: " . mysqli_error($conn);
mysqli_close($conn);
?>
Example: To create a table in MySQL
<?php
$link = mysqli_connect("localhost", "root", "");
if($link == false)
die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "CREATE TABLE persons(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
email VARCHAR(70) NOT NULL UNIQUE )";
if(mysqli_query($link, $sql))
echo "Table created successfully.";
else
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
mysqli_close($link);
?>
Example: To insert a record in a table
<?php
$link = mysqli_connect("localhost", "root", "", "");
if($link == false)
die("ERROR: Could not connect. " . mysqli_connect_error());
if(mysqli_num_rows($result) > 0)
{
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
}
else
{
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
Filtering the Records
The WHERE clause is used to extract only those records that fulfill a specified
condition.
<?php
$link = mysqli_connect("localhost", "root", "");
if($link === false)
die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "SELECT * FROM persons WHERE first_name='john'";
if($result = mysqli_query($link, $sql))
{
if(mysqli_num_rows($result) > 0)
{
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
Updating Database Table Data
The UPDATE statement is used to change or modify the existing records in a
database table. This statement is typically used in conjugation with the
WHERE clause to apply the changes to only those records that matches
specific criteria.
<?php
$link = mysqli_connect("localhost", "root", "");
if($link === false)
die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "UPDATE persons SET email='[email protected]' WHERE
id=1";
if(mysqli_query($link, $sql))
echo "Records were updated successfully.";
else
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
mysqli_close($link);
?>
Deleting Database Table Data
Just as you insert records into tables, you can delete records from a table
using the SQL DELETE statement. It is typically used in conjugation with the
WHERE clause to delete only those records that matches specific criteria or
condition.
<?php
$link = mysqli_connect("localhost", "root", "");
if($link === false)
die("ERROR: Could not connect. " . mysqli_connect_error());
$sql = "DELETE FROM persons WHERE first_name='John'";
if(mysqli_query($link, $sql))
echo "Records were deleted successfully.";
else
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
mysqli_close($link);
?>
$_SERVER
$_REQUEST
$_GET
$_POST
$_SESSION
$_COOKIE
$_FILES
$_ENV
1. $GLOBALS
It is a super global variable which is used to access global variables from
anywhere in the PHP script.
PHP stores all the global variables in array $GLOBALS [ ] it consist of an
array which have an index that holds the global variable name, which
can be accessed.
Example:
<?php
$x = 300;
$y = 200;
function multiplication()
{
$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
}
multiplication();
echo $z;
?>
Output:
60000
2. $_SERVER
The following table lists the most important elements that can go inside
$_SERVER:
Element/Code Description
3. $_REQUEST
The PHP $_REQUEST variable contains the contents of both $_GET,
$_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the result from form
data sent with both the GET and POST methods. By using this we can
also get values of cookie and query string.
Form.html
<form method=”GET” action=”p1.php”>
<input type=”textbox” name=”t1” ><br>
<input type=”textbox” name=”t2” ><br>
<input type=”submit” name=”b1” value=”click” ><br>
</form>
P1.php
<?php
print_r($_GET);
echo $_GET[“t1”];
echo $_GET[“t2”];
echo $_GET[“b1”];
?>
Output:
Array([t1]->uday [t2]->cse [sub]->click)
uday cse click
5. $_POST
The $_POST variable is an array of variable names and values sent by
the HTTP POST method.
The $_POST variable is used to collect values from a form with
method="post".
Information sent from a form with the POST method is invisible to others
and has no limits on the amount of information to send.
If more than one submit controls are there in the form, then only one
control should pass to server.
Example:
Form.php
<?php
$txt1=$_POST[‘t1’];
$txt2=$_POST[‘t2’];
echo “value is”.$txt1;
echo “value is”.$txt2;
?>
<form method=”GET” action=” ”>
<input type=”textbox” name=”t1” ><br>
<input type=”textbox” name=”t2” ><br>
<input type=”submit” name=”b1” value=”click” ><br>
</form>
NOTE: In the above example, the php script is first executed. Since the form is
not yet executed, the values are undefined for txt1 and txt2 variables. Thus to
eliminate this problem, we rewrite the code as:
<?php
if(isset($_POST[‘b1]))
{
error_reporting(E_ALL);
$txt1=$_POST[‘t1’];
$txt2=$_POST[‘t2’];
echo “value is”.$txt1;
echo “value is”.$txt2;
}
?>
<form method=”GET” action=” ”>
<input type=”textbox” name=”t1” ><br>
<input type=”textbox” name=”t2” ><br>
<input type=”submit” name=”b1” value=”click” ><br>
</form>
When you are working with an application, you open it, do some changes
and then you close it. This is much like a Session. The computer knows
who you are. It knows when you start the application and when you end.
But on the internet there is one problem: the web server does not know
who you are and what you do because the HTTP address doesn't
maintain state.
A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping items,
etc). However, session information is temporary and will be deleted after
the user has left the website. If you need a permanent storage you may
want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must
first start up the session.
The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you
to start saving user information, and assign a UID for that user's session.
The correct way to store and retrieve session variables is to use the PHP
$_SESSION variable:
Example:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset()
function checks if the "views" variable has already been set. If "views" has been
set, we can increment our counter. If "views" doesn't exist, we create a "views"
variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the
session_destroy() function.
The unset() function is used to free the specified session variable:
The session_destroy() will reset your session and you will lose all your
stored session data.
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy()
function:
<?php
session_destroy();
?>
7. $_COOKIE
Cookie is a state management object used to maintain state of
application.
Data of cookie will store in browser memory location. This data can be
accessed from any web page in an application.
A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer
requests a page with a browser, it will send the cookie too. With PHP, you
can both create and retrieve cookie values.
Cookie is state
A cookie is often used to identify a user.
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
Example
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
Example
Pro.php
<?php
setcookie(x,100);
echo $_COOKIE[‘x’];
?>
<a href=”p1.php”>GO</a>
P1.php
<?php
echo “HI”;
echo $_COOKIE[‘x’];
?>
NOTE:
At the time of 1st execution, the value of x is not shown in the output. Since
the time setcookie() is creating the cookie, the next statement is executed. This
setcookie() takes some time to create cookie, thus we are unable to see value of
x at first execution.
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
HOW TO CREATE PERSISTENCE COOKIES?
There are four steps to create persistence cookies.
1. Find out current date and time information when cookie is downloading
into client system.
2. Add lifetime to current date and time to get expiry time.
3. Create cookie in client system with the resultant expiry time.
<?php
setcookie(“sno”,123,time()+3600);
Current time Expiry(in Sec)
echo $_COOKIE[‘sno’];
?>
4. We can destroy the cookies before its expiry time by recreating the cookie
with completed time.
<?php
setcookie(“sno”,’ ‘,time()-1);
?>
WHAT IF A BROWSER DOES NOT SUPPORT COOKIES?
If your application deals with browsers that do not support cookies, you
will have to use other methods to pass information from one page to
another in your application. One method is to pass the data through
forms (forms and user input are described earlier in this tutorial).
The form below passes the user input to "welcome.php" when the user
clicks on the "Submit" button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
LIMITATIONS OF COOKIE:
1. It can store limited amount of data.
2. It can store only text data.
3. Data of cookie is storing in browser memory location, that’s why we
should store secure information in cookies. If you want to store secure
data, we should get user’s permission.
Program: Pro.php
<?php
if(isset($_POST[‘sub’]))
{
$sp=$_POST[‘d1’];
$qty=$_POST[‘tqty’];
setcookie($sp,$qty);
}
?>
<form method=”post” action=” ”>
Select Product:<select name=”d1”>
<option>Samsung</option>
<option>Nokia</option>
<option>Apple</option>
</select><br>
Enter Quantity:<input name=”tqty”>
<br>
<input name=”submit” type=”submit” value=”Add to Cart”>
</form>
<a href=”bill.php”>Bill</a>
Bill.php
<?php
foreach($_COOKIE as $k $v)
{
echo $k;
echo “=”;
echo $v;
echo “<br>”;
}
?>
8. $_FILES
By using this, we can get information of uploaded file.
Example:
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false)
{
$errors[]="extension not allowed, please choose a JPEG or PNG
file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}
else{
print_r($errors);
}
}
?>
<html>
<body>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "image" />
<input type = "submit"/>
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>
</form>
</body>
</html>
Output:
MIME:
It stands for Multipurpose Internet Mailing Extension.
It is a type of extension used to upload a file from browser to server.
Every file contains different types of MIME types to upload into server
from browser.
Available MIME types are:
1. jpg - image/jpeg
Prepared By: Dept Of CSE, RGMCET Page 52
PHP PROGRAMMING
2. bmp - image/bmp
3. exe - application/octet-stream
4. pdf - application/pdf
5. multipart/form-data - using this we can upload any type of file
from browser to server.
6. is_uploaded_file - using this function, we can check a file can be
uploaded or not from temporary memory
location to permanent memory location.
7. move_uploaded_file - to move the uploaded file from temporary
memory location to permanent memory location.
Example: select.html
<form method=”POST” enctype=”multipart/form-data” action=”upload.php”>
Select File:<input name=”f1” type=”file”> <br>
<input name=”sub” type=”submit” value=”upload”>
</form>
Upload.php
<?php>
print_r($_FILES);
$fname=$_FILES[‘f1’][‘name’];
echo $fname;
if(move_uploaded_file($_FILES[‘f1][‘tmp_name’],”up/$fname”))
echo “File is moved”;
else
echo “Not”;
?>
Example: To allow all files except .exe files.
<?php
if($_FILES[‘f1’][type’]==”application/octet_stream”)
{
echo “exe not supported”
}
else
move_uploaded_file($_FILES[‘f1][‘tmp_name’],”up/”.$_FILES[‘f1][‘name’]);
?>
Without MIME types, we won’t be able to upload file, only txt controls will
be supported.
CONFIGURATION SETTINGS TO WORK WITH FILE UPLOAD CONCEPT:
file_upload
Using this we can allow and stop file uploads. Default value is ON, by
changing this value as OFF we can stop file uploads.
upload_tmp_dir
Using this we can change temporary directory location of uploaded file.
By default, all files will store in tmp folder.
upload_max_filesize
Using this we can increase or decrease maximum file size to upload the
files(by default 128MB).
PROTOCOLS:
Protocols are set of instructions to transfer data from one page to
another page.
Protocols are mainly divided into two types:
1. Stateful protocols:
These protocols can maintain the state of application. i.e. they can
remember previous pages data in current pages. In windows application, we
are using these protocols.
E.g., TCP/IP, FTP etc.
2. Stateless protocols:
Required field will check whether the field is filled or not in the proper way.
Most of cases we will use the * symbol for required field.
What is Validation?
Validation means check the input submitted by the user. There are two types
of validation are available in PHP. They are as follows −
1. Client-Side Validation − Validation is performed on the client machine
web browsers.
2. Server Side Validation − After submitted by data, the data has sent to a
server and perform validation checks in server machine.
<html>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Absolute classes registration</h2>
<p><span class = "error">* required field.</span></p>
<form method = "post"
action = "<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Name:</td>
<td><input type = "text" name = "name">
<span class = "error">* <?php echo
$nameErr;?></span>
</td>
</tr>
<tr>
<td>E-mail: </td>
<td><input type = "text" name = "email">
<span class = "error">* <?php echo
$emailErr;?></span>
</td>
</tr>
<tr>
<td>Time:</td>
<td> <input type = "text" name = "website">
<span class = "error"><?php echo $websiteErr;?></span>
</td>
</tr>
<tr>
<td>Classes:</td>
die(): It is an inbuilt function in PHP. It is used to print message and exit from
the current php script. It is equivalent to exit() function in PHP.
<?php
$site = "";
fopen($site, "r")
or die("Unable to connect to given site.");
?>
Output: Unable to connect to given site.
CONSTRAINTS IN MYSQL
MySQL CONSTRAINT is used to define rules to allow or restrict what
values can be stored in columns. The purpose of inducing constraints is
to enforce the integrity of a database.
MySQL CONSTRAINTS are used to limit the type of data that can be
inserted into a table.
MySQL CONSTRAINTS can be classified into two types - column level
and table level.
The column level constraints can apply only to one column whereas table
level constraints are applied to the entire table.
MySQL CONSTRAINT is declared at the time of creating a table.
Constrains are used to apply some conditions on tables. MySQL is
supporting different types of constraints.
1. NOT NULL
MySQL NOT NULL constraint allows to specify that a column can not contain
any NULL value. MySQL NOT NULL can be used to CREATE and ALTER a
table.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,FirstName varchar(255) NOT NULL, Age int );
2. UNIQUE
The UNIQUE constraint in MySQL does not allow to insert a duplicate value in
a column. The UNIQUE constraint maintains the uniqueness of a column in a
table. More than one UNIQUE column can be used in a table.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,FirstName varchar(255), Age int, UNIQUE (ID) );
3. PRIMARY KEY
A PRIMARY KEY constraint for a table enforces the table to accept unique data
for a specific column and this constraint creates a unique index for accessing
the table faster.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,FirstName varchar(255), Age int, PRIMARY KEY (ID) );
4. AUTO_INCREMENT
AUTO_INCREMENT allows a unique number to be generated automatically
when a new record is inserted into a table. Often this is the primary key field
that we would like to be created automatically every time a new record is
inserted.
Example:
CREATE TABLE Persons ( ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL, FirstName
varchar(255),Age int, PRIMARY KEY (ID) );
5. DEFALUT
The DEFAULT constraint is used to provide a default value for a column. The
default value will be added to all new records IF no other value is specified.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,
FirstName varchar(255), Age int,
City varchar(255) DEFAULT 'Sandnes' );
6. FOREIGN KEY
A FOREIGN KEY in MySQL creates a link between two tables by one specific
column of both tables. The specified column in one table must be a PRIMARY
KEY and referred by the column of another table known as FOREIGN KEY.
Example:
CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT
NULL,
PersonID int, PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES
Persons(PersonID) );
7. CHECK
A CHECK constraint controls the values in the associated column. The CHECK
constraint determines whether the value is valid or not from a logical
expression.
Example:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL,FirstName varchar(255), Age int, CHECK (Age>=18) );
mysql_fetch_assoc():
This function fetches the record from result set and it returns output as an
associative array. Key is a column names, values are column values.
mysql_fetch_array():The mysql_fetch_array() function returns a row from a recordset as an
associative array and/or a numeric array. This function gets a row from the mysql_query() function and
returns an array on success, or FALSE on failure or when there are no more rows .It is combination
of previous two functions reads a record from result set and returns output as
an associative array, a numeric array, or both
mysql_fetch_object():
It reads a record from result set and returns output as an object. Object is a
collection of properties. Property names are column names and values are
column values. This object belongs to stdclass.
mysql_num_fields():The To get total number of fields from result set.
mysql_fetch_field():mysql_fetch_field() function returns an object containing
information of a field from a recordset. This function gets field data from the
mysql_query() function and returns an object on success, or FALSE on failure
or when there are no more rows.
To fetch complete information of a field and returns output as an object.
mysql_fetch_field($result)
mysql_field_type():
To get the type of field from the result set.
mysql_field_len():
To get the length of the field from result set.
mysql_get_client_info():
To get version information of mysql database.
mysql_data_seek():
To locate result set pointer on specified record.
mysql_field_seek():
To locate result set pointer on specified column.
mysql_close():
To close the opened mysql connections.
mysql_list_dbs():
To get list of databases available.
mysql_list_tables():
To get the list of tables available in a database.
https://www.studentstutorial.com/php/php-update-multiple-row.php