introduction to PHP
introduction to PHP
PHP
PHP Introduction
PHP code is executed on the server.
What You Should Already Know
Before you continue you should have a basic understanding of the following:
• HTML
• CSS
• JavaScript
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
What is a PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the browser
as plain HTML
• PHP files have extension ".php"
With PHP you are not limited to output HTML. You can output images, PDF files, and
even Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
•PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
•PHP is compatible with almost all servers used today (Apache, IIS, etc.)
•PHP supports a wide range of databases
•PHP is free. Download it from the official PHP resource: www.php.net
•PHP is easy to learn and runs efficiently on the server side
If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server
will automatically parse them for you.
You do not need to compile anything or install any extra tools.
Because PHP is free, most web hosts offer PHP support.
Set Up PHP on Your Own PC
However, if your server does not support PHP, you must:
<?php
// PHP code goes here
?>
Basic program
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
OUTPUT:
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Output:
Hello World!
Hello World!
Hello World!
Program:
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
Output:
My car is red
My house is
My boat is
Comments in PHP
Single line comment :
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
• comments to leave out parts of a code
line<!DOCTYPE html>
<html>
<body>
<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
Output:
10
PHP Variables
Creating (Declaring) PHP Variables
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
Output:
Hey
Hello world!
5
10.5
• Output variable:
<!DOCTYPE html>
<html>
<body>
<?php
$txt = “yvu students.com";
echo “I love " . $txt . "!";
?>
</body>
</html>
Output:
Global scope:
<!DOCTYPE html> echo "<p>Variable x inside
<html> function is: $x</p>";
<body> }
myTest();
<?php
$x = 5; // global scope echo "<p>Variable x outside
function is: $x</p>";
?>
function myTest() {
// using x inside this function will
generate an error </body>
</html>
Output:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
</body>
Output:
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
</body>
Output:
15
Globel keyword 2:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y;
?>
</body>
</html>
Output:
15
PHP The static Keyword
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
</body>
Output:
0
1
2
PHP echo and print Statements
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
</body>
Output:
PHP is Fun!
Hello world!
I'm about to learn PHP!
This string was made with multiple parameters.
Display variable:
<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
</body>
Output:
Learn PHP
Study PHP at W3Schools.com
9
The PHP print Statement
Display text:
<!DOCTYPE html>
<html>
<body>
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
</body>
</html>
Output:
PHP is Fun!
Hello world!
I'm about to learn PHP!
Display variable:
<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
</body>
Output:
Learn PHP
Study PHP at W3Schools.com
9
PHP Data Types
PHP Data Types
Variables can store data of different types, and different data types can do different
things.
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
Output:
Hello world!
Hello world!
PHP Integer
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5985;
var_dump($x);
?>
</body>
</html>
Output:
int(5985)
PHP Float
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10.365;
var_dump($x);
?>
</body>
</html>
Output:
float(10.365)
• PHP Boolean
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
Output:
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
PHP Object
$myCar = new Car("black",
<!DOCTYPE html>
<html> "Volvo");
<body> echo $myCar -> message();
echo "<br>";
<?php
class Car { $myCar = new Car("red",
public $color; "Toyota");
public $model; echo $myCar -> message();
public function __construct($color, $model) {
?>
$this->color = $color;
$this->model = $model;
}
</body>
public function message() {
return "My car is a " . $this->color . " " . $this-
</html>
>model . "!";
}
}
Output:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
</body>
</html>
Output:
Null
PHP Resource
PHP Operators
PHP Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
PHP Arithmetic Operators
<?php
$x = 10;
$y = 6;
echo "<br>",$x + $y;
echo "<br>",$x - $y;
echo "<br>",$x * $y;
echo "<br>",$x / $y;
echo "<br>",$x % $y;
echo "<br>",$x ** $y;
?>
</body>
</html>
Output:
16
4
60
1.6666666666667
4
1000000
PHP Assignment Operators
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
Assignment Operators
<?php
Output:
$x = 10;
$y = 20; 20
40
20
$res=$x = $y; 400
echo $res."<br>"; 20
0
$res= $x += $y;
echo $res."<br>";
$res= $x -= $y;
echo $res."<br>";
$res= $x *= $y;
echo $res."<br>";
$res= $x /= $y;
echo $res."<br>";
$res= $x %= $y;
echo $res."<br>";
PHP Comparison Operators
Operator Name Example Result
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the
same type
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not
of the same type
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater
than zero, depending on if $x is less than, equal to,
or greater than $y. Introduced in PHP 7.
Program on comparision operators
<html> echo "TEST2 : a is neither greater than nor
not greater than b<br/>"; equal to b<br/>";
} }
<head>
if( $a < $b ) {
<title>Comparison
Operators</title> echo "TEST3 : a is if( $a <= $b ) {
</head> less than b<br/>"; echo "TEST6 : a is
}else { either less than or equal
<body> echo "TEST3 : a is to b<br/>";
not less than b<br/>"; }else {
} echo "TEST6 : a is
<?php
neither less than nor
$a = 42;
if( $a != $b ) { equal to b<br/>";
$b = 20; }
echo "TEST4 : a is
?>
not equal to b<br/>";
if( $a == $b ) {
}else {
echo "TEST1 : a is
</body>
equal to b<br/>"; echo "TEST4 : a is
equal to b<br/>"; </html>
}else {
}
echo "TEST1 : a is
not equal to b<br/>";
if( $a >= $b ) {
}
echo "TEST5 : a is
either greater than or
if( $a > $b ) {
equal to b<br/>";
echo "TEST2 : a is }else {
greater than b<br/>";
output
TEST1 : a is not equal to b
TEST2 : a is greater than b
TEST3 : a is not less than b
TEST4 : a is not equal to b
TEST5 : a is either greater than or equal to b
TEST6 : a is neither less than nor equal to b
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
x=6y=4x=5y=5
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
or Or $x or $y True if either $x or $y is
true
|| Or $x || $y True if either $x or $y is
true
PHP has two operators that are specially designed for strings.
<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2 . "<br>";
$txt1 .= $txt2;
echo $txt1;
?>
</body>
</html>
Output
Hello world!
Hello world!
PHP Array Operators
Array ( [a] => red [b] => green [c] => blue [d] => yellow )
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending
on conditions:
<?php
// if empty($user) = TRUE, set $status = "anonymous"
echo $status = (empty($user)) ? "anonymous" : "logged in";
echo("<br>");
</body>
</html>
Output
anonymous
logged in
PHP Constants
Syntax
define(name, value, case-insensitive)
Parameters:
<!DOCTYPE html>
<html>
<body>
<?php
// case-sensitive constant name
define("GREETING", "Welcome to yogi venama university.com!");
echo GREETING;
?>
</body>
</html>
Output:
<?php
// case-insensitive constant name
define("GREETING", "Welcome to proddatur.com!", true);
echo greeting;
?>
</body>
</html>
Output:
Welcome to proddatur.com!
PHP Constant Arrays
<!DOCTYPE html>
<html>
<body>
<?php
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
?>
</body>
</html>
Output:
Alfa Romeo
Constants are Global
<!DOCTYPE html>
<html>
<body>
<?php
define("GREETING", "Welcome to yvu of ysr engineering college.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
</body>
</html>
Output:
Very often when you write code, you want to perform different actions for
different conditions. You can use conditional statements in your code to do
this.
<?php
$t = date("H");
</body>
Output:
Have a good day!
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Program:
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Program:
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
</body>
Output:
The hour (of the server) is 10, and will give the following message:
Have a good day!
PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Program:
<!DOCTYPE html> echo "Your favorite color is blue!";
<html> break;
<body> case "green":
echo "Your favorite color is
<?php green!";
break;
$favcolor = "red";
default:
echo "Your favorite color is
switch ($favcolor) {
neither red, blue, nor green!";
case "red": }
echo "Your favorite color is ?>
red!";
break;
</body>
case "blue":
</html>
Output:
Your favorite color is red!
PHP Loops
Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost
equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as
a certain condition is true.
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
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
Program:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
</body>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Program 2:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 0;
</body>
</html>
Output:
The number is: 0
The number is: 10
The number is: 20
The number is: 30
The number is: 40
The number is: 50
The number is: 60
The number is: 70
The number is: 80
The number is: 90
The number is: 100
PHP do while Loop
The do...while loop will always execute the block of code once, it will then check the condition, and repeat
the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
Program:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
Program 2:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>
Output:
The number is: 6
PHP for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Program:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Program 2 :
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 100; $x+=10) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
Output:
The number is: 0
The number is: 10
The number is: 20
The number is: 30
The number is: 40
The number is: 50
The number is: 60
The number is: 70
The number is: 80
The number is: 90
The number is: 100
PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
Program:
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
</body>
Output:
red
green
blue
yellow
Program 2 :
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("sreedhar"=>"35", "Madhu"=>"37", "krishna"=>"43");
</body>
</html>
Output:
sreedhar = 35
Madhu = 37
krishna = 43
PHP Break and Continue
PHP Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
Program:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
PHP Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
Program:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
</body>
</html>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
Break and Continue in While Loop
You can also use break and continue in while loops:
Break Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 0;
</body>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
Continue Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 0;
</body>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
UNIT - IV
ARRAYS
What is an Array?
An array is a special variable, which can hold more than one value at a
time.
If you have a list of items (a list of car names, for example), storing the
cars in single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific
one? And what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can
access the values by referring to an index number.
PHP Arrays
<!DOCTYPE html>
<html>
<body>
<?php
$mobiles = array("Redme", "APPLE", "vivo");
echo "I like " . $mobiles[0] . ", " . $mobiles[1] . " and " . $mobiles[2] . ".";
?>
</body>
</html>
Output:
array();
<!DOCTYPE html>
<html>
<body>
<?php
$things = array("pen", "pencil", "marker");
echo count($things);
?>
</body>
</html>
Output:
3
PHP Indexed Arrays
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Indexed Arrays
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
Output:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
</body>
Output:
Volvo
BMW
Toyota
PHP Associative Arrays
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Associative Arrays
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("kumar"=>"35", "sree"=>"37", "krishna"=>"43");
echo "kumar is " . $age['kumar'] . " years old.";
?>
</body>
</html>
Output:
<?php
$age = array("kumar"=>"35", "sree"=>"37", "krishna"=>"43");
</body>
</html>
Output:
Key=kumar, Value=35
Key=sree, Value=37
Key=krishna, Value=43
PHP Multidimensional Arrays
In the previous pages, we have described arrays that are a single list of key/value pairs.
However, sometimes you want to store values with more than one key. For this, we have
multidimensional arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an
element.
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Two dimensional array
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
</body>
Output:
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
</body>
Output:
Row number 0
• Volvo
• 22
• 18
Row number 1
• BMW
• 15
• 13
Row number 2
• Saab
• 5
• 2
Row number 3
• Land Rover
• 17
•
PHP Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
Output:
BMW
Toyota
Volvo
Ascending numerical order:
<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
Output:
2
4
6
11
22
Sort Array in Descending Order -
rsort()
Descending alphabetical order:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Output:
Volvo
Toyota
BMW
Descending numerical order:
<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
Output:
22
11
6
4
2
Sort Array (Ascending Order), According to Value -
asort()
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
</body>
Output:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
Sort Array (Ascending Order), According to Key
- ksort()
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
</body>
Output:
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
Sort Array (Descending Order), According to
Value - arsort()
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
</body>
Output:
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
Sort Array (Descending Order), According to
Key - krsort()
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
</body>
Output:
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
PHP Form Handling
A Simple HTML Form
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
Output:
GET vs. POST
Both GET and POST create an array (e.g. array( key1 => value1, key2
=> value2, key3 => value3, ...)). 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, which means that they are always accessible, regardless
of scope - and you can access them from any function, class or file
without having to do anything special.
$_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.
When to use GET?
Information sent from a form with the GET method is visible to
everyone (all variable names and values are displayed in the URL). GET
also has limits on the amount of information to send. The limitation is about
2000 characters. However, because the variables are displayed in the URL,
it is possible to bookmark the page. This can be useful in some cases.
Note: GET should NEVER be used for sending passwords or other sensitive
information!
When to use POST?
Information sent from a form with the POST method is invisible to
others (all names/values are embedded within the body of the HTTP
request) and has no limits on the amount of information to send.
However, because the variables are not displayed in the URL, it is not
possible to bookmark the page.
PHP Form Validation
The name, email, and website fields are text input elements, and the
comment field is a textarea. The HTML code looks like this:
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></
textarea>
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
The Form Element
The HTML code of the form looks like this:
<form method="post" action="<?
php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
When the form is submitted, the form data is sent with method="post".
What is the $_SERVER["PHP_SELF"] variable?
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
HI
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
h i
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular
expression also allows dashes in the URL). If the URL address syntax is not valid, then
store an error message:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
PHP - Validate Name, E-mail, and URL
<!DOCTYPE HTML> // check if name only contains letters and
<html> whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",
<head>
$name)) {
<style> $nameErr = "Only letters and white
.error {color: #FF0000;} space allowed";
</style> }
</head> }
<body>
if (empty($_POST["email"])) {
$emailErr = "Email is required";
<?php } else {
// define variables and set to empty $email = test_input($_POST["email"]);
values // check if e-mail address is well-
$nameErr = $emailErr = $genderErr = formed
$websiteErr = ""; if (!filter_var($email,
FILTER_VALIDATE_EMAIL)) {
$name = $email = $gender = $comment =
$emailErr = "Invalid email format";
$website = ""; }
}
if ($_SERVER["REQUEST_METHOD"]
== "POST") { if (empty($_POST["website"])) {
if (empty($_POST["name"])) { $website = "";
} else {
$nameErr = "Name is required";
$website =
} else { test_input($_POST["website"]);
$name = test_input($_POST["name"]);
h i
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="other") echo "checked";?>
PHP - Complete Form Example
// check if name only contains
<!DOCTYPE HTML>
letters and whitespace
<html>
if (!preg_match("/^[a-zA-
<head> Z-' ]*$/",$name)) {
<style> $nameErr = "Only letters and
.error {color: #FF0000;} white space allowed";
</style> }
</head> }
<body>
if (empty($_POST["email"])) {
<?php $emailErr = "Email is required";
// define variables and set to } else {
empty values $email =
$nameErr = $emailErr = $genderErr test_input($_POST["email"]);
// check if e-mail address is
= $websiteErr = "";
well-formed
$name = $email = $gender =
if (!filter_var($email,
$comment = $website = ""; FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email
if ($_SERVER["REQUEST_METHOD"] format";
== "POST") { }
if (empty($_POST["name"])) { }
$nameErr = "Name is
required"; if (empty($_POST["website"])) {
} else { $website = "";
$name = } else {
hi
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the
first match. If no match is found, it will return FALSE.
Tip: The first character position in a string is 0 (not 1).
Tip: The first character position in a string is 0 (not 1).
str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some
other characters in a string.
Program on string functions
<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello world!") . "<br/>";
echo str_word_count("Hello world!") . "<br/>";
echo strrev("Hello world!") . "<br/>";
echo strpos("Hello world!", "world") . "<br/>";
echo str_replace("world", "Dolly", "Hello world!") . "<br/>";
echo strtolower("GeeksForGeeks") . "<br/>";
echo strtoupper("hello world") . "<br/>";
echo strstr( "hello world","hello") . "<br/>";
?>
</body>
</html>
output
12
2
!dlrow olleH
6
Hello Dolly!
Geeksforgeeks
HELLO WORLD
hello world
Php functions
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
output:
Hello world!
PHP Function Arguments
Program by passing single argument into t function
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
output
Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.
Program passing two
arguments into the function
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege","1975");
familyName("Stale","1978");
familyName("Kai Jim","1983");
?>
</body>
</html>
output
we did not have to tell PHP which data type the variable is.
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.
In PHP 7, type declarations were added. This gives us an option to
specify the expected data type when declaring a function, and by
adding the strict declaration, it will throw a "Fatal Error" if the data
type mismatches.
Program without declaring type of
data
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" ischanged to int(5), and it will
return 10
?>
PHP Default Argument Value
program
<?php declare(strict_types=1); // strict requirement ?>
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
output
<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
</body>
</html>
output
5 + 10 = 15
7 + 13 = 20
2+4=6
PHP Return Type Declarations program
6.4
Program with return datatype
6
Passing Arguments by Reference
<!DOCTYPE html>
<html>
<body>
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
</body>
</html>
output
7
Working with files
Syntax
file_get_contents(path, include_path, context, start, max_length)
program on file_get_contents()
<!DOCTYPE html>
<html>
<body>
<?php
echo file_get_contents("test.txt");
?>
</body>
</html>
0utput
Hello, this is a test file. There are three lines here. This is the last line
Definition
PHP filesize() Function
and Usage
The filesize() function returns the size of a file.
Note: The result of this function is cached.
Use clearstatcache() to clear the cache.
Syntax
filesize(filename)
Program on filesize()
<!DOCTYPE html>
<html>
<body>
<?php
echo filesize("test.txt");
?>
</body>
</html>
Output
80
PHP filesize() Function
Program on filesize() function
<!DOCTYPE html>
<html>
<body>
<?php
echo filesize("test.txt");
?>
</body>
</html>
Output:
8O
PHP fileowner() Function
Program using fileowner()
function
<!DOCTYPE html>
<html>
<body>
<?php
echo fileowner("test.txt");
?>
</body>
</html>
Output
0
PHP fileatime() Function
Program on fileatime()
<!DOCTYPE html>
<html>
<body>
<?php
echo fileatime("webdictionary.txt");
echo "<br>";
echo "Last access: ".date("F d Y H:i:s.",
fileatime("webdictionary.txt"));
?>
</body>
</html>
Output
1628462283
Last access: August 08 2021 22:38:03.
PHP filetype() Function
Program on filetype()
<!DOCTYPE html>
<html>
<body>
<?php
echo filetype("test.txt");
?>
</body>
</html>
Output
file
PHP stat() Function
Program on stat()
<!DOCTYPE html>
<html>
<body>
<?php
$stat = stat("test.txt");
echo "Access time: " .$stat["atime"];
echo "<br>Modification time: " .$stat["mtime"];
echo "<br>Device number: " .$stat["dev"];
?>
</body>
</html>
output
<?php
echo realpath("test.txt");
?>
C:\Inetpub\testweb\test.txt
PHP basename() Function
<?php
$path = "/testweb/home.php";
//Show filename
echo basename($path) ."<br/>";
//Show filename, but cut off file extension for ".php" files
echo basename($path,".php");
?>
Syntax
file(filename, flag, context)
Program on file()
<!DOCTYPE html>
<html>
<body>
<?php
print_r(file("test.txt"));
?>
</body>
</html>
Output
Array ( [0] => Hello, this is a test file. [1] => There are three lines here. [2]
=> This is the last line. )
Opening and closing of files
<!DOCTYPE html>
<html>
<body>
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
</body>
</html>
Output
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language PHP = PHP Hypertext
Preprocessor SQL = Structured Query Language SVG = Scalable Vector
Graphics XML = EXtensible Markup Language
PHP Close File - fclose()
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to ope
file!");
// Output one line until end-of-file
while(!feof($myfile))
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
READ nde write of files
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
echo fgets($myfile);
fclose($myfile);
?>
Output :
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
Output
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup
Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector
Graphics XML = EXtensible Markup Language
PHP Write to File - fwrite()
The fwrite() function is used to write to a file.
The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string $txt that first contained "John Doe" and second
contained "Jane Doe". After we finished writing, we closed the file using the fclose() function.
If we open the "newfile.txt" file it would look like this:
John Doe
Jane Doe
PHP copy() Function
Definition and Usage
The copy() function copies a file.
Note: If the to_file file already exists, it will be overwritten.
Syntax
copy(from_file, to_file, context)
Example
Copy "source.txt" to "target.txt":
<?php
echo copy("source.txt","target.txt");
?>
PHP rename() function
Example
Rename a directory + a file:
<?php
rename("images","pictures");
rename("/test/file1.txt","/home/docs/my_file.txt");
?>
PHP unlink() Function
Example
Delete a file:
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
unlink("test.txt");
?>
https://medium.com/oceanize-geeks/concepts-of-database-
architecture-dfdc558a93e4
MySQL INSERT INTO
Statement
DELETE Syntax
DELETE FROM table_name WHERE condition;
Example
DELETE FROM Customers;
PHP Error Handling
Example
<?php
if(file_exists("mytestfile.txt")) {
$file = fopen("mytestfile.txt", "r");
} else {
die("Error: The file does not exist.");
}
?>
Now if the file does not exist you get an error like this:
The default error handler for PHP is the built in error handler. We are
going to make the function above the default error handler for the
duration of the script.
It is possible to change the error handler to apply for only some
errors, that way the script can handle different errors in different
ways. However, in this example we are going to use our custom error
handler for all errors:
set_error_handler("customError");
Since we want our custom function to handle all errors,
the set_error_handler() only needed one parameter, a second
parameter could be added to specify an error level.
Example
Testing the error handler by trying to output variable that does not exist:
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//trigger error
echo($test);
?>
The output of the code above should be something like this:
In a script where users can input data it is useful to trigger errors when an illegal input
occurs. In PHP, this is done by the trigger_error() function.
Example
In this example an error occurs if the "test" variable is bigger than "1":
<?php
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below");
}
?>
The output of the code above should be something like this:
Notice: Value must be 1 or below
in C:\webfolder\test.php on line 6
Error Logging
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");|}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);}
?>
And the mail received from the code above looks like this:
This should not be used with all errors. Regular errors should be logged on the server using the default
PHP logging system.
PHP MySQL Database
With PHP, you can connect to and manipulate databases.
MySQL is the most popular database system used with PHP.
What is MySQL?
• MySQL is a database system used on the web
• MySQL is a database system that runs on a server
• MySQL is ideal for both small and large applications
• MySQL is very fast, reliable, and easy to use
• MySQL uses standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use
• MySQL is developed, distributed, and supported by Oracle Corporation
• MySQL is named after co-founder Monty Widenius's daughter: My
The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of
columns and rows.
Databases are useful for storing information categorically. A company may have a database with the
following tables:
• Employees
• Products
• Customers
PHP + MySQL Database System
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)
Database Queries
A query is a question or a request.
We can query a database for specific information and have a recordset returned.
Look at the following query (using standard SQL):
The query above selects all the data in the "LastName" column from the "Employees" table.
To learn more about SQL, please visit our SQL tutorial.
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated
in 2012.
Should I Use MySQLi or
PDO?
If you need a short answer, it would be "Whatever you like".
PDO will work on 12 different database systems, whereas MySQLi will only work with
MySQL databases.
So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries. With
MySQLi, you will need to rewrite the entire code - queries included.
Both support Prepared Statements. Prepared Statements protect from SQL injection,
and are very important for web application security.
MySQL Examples in Both MySQLi and PDO Syntax
In this, and in the following chapters we demonstrate three ways of working with PHP and
MySQL:
MySQLi (object-oriented)
MySQLi (procedural)
PDO
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when
php5 mysql package is installed.
For installation details, go to: http://php.net/manual/en/mysqli.installation.php
PDO Installation
For installation details, go to: http://php.net/manual/en/pdo.installation.php
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Close the Connection
The connection will be closed automatically when the script ends. To close the connection
before, use the following:
MySQLi Object-Oriented:
$conn->close();
MySQLi Procedural:
mysqli_close($conn);
PDO:
$conn = null;
HP Create a MySQL Database
o A database consists of one or more tables.
o You will need special CREATE privileges to create or to delete a MySQL database.
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username,
$password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$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 (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
PHP MySQL Create Table
A database table has its own unique name and consists of columns and rows.
We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname",
"email" and "reg_date":
$CONN->CLOSE();
?>
Example (MySQLi Procedural)
<?php // sql to create table
$servername = "localhost"; $sql = "CREATE TABLE MyGuests (
$username = "username"; id INT(6) UNSIGNED AUTO_INCREMENT
$password = "password"; PRIMARY KEY,
$dbname = "myDB"; firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
// Create connection email VARCHAR(50),
$conn = mysqli_connect($servername, reg_date TIMESTAMP DEFAULT
$username, $password, $dbname); CURRENT_TIMESTAMP ON UPDATE
// Check connection CURRENT_TIMESTAMP
if (!$conn) { )";
die("Connection failed: " .
mysqli_connect_error()); if (mysqli_query($conn, $sql)) {
} echo "Table MyGuests created
successfully";
} else {
echo "Error creating table: " .
mysqli_error($conn);
}
mysqli_close($conn);
Example (PDO)
<?php // use exec() because no results are
$servername = "localhost"; returned
$username = "username"; $conn->exec($sql);
$password = "password"; echo "Table MyGuests created
$dbname = "myDBPDO"; successfully";
} catch(PDOException $e) {
try { echo $sql . "<br>" . $e->getMessage();
$conn }
= new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password); $conn = null;
// set the PDO error mode to exception ?>
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);