The document provides an introduction and overview of PHP, including:
- PHP is a server-side scripting language used for web development and can be embedded into HTML. It is commonly used to manage dynamic content, databases, sessions, and build ecommerce sites.
- Common uses of PHP include handling forms, accessing and modifying database elements, setting and accessing cookies, and restricting user access to website pages.
- The document then covers PHP syntax, variables, operators, conditional statements, loops, and arrays to provide the basic building blocks of the language.
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
Php
1. INTRODUCTION
•PHP is an Interpreted High-level Programming
Language
•PHP stands for Personal Home Page (1995 by Rasmus
lerdorf)
•After PHP version 3 : Hypertext Preprocessor.
•PHP is a server side scripting language that is
embedded in HTML. It is used to manage dynamic
content, databases, session tracking, even build entire
ecommerce sites.
2. • It is integrated with a number of popular
databases, including MySQL, PostgreSQL, Oracle,
Sybase, Informix, and Microsoft SQL Server.
• PHP supports a large number of major protocols
such as POP3, IMAP, and LDAP. PHP4 added
support for Java and distributed object
architectures (COM and CORBA), making n-tier
development a possibility for the first time.
• PHP Syntax is C-Like.
3. Common uses of PHP
• PHP can handle forms, i.e. gather data from files,
save data to a file, thru email you can send data,
return data to the user.
• You add, delete, modify elements within your
database thru PHP.
• Access cookies variables and set cookies.
• Using PHP, you can restrict users to access some
pages of your website.
• It can encrypt data.
4. Characteristics of PHP
• Performance
• Portability
• Simplicity
• Open Source
• Community Support
• Third-Party Application Support
• Security
• Flexibility
• Familiarity
5. "Hello World" Script in PHP
<html>
<head>
<title>Hello World</title>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
All PHP code must be included inside one of the three
special markup tags
<?php PHP code goes here ?>
<? PHP code goes here ?>
<script language="php"> PHP code goes here </script>
6. SYNTAX OVERVIEW
• Escaping to PHP
The PHP parsing engine needs a way to differentiate
PHP code from other elements in the page.
The mechanism for doing so is known as 'escaping to
PHP.'
There are four ways to do this:
Canonical PHP tags: <?php...?>
Short-open (SGML-style) tags: <?...?>
ASP-style tags :<%...%>
HTML script tags : <script language="PHP">...</script>
7. • Commenting PHP Code
Single-line comment
<?
# 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";
?>
Multi-lines comments
<?
/* This is a comment with multiline
Author : Parameswar
Purpose: Multiline Comments Demo
Subject: PHP
*/
print "An example with multi line comments";
?>
8. PHP is whitespace insensitive
$four = 2 + 2; // single spaces
$four <tab>=<tab>2<tab>+<tab>2 ; // spaces and tabs
$four =
2+
2; // multiple lines
PHP is case sensitive
<html>
<body>
<? $capital = 67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html>
Statements or expressions terminated by semicolons
9. VARIABLE TYPES
To store the information we use a variable.
Here are the most important things to know about
variables in PHP.
1. All variables are denoted with a dollar sign ($).
2. The value of a variable is the value of its most
recent assignment.
3. Variables are assigned with “= “operator
4. Variables in PHP do not have intrinsic types
5. Variables used before they are assigned have
default values.
6. PHP automatically converting types from one to
another when necessary.
10. PHP has eight data type
Integers
Doubles
Booleans simple Types
NULL
Strings
Arrays
Objects compound Types
Resources : are special variables that hold references
to resources external to PHP
11. Here Document
To assign multiple lines to a single string variable using here document
<?php
$channel =<<<_XML_
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;
echo <<<END
This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
<br />
END;
print $channel;
?>
12. Variable Naming
Rules for naming a variable
1.Variable names must begin with a letter or
underscore character.
2.A variable name can consist of numbers, letters,
underscores but you cannot use characters like + , -
, % , ( , ) . & , etc
3.There is no size limit for variables.
13. Variables Scope
Local variables
a variable declared in a function is considered local
<?
$x = 4;
function assignx () {
$x = 0;
print "$x inside function is $x. ";
}
assignx();
print "$x outside of function is $x. ";
?>
14. Function Parameters
Function parameters are declared after the function
name and inside parentheses.
They are declared much like a typical variable
<?
// multiply a value by 10 and return it to the caller
function multiply ($value)
{
$value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retvaln";
?>
15. Global Variables
a global variable can be accessed in any part of the
program
placing the keyword GLOBAL in front of the variable that
should be recognized as global
<?
$somevar = 15;
function addit()
{
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
16. Static Variables
a static variable will not lose its value when the function exits
and will still hold that value should the function be called
again
<?
function keep_track()
{
STATIC $count = 0;
$count++;
print $count;
print " ";
}
keep_track();
keep_track();
keep_track();
?>
17. CONSTANTS
A constant is a name or an identifier for a simple
value.
A constant value cannot change during the execution
of the script.
By default a constant is case-sensitive
To define a constant you have to use define() function
you do not need to have a constant with a $
18. constant() function:
this function will return the value of the constant
constant() example
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the
previous line
?>
19. Differences between constants and variables
There is no need to write a dollar sign ($) before a
constant, where as in Variable one has to write a
dollar sign.
Constants cannot be defined by simple assignment,
they may only be defined using the define()
function.
Constants may be defined and accessed anywhere
without regard to variable scoping rules.
Once the Constants have been set, may not be
redefined or undefined.
20. Few "magical" PHP constants
__LINE__ : The current line number of the file.
__FILE__ :The full path and filename of the file. If used inside
an include, the name of the included file is returned. Since
PHP 4.0.2, __FILE__ always contains an absolute path
whereas in older versions it contained relative path under
some circumstances.
__FUNCTION__ :
The function name. (Added in PHP 4.3.0) As of PHP 5 this
constant returns the function name as it was declared (case-
sensitive). In PHP 4 its value is always lowercased.
__CLASS__ :The class name. (Added in PHP 4.3.0) As of PHP 5
this constant returns the class name as it was declared (case-
sensitive). In PHP 4 its value is always lowercased.
__METHOD_ _ :
The class method name. (Added in PHP 5.0.0) The method name
is returned as it was declared (case-sensitive).
21. OPERATOR TYPES
What is Operator?
types of operators
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
23. Comparison Operators
==, !=, >, <, >=, <=
<html>
<head><title>Comparison Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
if( $a == $b ){
echo "TEST1 : a is equal to b<br/>";
}else{
echo "TEST1 : a is not equal to b<br/>";
}
if( $a > $b ){
echo "TEST2 : a is greater than b<br/>";
}else{
echo "TEST2 : a is not greater than b<br/>";
}
if( $a < $b ){
echo "TEST3 : a is less than b<br/>";
}else{
echo "TEST3 : a is not less than b<br/>";
}
24. if( $a != $b ){
echo "TEST4 : a is not equal to b<br/>";
}else{
echo "TEST4 : a is equal to b<br/>";
}
if( $a >= $b ){
echo "TEST5 : a is either greater than or equal to b<br/>";
}else{
echo "TEST5 : a is neither greater than nor equal to b<br/>";
}
if( $a <= $b ){
echo "TEST6 : a is either less than or equal to b<br/>";
}else{
echo "TEST6 : a is neither less than nor equal to b<br/>";
}
?>
</body>
</html>
25. Logical Operators
And: (A and B) is true.
Or: (A or B) is true.
&&: (A &&B) is true.
||: (A || B) is true.
!: !(A && B) is true.
26. Assignment Operators
=, +=,-=,*=,/=,%=
<head><title>Assignment Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b; /* Assignment operator */
echo "Addition Operation Result: $c <br/>";
$c += $a; /* c value was 42 + 20 = 62 */
echo "Add AND Assignment Operation Result: $c <br/>";
$c -= $a; /* c value was 42 + 20 + 42 = 104 */
echo "Subtract AND Assignment Operation Result: $c <br/>";
$c *= $a; /* c value was 104 - 42 = 62 */
echo "Multiply AND Assignment Operation Result: $c <br/>";
$c /= $a; /* c value was 62 * 42 = 2604 */
echo "Division AND Assignment Operation Result: $c <br/>";
$c %= $a; /* c value was 2604/42 = 62*/
echo "Modulus AND Assignment Operation Result: $c <br/>";
?>
</body>
</html>
28. <html>
<head><title>Arithmetical Operators</title><head>
<body>
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otherwise b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otherwise b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>
</body>
</html>
29. DECISION MAKING
use conditional statements in your code to make your
decisions
if...else statement - use this statement if you want to
execute a set of code when a condition is true and
another if the condition is not true
elseif statement - is used with the if...else statement
to execute a set of code if one of several condition
are true
switch statement - is used if you want to select one of
many blocks of code to be executed, use the Switch
statement. The switch statement is used to avoid
long blocks of if..elseif..else code.
30. Switch Statement
<html>
<body>
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>
31. LOOP TYPES
Loops in PHP are used to execute the same block of
code a specified number of times
for - loops through a block of code a specified number
of times.
while - loops through a block of code if and as long as
a specified condition is true.
do...while - loops through a block of code once, and
then repeats the loop as long as a special condition
is true.
foreach - loops through a block of code for each
element in an array.
32. For Loop
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
33. While Loop
<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body> </html
38. ARRAYS
Array variables are “special,” because they can hold
more than one value at a time.
There are three different kind of arrays
Numeric array : An array with a numeric index
Associative array : An array with strings as index
Multidimensional array :An array containing one or
more arrays and values are accessed using multiple
indices
39. Numeric array
Example
<?php // define array
$fruits = array('apple', 'banana', 'pineapple', 'grape');
?>
To access this
$fruits[index]
here index is numeric, which starts from 0
40. Associative array
Example
<?php // define array
$fruits = array(
'a' => 'apple',
'b' => 'banana',
'p' => 'pineapple',
'g' => 'grape' );
?>
To access this
$fruits[index]
Here index numbers are replaced with user-defined
strings, or “keys.”
41. Assigning Array Values
Two ways u can assign values to arrays(both numeric and
associate )
Method 1: same as previous
Method 2:
numeric
<?php
// define array
$cars[0] = 'Ferrari';
$cars[1] = 'Porsche';
$cars[2] = 'Jaguar';
$cars[3] = 'Lamborghini';
$cars[4] = 'Mercedes';
?>
42. Associate
<?php
// define array
$data['username'] = 'john';
$data['password'] = 'secret';
$data['host'] = '192.168.0.1';
?>
To access a value from an array in a script
echo 'The password is: ' . $data['password'];
43. Modifying Array Values
example
<?php // define array
$meats = array(
'fish',
'chicken',
'ham',
'lamb'
);
// change 'ham' to 'turkey'
$meats[2] = 'turkey';
?>
To remove an element from an array
use the unset() function on the corresponding key or
index:
45. To access a value from nested array, use the correct
hierarchical sequence of indices/keys to get to the
value.
// access nested value
echo "David Duck's number is: "
.$phonebook[0]['tel'];
echo " Raymond Rabbit mail id: "
.$phonebook[1][‘email'];
echo " name: "
.$phonebook[2][‘name'];
46. Strings
• PHP provides many functions with which you can format and
manipulate strings.
Formatting Strings with PHP
Specifier Description
d Display argument as a decimal number
b Display an integer as a binary number
c Display an integer as ASCII equivalent
f Display an integer as a floating-point number (double)
o Display an integer as an octal number
S Display argument as a string
x Display an integer as a lowercase hexadecimal number
X Display an integer as an uppercase hexadecimal
number
48. STRING Handling Functions
String Concatenation Operator
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
strlen() – function returns length of the string.
<?php
$string=“welcome”;
Echo “the length of string is :”.strlen($string);
?>
49. the strpos() function
The strpos() function is used to search for a string or
character within a string.
example
<?php
echo strpos("Hello world!","world");
?>
• Splitting the string into an array –
explode(seperator, string);
• Joining the array elements into a single string -
implode(seperator,array);
50. Repeating the same string many times:
str_repeat() – is used to repeat a string for a
specific number of times.
Reversing a string – strrev()
<?php
$string=“kogent- ”;
echo “the repeated string is :”.str_repeat($string,5);
?>
<?php
$string=“kogent”;
Echo “the reversed string is :”.strrev($string);
?>
51. Finding current date and time
• The date() function is used to format the local
time and date.
date(format, timestamp);
format- format in which the date string to be
displayed.
timestamp – optional, it displays current
system date and time by default.
52. Some of the characters that can be used with the format
parameter are as follows:
d – specifies the day of the month(from 01 to 31)
D – textual representation of the day in three letters
F – full textual representation of a month(january)
t – specifies number of days in the given month
g – specifies 12 – hour format of an hour (1 to 12)
l – specifies full textual representation of a day
h - specifies 12 – hour format of an hour (01 to 12)
i – specifies minutes with leading zeros (00 to 59)
s – specifies seconds with leading zeros (00 to 59)
Y – four digit representation of a year
a – specifies a lowercase am or pm
S – specifies the english ordinal suffix for the day of month(st,nd,rd,
or th)
<?php
date_default_timezone_set('UTC');
echo date('l'). '<br>';
echo date('l dS of F Y h: i: s a');
?>
53. Functions
Advantages
It reduces duplication within a program
A function is created once but used many times
Debugging and testing a program becomes easier
when the program is subdivided into functions.
54. Creating and Invoking Functions
<?php
// function definition // print today's weekday name
function whatIsToday()
{
echo "Today is " . date('l', mktime());
}
// function invocation
whatIsToday();
?>
55. Function Using Arguments
<?php
// calculate perimeter of rectangle
// p = 2 * (l+w)
function getPerimeter($length, $width)
{
$perimeter = 2 * ($length + $width);
echo "The perimeter of a rectangle of length $length
units and width $width units is: $perimeter units";
}
// function invocation with arguments
getPerimeter(4,2);
?>
56. Function with return value
<?php
// function definition
// calculate perimeter of rectangle
// p = 2 * (l+w)
function getPerimeter($length, $width)
{ $perimeter = 2 * ($length + $width);
return $perimeter;
}
// function invocation with arguments
echo 'The perimeter of a rectangle of length 4 units and
width 2 units is: ' . getPerimeter(4,2) . ' units';
?>
57. Setting Default Argument Values
<?php
// generate e-mail address from supplied values
function buildAddress($username, $domain = ‘gmail.com')
{
return $username . '@' . $domain;
}
// function invocation
// without optional argument
echo 'My e-mail address is ' . buildAddress('john');
// function invocation
// with optional argument
echo 'My e-mail address is ' . buildAddress('jane',
'cooldomain.net');
?>
58. Using Dynamic Argument Lists
<?php
// function definition
// calculate average of supplied values
function calcAverage()
{
$args = func_get_args(); //returns the actual argument values, as an
array
$count = func_num_args(); // returns the number of arguments
passed to a function
$sum = array_sum($args);
$avg = $sum / $count;
return $avg; }
// function invocation with 3 arguments
echo calcAverage(3,6,9);
// function invocation with 8 arguments
echo calcAverage(100,200,100,300,50,150,250,50);
?>
59. Form Handling
Simple form
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
get
60. welcome.php
<html>
< body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"];
?>
< /body>
< /html>
---------------------------------------------------------------------
The same result could also be achieved using the
HTTP GET
_get
61. GET vs. POST vs REQUEST
Both GET and POST create an array. This array holds
key/value pairs, where keys are the names of the form
controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST.
These are superglobals
$_GET is an array of variables passed to the current
script via the URL parameters.
$_POST is an array of variables passed to the current
script via the HTTP POST method.
We may also use the $_REQUEST superglobal, if you
do not care about the source of your request data.
62. Connecting to database(MySql)
• Php is providing php_mysql.dll library with
number of functionalities to connect with mysql
databse.
• Mysql is open source RDBMS. It supports number
of objects like tables,views, etc.
• The default username for mysql db is “root” and
it does not contain any password.
• We can connect to mysql db through a command
prompt by executing mysql.exe file
c:/xampp/mysql/bin>mysql.exe
mysql>create database dbname;
mysql>use dbname;
63. phpmyadmin
• It is a GUI used to connect with mysql db.
• It is available with xampp download.
• The url address to open phpmyadmin is
http://localhost/phpmyadmin.
insert – we can insert records in a table
browse – we can browse the table records
structure – to change the structure of a table
sql – we can execute our sql statements
export – we can export database tables into text
files,pdf,excell,etc.
import – we can import the exported file
empty – we can delete the table records
drop – we can delete the table structure
64. My sql interaction with php
• php_mysql.dll provides more functions to connect with mysql database.
mysql_connect:
By using this we can create a connection between php and mysql database.it
contains 3 arguments:
servername
Username
password
mysql_select_db:
to select database from mysql server, arguments are sql statement
and connection id.
mysql_query:
To execute sql query in mysql database. arguments are sql statement
and connection id.
mysql_error:
To get the error messages while executing mysql statements.
mysql_errno:
To get the error number while executing mysql statements.
65. To create connection between mysql
and php
<?php
if($con=mysql_connect(“localhost”, “root”, “ ”))
{
echo “connected”. “<br>”;
echo $con; // resource type
}
else
echo mysql_error();
?>