Professional Documents
Culture Documents
PHP
Syllabus
Introduction and basic syntax of PHP, decision and looping with examples, PHP and HTML, Arrays,
Functions, Browser control and detection, string, Form processing, Files, Advance Features: Cookies
and Sessions, Object Oriented Programming with PHP
Introduction
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to
create dynamic content that interacts with databases. PHP is basically used for developing web
based software applications.
PHP is an interpreted language, i.e., there is no need for compilation.
PHP is faster than other scripting languages, for example, ASP and JSP.
PHP is a server-side scripting language, which is used to manage the dynamic content of the
website.
PHP can be embedded into HTML.
PHP is an object-oriented language.
PHP is an open-source scripting language.
PHP is simple and easy to learn language.
Features of PHP
PHP is one of the most widely used language over the web.
PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, through email
you can send data, return data to the user.
You add, delete, modify elements within your database through PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
PHP Syntax
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
PHP Echo
PHP echo is a language construct, not a function.
PHP echo statement can be used to print the string, multi-line strings, escaping characters, variable, array,
etc
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
PHP Variables
In PHP, a variable is declared using a $ sign followed by the variable name.
As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.
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)
Example
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
Example
<!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>
PHP is Case Sensitive, so $color, $COLOR, and $coLOR are treated as three different
variables.
PHP echo and print Statements
With PHP, there are two basic ways to get output: echo and print.
The differences are: echo has no return value while print has a return value of 1 so it can
be used in expressions. echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.
Example
<!DOCTYPE html>
<html>
<body>
<?php
print "<h2>PHP </h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "<h2>PHP </h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
</body>
</html>
PHP - Decision Making
The conditional statements are used to perform different actions based on the different
conditions.
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 - The if Statement
Syntax
if (condition) {
code to be executed if condition is true;
}
Example
<!DOCTYPE html>
<html>
<body>
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
</body>
</html>
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;
}
Example
<!DOCTYPE html>
<html>
<body>
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
</body>
</html>
Example
PHP - The if...else..if Statement
The if...elseif...else statement executes different codes for more than two conditions.
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;
}
Example
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
PHP - The switch Statement
switch (expression){
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
Example
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue": Output:
echo "Your favorite color is blue!"; Your favorite color is red!
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
break;
}
?>
PHP break
The PHP break keyword is used to terminate the execution of a loop prematurely. The
break statement is situated inside the statement block. If gives you full control and
whenever you want to exit from the loop you can come out. After coming out of a loop
immediate statement to the loop will be executed.
Example
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )
break;
}
echo ("Loop stopped prematurely at i = $i" );
?>
Output: Loop stopped prematurely at i = 3
PHP continue
The PHP continue keyword is used to halt the current iteration of a loop but it
does not terminate the loop. Just like the break statement the continue
statement is situated inside the statement block containing the code that the
loop executes, preceded by a conditional test. For the pass encountering
continue statement, rest of the loop code is skipped and next pass starts.
Example
<?php
$array = array( 1, 2, 3, 4, 5);
foreach ( $array as $value )
{
Output
if( $value == 3 )
{ continue; Value is 1
Value is 2
} Value is 4
echo "Value is $value <br />"; Value is 5
}
?>
PHP Loops
<?php
$x = 0;
while($x <= 100) {
echo "The number is: $x <br>";
$x+=10;
}
?>
</body>
</html>
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);
Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>
The for loop - Loops through a block of code a specified number of times.
The for loop is used when you know in advance how many times the script should run.
Syntax
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
The foreach loop - Loops through a block of code for each element in an array.
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;
}
For every loop iteration, the value of the current array element is assigned to $value
and the array pointer is moved by one, until it reaches the last array element.
Example
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<?php $array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{ echo "Value is $value <br />"; }
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
</body>
</html>
PHP Arrays
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example
First method
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Second method
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Example
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5); OUTPUT
foreach( $numbers as $value )
{ Value is 1
echo "Value is $value <br />"; Value is 2
} Value is 3
/* Second method to create array. */ Value is 4
$numbers[0] = "one"; Value is 5
$numbers[1] = "two"; Value is one
$numbers[2] = "three"; Value is two
$numbers[3] = "four"; Value is
$numbers[4] = "five"; three Value
foreach( $numbers as $value ) is four Value
{ is five
echo "Value is $value <br />";
}
?>
</body> </html>
Associative Array
Associative array will have their index as string so that you can establish a strong association
between key and values.
There are two ways to define associative array:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2. $salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, “John" => 1000, "zara" => 500);
</body>
</html>
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an
array. And each element in the sub-array can be an array, and so on.
Values in the multi-dimensional array are accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three subjects −
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
</body>
OUTPUT
</html>
Marks for mohammad in physics :
35 Marks for qadir in maths : 32
Marks for zara in chemistry : 39
Functions
Function is a set of statements that perform a specific task and can be executed at any
time. PHP defines several built in functions and also supports user –defined function.
The general syntax of a PHP function is as follows,
function function_name(args 1, args 2, …., args n )
{ // block of codes / statements;
}
Example
<?php
average();
function average()
{
$sub1=50;
$sub2=50;
$total = $sub1 + $sub2;
$avg = $total / 2;
echo “The Average is: $avg”;
}
?>
PHP Functions with Parameters
Information can be passed to functions through arguments. An argument is just like a
variable.
Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
Default Argument Value
<?php
function setHeight(int $minheight = 50)
{
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Functions returning value
Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
<?php
header(“Cache-Control: no-cache”);
$self=$SERVER[‘PHP_SELF];
…
?>
It is important to know which browser and other details you are dealing with in order to
appropriately render the web page.
The browser that the server is dealing with can be identified using:
$browser_ID=$_SERVER[‘HTTP_USER_AGENT’];
$_SERVER is a global array with lots of useful information stored in it about the server’s
current status.
The HTTP_USER_AGENT is an environmental variable that contains information.
Eg1
Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebkit /312.1 (KHTML, like Gecko)
Safari/312
This shows the Safari browser running on Mac OS X.
Eg2
Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-0; en-US; rv:1.7.6) Gecko/20050225
Firefox/1.0.1
This shows the Firefox running on Mac OS X.
PHP Strings
The PHP superglobals $_GET and $_POST are used to collect form-data .
Example
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?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;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
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
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Output
$_SERVER["PHP_SELF"] variable
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently
executing script.
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of
jumping to a different page.
htmlspecialchars() function
The htmlspecialchars() function converts special characters to HTML entities. This means
that it will replace HTML characters like < and > with < and >. This prevents attackers
from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks)
in forms.
PHP trim() function -Strip unnecessary characters (extra space, tab, newline) from the
user input data.
PHP stripslashes() function - Remove backslashes (\) from the user input data
PHP-Files
PHP File System allows us to create file, read file line by line, read file character by
character, write file, append file, delete file and close file.
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.
Example
<?php
$myfile = fopen("web.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
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 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.
fread($myfile,filesize(“web.txt"));
The following example assigns the content of a text file to a variable then displays those contents on the web
page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>
<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );
Following example will create two cookies name and age these cookies will be expired after one hour
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>.
use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
Deleting Cookie with PHP
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>
PHP Sessions
<?php session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output: Pageviews=1
In the example below, we create a simple page-views counter. The
isset() function checks if the "views" variable has already been set.
If "views" has been set, we can increment our counter. If "views"
doesn't exist, we create a "views" variable, and set it to 1:
<?php session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy()
function.
The unset() function is used to free the specified session variable:
<?php unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php session_destroy();
?>
session_destroy() will reset your session and you will lose all your stored session data.
Difference between cookies and sessions
Object Oriented Programming with PHP
Polymorphism – this is concerned with having a single form but many different
implementation ways. The main purpose of polymorphism is;
Simplify maintaining applications and making them more extendable.
OOPs Concepts in PHP
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}