PHP
PHP:HYPERTEXT PREPROCESSOR
Prepared By
Yogaraja C A
Ramco Institute of Technology
INTRODUCTION
 PHP is a server scripting language, and a powerful tool for
making dynamic and interactive Web pages.
 PHP can be easily embedded in HTML files and HTML codes can
also be written in a PHP file
 PHP is a widely-used
 Opensource
 Simple Language
 Object Oriented
 PHP 7 is the latest stable release.
 Loosely Typed – Contains different type of data at different times
SYNTAX
 A PHP script can be placed anywhere in the document.
 The default file extension for PHP files is ".php".
 A PHP script starts with <?php and ends with ?>
 PHP statements end with a semicolon (;).
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
SYNTAX(Case Sensitivity)
 In PHP, NO keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are case-sensitive.
 PHP will ignore all the spaces or tabs in a single row or carriage return in multiple rows.
 Unless a semi-colon is encountered, PHP treats multiple lines as a single command.
 PHP Variables are case Sensitive
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
$COLOR="BLUE"
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
?>
</body>
</html>
SYNTAX(Comments)
 A comment is something which is ignored and not read or
executed by PHP engine or the language as part of a program
 It is written to make the code more readable and
understandable.
 Single Line Comment
<?php
// This is a single line comment
echo "hello world!!!";
# This is also a single line comment
?>
SYNTAX(Comments)
 Multi-line or Multiple line Comment:
<?php
/* This is a multi line comment
In PHP variables are written
by adding a $ sign at the beginning.*/
?>
PHP Variables
 A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).
 Rules for PHP variables:
 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 cannot 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 ($age and $AGE are two different
variables)
PHP is a Loosely Typed Language
 PHP automatically associates a data type to the variable,
depending on its value.
 Since the data types are not set in a strict sense, you can do
things like adding a string to an integer without causing an
error.
PHP Variables Scope
 In PHP, variables can be declared anywhere in the script.
 The scope of a variable is the part of the script where the
variable can be referenced/used.
 PHP has three different variable scopes:
 local
 global
 Static
***The global keyword is used to access a global variable from
within a function.
PHP Data Types
 String
 Integer(2,147,483,648 and 2,147,483,647 or -2^31 to 2^31)
 Float (also called double)
 Boolean
 Array
 Object
 NULL
 Resource
PHP Constants
 A constant is an identifier (name) for a simple value. The value
cannot be changed during the script.
 A valid constant name starts with a letter or underscore (no $
sign before the constant name).
 ***Unlike variables, constants are automatically global across
the entire script.
 The define() function in PHP is used to create a constant
 define(name, value, case_insensitive)
 name: The name of the constant.
 value: The value to be stored in the constant.
 case_insensitive: Defines whether a constant is case insensitive. By
default this value is False, i.e., case sensitive.
PHP Constants
<?php
define("GREETING", "Welcome to india.com!");
echo GREETING;
?>
<?php
define("cars", ["Alfa Romeo", "BMW", "Toyota"]);
echo cars[0];
?>
PHP Operators
 PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators
PHP Conditional Statements
 In PHP we have the following conditional statements:
 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true
and another code if that condition is false
 if...elseif...else statement - executes different codes for more
than two conditions
 switch statement - selects one of many blocks of code to be
executed
PHP Loops
 while - loops through a block of code as long as the specified
condition is true
 do...while - loops through a block of code once, and then
repeats the loop as long as the specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an
array
foreach ($array as $value) {
code to be executed;
}
PHP functions
 Array
 Calendar
 Date
 Math
 Mail
 MySQLi
 String
 Error
PHP Array function
Function Description
array() Creates an array $cars=array("Volvo","BMW","Toyota");
array_combine() Creates an array by using the
elements from one "keys"
array and one "values" array
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
array_count_valu
es()
Counts all the values of an
array
$a=array("A","Cat","Dog","A","Dog");
print_r(array_count_values($a));
array_diff() Compare arrays, and returns
the differences (compare
values only)
$a1=array("a"=>"red","b"=>"green","c"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);
array_flip() Flips/Exchanges all keys with
their associated values in an
array
$a1=array("a"=>"red","b"=>"green");
$result=array_flip($a1);
array_merge() Merges one or more arrays
into one array
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
PHP Array function
Function Description
array_rand() Returns one or more random
keys from an array
$a=array("a"=>"red, "c"=>"blue","d"=>"yellow");
print_r(array_rand($a,1));
array_replace() Replaces the values of the
first array with the values
from following arrays
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2));
array_reverse() Returns an array in the
reverse order
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
array_search() Searches an array for a given
value and returns the key
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
array_unique() Removes duplicate values
from an array
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
count() Returns the number of
elements in an array
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
PHP Array function
Function Description
arsort() Sorts an associative array in
descending order, according
to the value
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
print_r($age);
asort() Sorts an associative array in
ascending order, according
to the value
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
print_r($age);
PHP Calendar function
Function Description
cal_days_in_mont
h()
Returns the number of days
in a month for a specified
year and calendar
$d=cal_days_in_month(CAL_GREGORIAN,10,2005);
echo $d;
jdmonthname() Returns a month name $jd=gregoriantojd(1,13,1998);
echo jdmonthname($jd,0);
0 - Gregorian - abbreviated form (Jan, Feb, Mar,
etc.)
1 - Gregorian (January, February, March, etc.)
2 - Julian - abbreviated form (Jan, Feb, Mar, etc.)
3 - Julian (January, February, March, etc.)
jddayofweek() Returns the day of the week $jd=gregoriantojd(1,13,1998);
echo jddayofweek($jd,1);
0 - Default. Returns 0=Sunday, 1=Monday, etc.
1 - Sunday, Monday, etc.
2 - Returns Sun, Mon, etc.
PHP Date function
Function Description
date() Formats a local
date and time
echo date("l")
d - The day of the month (from 01 to 31)
D - A textual representation of a day (three letters)
j - The day of the month without leading zeros (1 to 31)
l (lowercase 'L') - A full textual representation of a day
N - The ISO-8601 numeric representation of a day (1 for
Monday, 7 for Sunday)
S - The English ordinal suffix for the day of the month (2
characters st, nd, rd or th. Works well with j)
w - A numeric representation of the day (0 for Sunday, 6 for
Saturday)
z - The day of the year (from 0 through 365)
W - The ISO-8601 week number of year (weeks starting on
Monday)
F - A full textual representation of a month (January through
December)
m - A numeric representation of a month (from 01 to 12)
M - A short textual representation of a month (three letters)
PHP Date function
Function Description
getdate() Returns date/time
information of a
timestamp or the
current local
date/time
print_r(getdate());
Array ( [seconds] => 50 [minutes] => 16 [hours] => 9 [mday] => 17
[wday] => 1 [mon] => 2 [year] => 2020 [yday] => 47 [weekday] =>
Monday [month] => February [0] => 1581931010 )
time() Returns the current
time as a Unix
timestamp
echo($t);
echo(date("Y-m-d",$t));
1581931163
2020-02-17
date_diff() Returns the
difference between
two dates
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
date_date_
set()
Sets a new date $date=date_create();
date_date_set($date,2020,10,30);
echo date_format($date,"Y/m/d");
PHP Math function
Function Description
abs() Returns the absolute (positive) value of a number
base_convert() Converts a number from one number base to another $hex = "E196";
echo base_convert($hex,16,8);
ceil() Rounds a number up to the nearest integer
decbin() Converts a decimal number to a binary number
dechex() Converts a decimal number to a hexadecimal number
decoct() Converts a decimal number to an octal number
bindec() Converts a binary number to a decimal number
exp() Calculates the exponent of e echo(exp(4.8));
expm1() Returns exp(x) - 1
PHP Math function
Function Description
fmod() Returns the remainder of x/y
floor() Rounds a number down to the nearest integer
fmod() Returns the remainder of x/y
log() Returns the natural logarithm of a number
log10() Returns the base-10 logarithm of a number
max() Returns the highest value in an array, or the highest
value of several specified values
echo(max(array(44,16,81,12)));
min() Returns the lowest value in an array, or the lowest
value of several specified values
PHP Mail function
Function Description
mail() Allows you to send emails directly from a script mail("someone@example.com","My
subject",$msg);
PHP MYSQLi function
Function Description
mysqli_connect() opens a new connection to the MySQL
server.
$con = mysqli_connect("localhost",
"my_user", "my_password","my_db");
mysqli_query() performs a query against a database. $result = mysqli_query($con, "SELECT *
FROM Persons");
mysqli_fetch_array() fetches a result row as an associative
array, a numeric array, or both.
$row = mysqli_fetch_array($result);
mysqli_num_rows() eturns the number of affected rows
in the previous SELECT, INSERT,
UPDATE, REPLACE, or DELETE query.
mysqli_num_rows($result)
mysqli_close() closes a previously opened database
connection.
mysqli_close($con)
PHP string function
Function Description
md5() Calculates the MD5 hash of a string echo md5($str);
md5_file() Calculates the MD5 hash of a file $result = md5_file($filename);
trim() Removes whitespace or other
characters from both sides of a string
$str = "Hello World!";
echo trim($str,"Hed!");
ltrim() Removes whitespace or other
characters from the left side of a
string
$str = "Hello World Hello!";
echo ltrim($str,"Hello ");
rtrim() Removes whitespace or other
characters from the right side of a
string
$str = "Hello Word!";
echo rtrim($str,"odH!");
str_ireplace() Replaces some characters in a string
(case-insensitive)
echo str_ireplace("WORLD",“Rit","Hello
world!");
str_pad() Pads a string to a new length $str = "Hello World";
echo str_pad($str,20,".");
PHP string function
Function Description
str_repeat() Repeats a string a specified number of
times
echo str_repeat("Wow",13);
str_replace() Replaces some characters in a string (case-
sensitive)
echo str_replace("WORLD",“Rit","Hello
world!");
str_word_count() Count the number of words in a string echo str_word_count("Hello world!");
strip_tags() Strips HTML and PHP tags from a string echo strip_tags("Hello <b>world!</b>");
strrev() Reverses a string echo strrev("Hello World!");
strtolower() Converts a string to lowercase letters echo strtolower("Hello WORLD.");
strtoupper() Converts a string to uppercase letters echo strtoupper("Hello WORLD!");
ucfirst() Converts the first character of a string to
uppercase
echo ucfirst("hello world!");
ucwords() Converts the first character of each word in
a string to uppercase
echo ucwords("hello world");
PHP Error function
Function Description
error_clear_last() Clears the last error
error_get_last() Returns the last error that occurred
error_log() Sends an error message to a log, to a
file, or to a mail account
error_reporting() Specifies which errors are reported
Regular Expression
 A regular expression is an object that describes a pattern
of characters.
 Regular expressions commonly known as a regex (regexes)
are a sequence of characters describing a special search
pattern in the form of text string.
 Regular expressions help in validation of text strings which
are of programmer’s interest.
 It offers a powerful tool for analyzing, searching a pattern
and modifying the text data.
 It helps in searching specific string pattern and extracting
matching results in a flexible manner.
Regular Expression
REGULAR EXPRESSION MATCHES
rit The string “rit”
^rit The string which starts with “rit”
rit$ The string which have “rit” at the end.
^rit$ The string where “rit” is alone on a string.
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any letter which is NOT a uppercase letter
(gif|png) Either “gif” or “png”
[a-z]+ One or more lowercase letters
^[a-zA-Z0-9]{1, }$ Any word with at least one number or one letter
([ax])([by]) ab, ay, xb, xy
[^A-Za-z0-9] Any symbol other than a letter or other than number
([A-Z]{3}|[0-9]{5}) Matches three letters or five numbers
Operators in Regular Expression
OPERATOR DESCRIPTION
^ It denotes the start of string.
$ It denotes the end of string.
. It denotes almost any single character.
() It denotes a group of expressions.
[]
It finds a range of characters for example [xyz] means x, y or
z .
[^]
It finds the items which are not in range for example [^abc]
means NOT a, b or c.
– (dash)
It finds for character range within the given item range for
example [a-z] means a through z.
| (pipe) It is the logical OR for example x | y means x OR y.
? It denotes zero or one of preceding character or item range.
Operators in Regular Expression
OPERATOR DESCRIPTION
* It denotes zero or more of preceding character or item range.
+ It denotes one or more of preceding character or item range.
{n}
It denotes exactly n times of preceding character or item
range for example n{2}.
{n, }
It denotes atleast n times of preceding character or item
range for example n{2, }.
{n, m}
It denotes atleast n but not more than m times for example
n{2, 4} means 2 to 4 of n.
 It denotes the escape character.
Special Character Classes
SPECIAL CHARACTER MEANING
n It denotes a new line.
r
It denotes a carriage
return.
t It denotes a tab.
v It denotes a vertical tab.
f It denotes a form feed.
xxx
It denotes octal character
xxx.
xhh
It denotes hex character
hh.
Shorthand Character Sets
SHORTHAND MEANING
s
Matches space characters like
space, newline or tab.
d Matches any digit from 0 to 9.
w
Matches word characters including
all lower and upper case letters,
digits and underscore.
Predefined functions or Regex library:
FUNCTION DEFINITION
preg_match()
This function searches for a specific pattern against some
string. It returns true if pattern exists and false otherwise.
preg_match_all()
This function searches for all the occurrences of string
pattern against the string. This function is very useful for
search and replace.
ereg_replace()
This function searches for specific string pattern and
replace the original string with the replacement string, if
found.
eregi_replace()
The function behaves like ereg_replace() provided the
search for pattern is not case sensitive.
preg_replace()
This function behaves like ereg_replace() function provided
the regular expressions can be used in the pattern and
replacement strings.
preg_split()
The function behaves like the PHP split() function. It splits
the string by regular expressions as its paramaters.
PHP Validation
Email
 Use filter_var() function
$email = "yogaraja@ritrjpm.ac.in";
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
echo $emailErr;
PHP Validation
Name
 Use preg_match() function
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
PHP File Handling
 File handling is an important part of any web
application.
 You often need to open and process a file for
different tasks
 PHP has several functions for creating, reading,
uploading, and editing files.
PHP readfile()
 The readfile() function is useful if all you want
to do is open up a file and read its contents.
 <?php
echo readfile(“file.txt");
?>
PHP Open File - fopen()
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the
end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the
end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
PHP Open File - fopen()
 The first parameter of fopen() contains the
name of the file to be opened and the second
parameter specifies in which mode the file
should be opened.
 $myfile = fopen(“text.txt", "r")
 echo fread($myfile,filesize(“text.txt", "r"));
PHP Read File - fread()
 The fread() function reads from an open file.
 The first parameter of fread() contains the
name of the file to read from and the second
parameter specifies the maximum number of
bytes to read.
 $myfile = fopen(“text.txt", "r")
PHP Close File - fclose()
 The fclose() function is used to close an open
file.
 fclose($myfile);
PHP Read Single Line - fgets()
 The fgets() function is used to read a single
line from a file.
$myfile = fopen(“text.txt", "r")
echo fgets($myfile);
fclose($myfile);
After a call to the fgets() function, the file
pointer has moved to the next line.
PHP Check End-Of-File - feof()
 The feof() function checks if the "end-of-file"
(EOF) has been reached.
 The feof() function is useful for looping through
data of unknown length.
$myfile = fopen(“text.txt", "r")
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
PHP Read Single Character - fgetc()
 The fgetc() function is used to read a single
character from a file.
$myfile = fopen(“text.txt", "r")
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
After a call to the fgetc() function, the file
pointer moves to the next character.
PHP Write to File - fwrite()
 The first parameter of fwrite() contains the name
of the file to write to and the second parameter is
the string to be written.
 $myfile = fopen(“text.txt", “w")
$txt = "John Doen";
fwrite($myfile, $txt);
$txt = "Jane Doen";
fwrite($myfile, $txt);
fclose($myfile);
After a call to the fgetc() function, the file pointer
moves to the next character.
PHP 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, it is possible to create and retrieve
cookie values.
PHP Cookies
 Create Cookies
 A cookie is created with the setcookie() function.
 Syntax
 setcookie(name*, value, expire, path, domain, secure, httponly);
* Mandatory
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
// 86400 = 1 day
?>
The setcookie() function must appear BEFORE the <html> tag.
PHP Cookies
 Retrieve Cookies
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie()
instead).
PHP Cookies
 Modify Cookies
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), "/");
?>
PHP Cookies
 Delete Cookies
To delete a cookie, use the setcookie() function
with an expiration date in the past:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
PHP Cookies
 Check if Cookies are Enabled
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
PHP Sessions
 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.
 When you work with an application, you open it, do some changes,
and then you close it.
 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).
 By default, session variables last until the user closes the browser.
PHP Sessions
Start a PHP Session
 A session is started with the session_start()
function.
 Session variables are set with the PHP global
variable: $_SESSION.
PHP Sessions
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
$_SESSION["favcolor"] = "green";
?>
</body>
</html>
Note: The session_start()
function must be the very
first thing in your document.
Before any HTML tags.
PHP Sessions
Reading Session Values
session variables are not passed individually to each
new page, instead they are retrieved from the
session we open at the beginning of each page
(session_start()).
Also notice that all session variable values are
stored in the global $_SESSION variable:
PHP Sessions
Reading Session Values
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";?>
</body>
</html>
To show all the session
variable values for a
user session
<?php
print_r($_SESSION);
?>
PHP Sessions
Destroy a PHP Session
 To remove all global session variables and destroy the
session, use session_unset() and session_destroy():
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
session_unset();
session_destroy();
?>
</body>
</html>
Anna University Questions
 Explain how cookies are handled in PHP with example. (Nov/Dec 2017) (Nov/Dec
2019)
 Write a PHP program to do string manipulations. (Nov/Dec 2015)
 Explain the steps in connecting a PHP code to a database.(Nov/Dec 2016)
 Explain the string comparison capability of PHP using regular expression with an
example. (Nov/Dec 2016)
 Write a PHP program that tests whether an email address is input correctly. Verify
that the input begins with a series of characters followed by the @ character,
another series of characters, a period ‘.’ And a final series of characters. Test your
program with both valid and invalid email address. (Apr/May 2017)
 Write a PHP code to create an array and sort it using built in functions. (Nov/Dec
2019)
 Write a PHP code to read from a cookie and display its contents. (Nov/Dec 2019)
 Design simple calculator using PHP. (Nov/Dec 2018)
 Explain about the control statements in PHP with example. (Nov/Dec 2018)
 Create a web page for a company with buses plying in different routes. Store
details of the users in the database, enable users to book tickets using the web site
and display the bus ticket with fare for the users using PHP. (Apr/May 2018)
 Create a Webserver based chat application using PHP. The application should
provide the following functions
Login
Send message(to one or more contacts)
Receive messages(from one or more contacts)
Add/delete/modify contact list of the user
Discuss the application’s user interface and use comments in PHP to explain the code clearly.
(May/June 2016)
 Design an application to send an email using PHP. (Nov/Dec 2017)
 Design a PHP application for College Management System with appropriate built-in
functions and database. (Nov/Dec 2018)
Anna University Questions

Php

  • 1.
    PHP PHP:HYPERTEXT PREPROCESSOR Prepared By YogarajaC A Ramco Institute of Technology
  • 2.
    INTRODUCTION  PHP isa server scripting language, and a powerful tool for making dynamic and interactive Web pages.  PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file  PHP is a widely-used  Opensource  Simple Language  Object Oriented  PHP 7 is the latest stable release.  Loosely Typed – Contains different type of data at different times
  • 3.
    SYNTAX  A PHPscript can be placed anywhere in the document.  The default file extension for PHP files is ".php".  A PHP script starts with <?php and ends with ?>  PHP statements end with a semicolon (;). <!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </body> </html>
  • 4.
    SYNTAX(Case Sensitivity)  InPHP, NO keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are case-sensitive.  PHP will ignore all the spaces or tabs in a single row or carriage return in multiple rows.  Unless a semi-colon is encountered, PHP treats multiple lines as a single command.  PHP Variables are case Sensitive <!DOCTYPE html> <html> <body> <?php $color = "red"; $COLOR="BLUE" echo "My car is " . $color . "<br>"; echo "My house is " . $COLOR . "<br>"; ?> </body> </html>
  • 5.
    SYNTAX(Comments)  A commentis something which is ignored and not read or executed by PHP engine or the language as part of a program  It is written to make the code more readable and understandable.  Single Line Comment <?php // This is a single line comment echo "hello world!!!"; # This is also a single line comment ?>
  • 6.
    SYNTAX(Comments)  Multi-line orMultiple line Comment: <?php /* This is a multi line comment In PHP variables are written by adding a $ sign at the beginning.*/ ?>
  • 7.
    PHP Variables  Avariable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).  Rules for PHP variables:  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 cannot 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 ($age and $AGE are two different variables)
  • 8.
    PHP is aLoosely Typed Language  PHP automatically associates a data type to the variable, depending on its value.  Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
  • 9.
    PHP Variables Scope In PHP, variables can be declared anywhere in the script.  The scope of a variable is the part of the script where the variable can be referenced/used.  PHP has three different variable scopes:  local  global  Static ***The global keyword is used to access a global variable from within a function.
  • 10.
    PHP Data Types String  Integer(2,147,483,648 and 2,147,483,647 or -2^31 to 2^31)  Float (also called double)  Boolean  Array  Object  NULL  Resource
  • 11.
    PHP Constants  Aconstant is an identifier (name) for a simple value. The value cannot be changed during the script.  A valid constant name starts with a letter or underscore (no $ sign before the constant name).  ***Unlike variables, constants are automatically global across the entire script.  The define() function in PHP is used to create a constant  define(name, value, case_insensitive)  name: The name of the constant.  value: The value to be stored in the constant.  case_insensitive: Defines whether a constant is case insensitive. By default this value is False, i.e., case sensitive.
  • 12.
    PHP Constants <?php define("GREETING", "Welcometo india.com!"); echo GREETING; ?> <?php define("cars", ["Alfa Romeo", "BMW", "Toyota"]); echo cars[0]; ?>
  • 13.
    PHP Operators  PHPdivides the operators in the following groups:  Arithmetic operators  Assignment operators  Comparison operators  Increment/Decrement operators  Logical operators  String operators  Array operators  Conditional assignment operators
  • 14.
    PHP Conditional Statements In PHP we have the following conditional statements:  if statement - executes some code if one condition is true  if...else statement - executes some code if a condition is true and another code if that condition is false  if...elseif...else statement - executes different codes for more than two conditions  switch statement - selects one of many blocks of code to be executed
  • 15.
    PHP Loops  while- loops through a block of code as long as the specified condition is true  do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true  for - loops through a block of code a specified number of times  foreach - loops through a block of code for each element in an array foreach ($array as $value) { code to be executed; }
  • 16.
    PHP functions  Array Calendar  Date  Math  Mail  MySQLi  String  Error
  • 17.
    PHP Array function FunctionDescription array() Creates an array $cars=array("Volvo","BMW","Toyota"); array_combine() Creates an array by using the elements from one "keys" array and one "values" array $fname=array("Peter","Ben","Joe"); $age=array("35","37","43"); array_count_valu es() Counts all the values of an array $a=array("A","Cat","Dog","A","Dog"); print_r(array_count_values($a)); array_diff() Compare arrays, and returns the differences (compare values only) $a1=array("a"=>"red","b"=>"green","c"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue"); $result=array_diff($a1,$a2); array_flip() Flips/Exchanges all keys with their associated values in an array $a1=array("a"=>"red","b"=>"green"); $result=array_flip($a1); array_merge() Merges one or more arrays into one array $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2));
  • 18.
    PHP Array function FunctionDescription array_rand() Returns one or more random keys from an array $a=array("a"=>"red, "c"=>"blue","d"=>"yellow"); print_r(array_rand($a,1)); array_replace() Replaces the values of the first array with the values from following arrays $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_replace($a1,$a2)); array_reverse() Returns an array in the reverse order $a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota"); print_r(array_reverse($a)); array_search() Searches an array for a given value and returns the key $a=array("a"=>"red","b"=>"green","c"=>"blue"); echo array_search("red",$a); array_unique() Removes duplicate values from an array $a=array("a"=>"red","b"=>"green","c"=>"red"); print_r(array_unique($a)); count() Returns the number of elements in an array $cars=array("Volvo","BMW","Toyota"); echo count($cars);
  • 19.
    PHP Array function FunctionDescription arsort() Sorts an associative array in descending order, according to the value $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); arsort($age); print_r($age); asort() Sorts an associative array in ascending order, according to the value $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); asort($age); print_r($age);
  • 20.
    PHP Calendar function FunctionDescription cal_days_in_mont h() Returns the number of days in a month for a specified year and calendar $d=cal_days_in_month(CAL_GREGORIAN,10,2005); echo $d; jdmonthname() Returns a month name $jd=gregoriantojd(1,13,1998); echo jdmonthname($jd,0); 0 - Gregorian - abbreviated form (Jan, Feb, Mar, etc.) 1 - Gregorian (January, February, March, etc.) 2 - Julian - abbreviated form (Jan, Feb, Mar, etc.) 3 - Julian (January, February, March, etc.) jddayofweek() Returns the day of the week $jd=gregoriantojd(1,13,1998); echo jddayofweek($jd,1); 0 - Default. Returns 0=Sunday, 1=Monday, etc. 1 - Sunday, Monday, etc. 2 - Returns Sun, Mon, etc.
  • 21.
    PHP Date function FunctionDescription date() Formats a local date and time echo date("l") d - The day of the month (from 01 to 31) D - A textual representation of a day (three letters) j - The day of the month without leading zeros (1 to 31) l (lowercase 'L') - A full textual representation of a day N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday) S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j) w - A numeric representation of the day (0 for Sunday, 6 for Saturday) z - The day of the year (from 0 through 365) W - The ISO-8601 week number of year (weeks starting on Monday) F - A full textual representation of a month (January through December) m - A numeric representation of a month (from 01 to 12) M - A short textual representation of a month (three letters)
  • 22.
    PHP Date function FunctionDescription getdate() Returns date/time information of a timestamp or the current local date/time print_r(getdate()); Array ( [seconds] => 50 [minutes] => 16 [hours] => 9 [mday] => 17 [wday] => 1 [mon] => 2 [year] => 2020 [yday] => 47 [weekday] => Monday [month] => February [0] => 1581931010 ) time() Returns the current time as a Unix timestamp echo($t); echo(date("Y-m-d",$t)); 1581931163 2020-02-17 date_diff() Returns the difference between two dates $date1=date_create("2013-03-15"); $date2=date_create("2013-12-12"); $diff=date_diff($date1,$date2); echo $diff->format("%R%a days"); date_date_ set() Sets a new date $date=date_create(); date_date_set($date,2020,10,30); echo date_format($date,"Y/m/d");
  • 23.
    PHP Math function FunctionDescription abs() Returns the absolute (positive) value of a number base_convert() Converts a number from one number base to another $hex = "E196"; echo base_convert($hex,16,8); ceil() Rounds a number up to the nearest integer decbin() Converts a decimal number to a binary number dechex() Converts a decimal number to a hexadecimal number decoct() Converts a decimal number to an octal number bindec() Converts a binary number to a decimal number exp() Calculates the exponent of e echo(exp(4.8)); expm1() Returns exp(x) - 1
  • 24.
    PHP Math function FunctionDescription fmod() Returns the remainder of x/y floor() Rounds a number down to the nearest integer fmod() Returns the remainder of x/y log() Returns the natural logarithm of a number log10() Returns the base-10 logarithm of a number max() Returns the highest value in an array, or the highest value of several specified values echo(max(array(44,16,81,12))); min() Returns the lowest value in an array, or the lowest value of several specified values
  • 25.
    PHP Mail function FunctionDescription mail() Allows you to send emails directly from a script mail("someone@example.com","My subject",$msg);
  • 26.
    PHP MYSQLi function FunctionDescription mysqli_connect() opens a new connection to the MySQL server. $con = mysqli_connect("localhost", "my_user", "my_password","my_db"); mysqli_query() performs a query against a database. $result = mysqli_query($con, "SELECT * FROM Persons"); mysqli_fetch_array() fetches a result row as an associative array, a numeric array, or both. $row = mysqli_fetch_array($result); mysqli_num_rows() eturns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query. mysqli_num_rows($result) mysqli_close() closes a previously opened database connection. mysqli_close($con)
  • 27.
    PHP string function FunctionDescription md5() Calculates the MD5 hash of a string echo md5($str); md5_file() Calculates the MD5 hash of a file $result = md5_file($filename); trim() Removes whitespace or other characters from both sides of a string $str = "Hello World!"; echo trim($str,"Hed!"); ltrim() Removes whitespace or other characters from the left side of a string $str = "Hello World Hello!"; echo ltrim($str,"Hello "); rtrim() Removes whitespace or other characters from the right side of a string $str = "Hello Word!"; echo rtrim($str,"odH!"); str_ireplace() Replaces some characters in a string (case-insensitive) echo str_ireplace("WORLD",“Rit","Hello world!"); str_pad() Pads a string to a new length $str = "Hello World"; echo str_pad($str,20,".");
  • 28.
    PHP string function FunctionDescription str_repeat() Repeats a string a specified number of times echo str_repeat("Wow",13); str_replace() Replaces some characters in a string (case- sensitive) echo str_replace("WORLD",“Rit","Hello world!"); str_word_count() Count the number of words in a string echo str_word_count("Hello world!"); strip_tags() Strips HTML and PHP tags from a string echo strip_tags("Hello <b>world!</b>"); strrev() Reverses a string echo strrev("Hello World!"); strtolower() Converts a string to lowercase letters echo strtolower("Hello WORLD."); strtoupper() Converts a string to uppercase letters echo strtoupper("Hello WORLD!"); ucfirst() Converts the first character of a string to uppercase echo ucfirst("hello world!"); ucwords() Converts the first character of each word in a string to uppercase echo ucwords("hello world");
  • 29.
    PHP Error function FunctionDescription error_clear_last() Clears the last error error_get_last() Returns the last error that occurred error_log() Sends an error message to a log, to a file, or to a mail account error_reporting() Specifies which errors are reported
  • 30.
    Regular Expression  Aregular expression is an object that describes a pattern of characters.  Regular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string.  Regular expressions help in validation of text strings which are of programmer’s interest.  It offers a powerful tool for analyzing, searching a pattern and modifying the text data.  It helps in searching specific string pattern and extracting matching results in a flexible manner.
  • 31.
    Regular Expression REGULAR EXPRESSIONMATCHES rit The string “rit” ^rit The string which starts with “rit” rit$ The string which have “rit” at the end. ^rit$ The string where “rit” is alone on a string. [abc] a, b, or c [a-z] Any lowercase letter [^A-Z] Any letter which is NOT a uppercase letter (gif|png) Either “gif” or “png” [a-z]+ One or more lowercase letters ^[a-zA-Z0-9]{1, }$ Any word with at least one number or one letter ([ax])([by]) ab, ay, xb, xy [^A-Za-z0-9] Any symbol other than a letter or other than number ([A-Z]{3}|[0-9]{5}) Matches three letters or five numbers
  • 32.
    Operators in RegularExpression OPERATOR DESCRIPTION ^ It denotes the start of string. $ It denotes the end of string. . It denotes almost any single character. () It denotes a group of expressions. [] It finds a range of characters for example [xyz] means x, y or z . [^] It finds the items which are not in range for example [^abc] means NOT a, b or c. – (dash) It finds for character range within the given item range for example [a-z] means a through z. | (pipe) It is the logical OR for example x | y means x OR y. ? It denotes zero or one of preceding character or item range.
  • 33.
    Operators in RegularExpression OPERATOR DESCRIPTION * It denotes zero or more of preceding character or item range. + It denotes one or more of preceding character or item range. {n} It denotes exactly n times of preceding character or item range for example n{2}. {n, } It denotes atleast n times of preceding character or item range for example n{2, }. {n, m} It denotes atleast n but not more than m times for example n{2, 4} means 2 to 4 of n. It denotes the escape character.
  • 34.
    Special Character Classes SPECIALCHARACTER MEANING n It denotes a new line. r It denotes a carriage return. t It denotes a tab. v It denotes a vertical tab. f It denotes a form feed. xxx It denotes octal character xxx. xhh It denotes hex character hh.
  • 35.
    Shorthand Character Sets SHORTHANDMEANING s Matches space characters like space, newline or tab. d Matches any digit from 0 to 9. w Matches word characters including all lower and upper case letters, digits and underscore.
  • 36.
    Predefined functions orRegex library: FUNCTION DEFINITION preg_match() This function searches for a specific pattern against some string. It returns true if pattern exists and false otherwise. preg_match_all() This function searches for all the occurrences of string pattern against the string. This function is very useful for search and replace. ereg_replace() This function searches for specific string pattern and replace the original string with the replacement string, if found. eregi_replace() The function behaves like ereg_replace() provided the search for pattern is not case sensitive. preg_replace() This function behaves like ereg_replace() function provided the regular expressions can be used in the pattern and replacement strings. preg_split() The function behaves like the PHP split() function. It splits the string by regular expressions as its paramaters.
  • 37.
    PHP Validation Email  Usefilter_var() function $email = "yogaraja@ritrjpm.ac.in"; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } echo $emailErr;
  • 38.
    PHP Validation Name  Usepreg_match() function if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; }
  • 39.
    PHP File Handling File handling is an important part of any web application.  You often need to open and process a file for different tasks  PHP has several functions for creating, reading, uploading, and editing files.
  • 40.
    PHP readfile()  Thereadfile() function is useful if all you want to do is open up a file and read its contents.  <?php echo readfile(“file.txt"); ?>
  • 41.
    PHP Open File- fopen() Modes Description r Open a file for read only. File pointer starts at the beginning of the file w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x Creates a new file for write only. Returns FALSE and an error if file already exists r+ Open a file for read/write. File pointer starts at the beginning of the file w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
  • 42.
    PHP Open File- fopen()  The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened.  $myfile = fopen(“text.txt", "r")  echo fread($myfile,filesize(“text.txt", "r"));
  • 43.
    PHP Read File- fread()  The fread() function reads from an open file.  The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.  $myfile = fopen(“text.txt", "r")
  • 44.
    PHP Close File- fclose()  The fclose() function is used to close an open file.  fclose($myfile);
  • 45.
    PHP Read SingleLine - fgets()  The fgets() function is used to read a single line from a file. $myfile = fopen(“text.txt", "r") echo fgets($myfile); fclose($myfile); After a call to the fgets() function, the file pointer has moved to the next line.
  • 46.
    PHP Check End-Of-File- feof()  The feof() function checks if the "end-of-file" (EOF) has been reached.  The feof() function is useful for looping through data of unknown length. $myfile = fopen(“text.txt", "r") while(!feof($myfile)) { echo fgets($myfile) . "<br>"; } fclose($myfile);
  • 47.
    PHP Read SingleCharacter - fgetc()  The fgetc() function is used to read a single character from a file. $myfile = fopen(“text.txt", "r") while(!feof($myfile)) { echo fgetc($myfile); } fclose($myfile); After a call to the fgetc() function, the file pointer moves to the next character.
  • 48.
    PHP Write toFile - fwrite()  The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.  $myfile = fopen(“text.txt", “w") $txt = "John Doen"; fwrite($myfile, $txt); $txt = "Jane Doen"; fwrite($myfile, $txt); fclose($myfile); After a call to the fgetc() function, the file pointer moves to the next character.
  • 49.
    PHP Cookies  Acookie 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, it is possible to create and retrieve cookie values.
  • 50.
    PHP Cookies  CreateCookies  A cookie is created with the setcookie() function.  Syntax  setcookie(name*, value, expire, path, domain, secure, httponly); * Mandatory <?php $cookie_name = "user"; $cookie_value = "John Doe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day ?> The setcookie() function must appear BEFORE the <html> tag.
  • 51.
    PHP Cookies  RetrieveCookies <?php if(!isset($_COOKIE[$cookie_name])) { echo "Cookie is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name]; } ?> The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
  • 52.
    PHP Cookies  ModifyCookies 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), "/"); ?>
  • 53.
    PHP Cookies  DeleteCookies To delete a cookie, use the setcookie() function with an expiration date in the past: <?php // set the expiration date to one hour ago setcookie("user", "", time() - 3600); ?>
  • 54.
    PHP Cookies  Checkif Cookies are Enabled <?php setcookie("test_cookie", "test", time() + 3600, '/'); ?> <html> <body> <?php if(count($_COOKIE) > 0) { echo "Cookies are enabled."; } else { echo "Cookies are disabled."; } ?>
  • 55.
    PHP Sessions  Asession 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.  When you work with an application, you open it, do some changes, and then you close it.  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).  By default, session variables last until the user closes the browser.
  • 56.
    PHP Sessions Start aPHP Session  A session is started with the session_start() function.  Session variables are set with the PHP global variable: $_SESSION.
  • 57.
    PHP Sessions <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php $_SESSION["favcolor"]= "green"; ?> </body> </html> Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
  • 58.
    PHP Sessions Reading SessionValues session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()). Also notice that all session variable values are stored in the global $_SESSION variable:
  • 59.
    PHP Sessions Reading SessionValues <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";?> </body> </html> To show all the session variable values for a user session <?php print_r($_SESSION); ?>
  • 60.
    PHP Sessions Destroy aPHP Session  To remove all global session variables and destroy the session, use session_unset() and session_destroy(): <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php session_unset(); session_destroy(); ?> </body> </html>
  • 61.
    Anna University Questions Explain how cookies are handled in PHP with example. (Nov/Dec 2017) (Nov/Dec 2019)  Write a PHP program to do string manipulations. (Nov/Dec 2015)  Explain the steps in connecting a PHP code to a database.(Nov/Dec 2016)  Explain the string comparison capability of PHP using regular expression with an example. (Nov/Dec 2016)  Write a PHP program that tests whether an email address is input correctly. Verify that the input begins with a series of characters followed by the @ character, another series of characters, a period ‘.’ And a final series of characters. Test your program with both valid and invalid email address. (Apr/May 2017)  Write a PHP code to create an array and sort it using built in functions. (Nov/Dec 2019)  Write a PHP code to read from a cookie and display its contents. (Nov/Dec 2019)  Design simple calculator using PHP. (Nov/Dec 2018)  Explain about the control statements in PHP with example. (Nov/Dec 2018)
  • 62.
     Create aweb page for a company with buses plying in different routes. Store details of the users in the database, enable users to book tickets using the web site and display the bus ticket with fare for the users using PHP. (Apr/May 2018)  Create a Webserver based chat application using PHP. The application should provide the following functions Login Send message(to one or more contacts) Receive messages(from one or more contacts) Add/delete/modify contact list of the user Discuss the application’s user interface and use comments in PHP to explain the code clearly. (May/June 2016)  Design an application to send an email using PHP. (Nov/Dec 2017)  Design a PHP application for College Management System with appropriate built-in functions and database. (Nov/Dec 2018) Anna University Questions