UNIT I (Introduction To PHP)
UNIT I (Introduction To PHP)
(Unit I)
Prepared By:
Ukesh Bhattarai
Server Side Scripting
PHP was created by Rasmus Lerdorf in 1994 and has since evolved into
a powerful scripting language for web development.
Hypertext Preprocessor(Open Source Scripting Language).
PHP is used for developing dynamic websites, handling forms, managing
databases, and creating CMS applications.
Open-source, cross-platform, easy to learn, database connectivity, rich
library support, and high scalability.
Popular Applications Built Using PHP: WordPress, Facebook (early
versions), and Laravel-based applications.
PHP runs on various platforms(Mac OS, Linux, UNIX, Windows)
PHP is compatible with all servers used until today. For example: XAMPP,
APACHE, NGINX etc.
Supports wide ranges of databases.
It is free and can access from www.php.net
Server side scripting using PHP
Features of PHP
Simple
Interpreted
Faster
Open Source
Platform Independent
Case Sensitive
Real Time access(Chats, Live Games)
Language Basics
Lexical Structures:
Syntax Rules and Code Structure: PHP scripts start with <?php and end
with ?>. It is case-sensitive and follows C-like syntax.
PHP supports single-line (// and #) and multi-line (/**/)comments.
PHP can be embedded within HTML files using standard PHP tags.
Hello World!!
<html>
<head>
<title>PHP test</title>
</head>
<body>
<?php
echo ‘<p>Hello World!!</p>’;
?>
</body>
</html>
Variables
$variablename = value;
Naming Rules:
Variable name must start with a letter (a-z or A-Z) or an underscore(_)
followed by any number of letters, numbers, or underscores.
Variable names are case sensitive.
Avoid starting variable names with numbers or special characters.
Variable variables:
PHP allows the use of variable variables, where the name of a
variable is dynamic and determined by the value of another variable.
This feature can be useful in certain scenarios but should be used
cautiously to maintain code readability.
For example:
<?php
$varName = 'dynamicVar';
$$varName = 'I am dynamic!';
echo $dynamicVar;
?>
Scope of Variables:
The scope of a variable determines where it can be accessed within a script. PHP
has three main scopes:
Local Scope: Variables declared within a function are local to that function and cannot
be accessed outside of it.
Global Scope: Variables declared outside of any function have a global scope and can
be accessed anywhere in the script, except inside functions unless explicitly specified.
To access a global variable within a function, use the global keyword or the $GLOBALS array
<?php
$globalVar = "I'm global";
function testFunction() {
global $globalVar;
echo $globalVar
}
testFunction();
?>
Static Variables
Static variables maintain their value between function calls. For example:
<?php
function counter()
{
static $count = 0;
$count++;
echo $count;
}
counter();
counter();
counter();
?>
Predefined variables
PHP supports various data types, which can be broadly categorized into
scalar, compound, and special types.
These data types define the kind of values a variable can hold.
Scalar Types:
1. Integer
2. Float
3. String
4. Boolean
Compound types:
Compound types can hold multiple values.
1. Array
Stores multiple values in one variable.
Types of arrays:
Indexed array (uses numeric keys)
Associative array (uses named keys)
Multidimensional array (array inside another array)
2. Object
• Special Types:
• NULL
• Represents a variable with no value.
• Resource
• Used for external resources like database connections, file handles, sockets, etc.
Type Conversion and Type Juggling
$var = "100";
$intVar = (int)$var;
var_dump($intVar);
Operators in PHP
Operators are symbols that tell the PHP processor to perform specific actions,
such as arithmetic, comparisons, or logical operations.
Some regular operators:
1. Arithemetic Operators:
These operators perform basic arithmetic operations:
•Addition (+): Adds two operands.
•Example: $sum = $a + $b;
•Exponentiation (**): Raises the left operand to the power of the right.
•Example: $power = $a ** $b;
2. Assignment Operators:
•Identical (===): Returns true if operands are equal and of the same type.
•Example: $a === $b
•Not Equal (!= or <>): Returns true if operands are not equal.
•Example: $a != $b
•Not Identical (!==): Returns true if operands are not equal or not of the same type.
•Example: $a !== $b
•Greater Than (>): Returns true if the left operand is greater than the right.
•Example: $a > $b
•Less Than (<): Returns true if the left operand is less than the right.
•Example: $a < $b
•Greater Than or Equal To (>=): Returns true if the left operand is greater than or equal to the right.
•Example: $a >= $b
•Less Than or Equal To (<=): Returns true if the left operand is less than or equal to the right.
•Example: $a <= $b
•Spaceship Operator (<=>): Returns -1 if the left operand is less, 0 if equal, and 1 if greater.
•Example: $a <=> $b
Logical Operators:
<?php
$a = NULL;
if(!isset($a))
{
echo “True”;
}
else
echo “False”;
?>
Precedence order of Operators
Parenthesis()
Exponentiation **
Multiplication *, Division /,Modulus %
Addition +, Subtraction -
Flow Control Statements
}
else {
}
if...elseif...else Statement: Evaluates multiple conditions in
sequence, executing the corresponding code block for the first true
condition.
if ($condition1){
}
elseif ($condition2) {
}
else {
}
Switch Statement
Selects one of many code blocks to execute based on the value of an
expression.
If we have menu driven/choice based program, we can use switch case.
switch (expression) {
case value1:
break;
case value2:
break;
default:
}
Looping Statements
For example:
$a = 1;
$a++;
}
do...while Loop: Similar to the while loop, but guarantees that the
code block is executed at least once before evaluating the condition.
do {
} while ($condition);
For example:
$a = 1;
do{
echo “value is: “ .$a. “<br>”;
$a++;
}while($a <=10);
for Loop: Executes a code block a specific number of times, with
initialization, condition, and iteration expressions.
for ($initialization; $condition; $increment) {
}
For example:
for($a=1;a<=10;a++)
{
echo “$a”;
}
foreach Loop: Specifically designed for iterating over arrays or objects.
In PHP, include and require statements are used to incorporate the content of
one PHP file into another.
This practice promotes code reusability and modularity, allowing you to
maintain common code segments, such as headers, footers, or configuration
settings, in separate files and include them wherever needed.
include 'filename.php';
require 'filename.php';
Error Handling:
include: Emits a warning (E_WARNING) if the specified file cannot be found or
included, but the script continues execution.
require: Emits a fatal error (E_COMPILE_ERROR) if the specified file cannot be
found or included, halting the script execution.
For Example:
Assume you have a file named header.php containing common
header elements:
<!-- header.php -->
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
</header>
You can include this header in your main page as follows:
<!-- index.php -->
<?php
include 'header.php';
?>
<main>
<p>This is the main content of the page.</p>
</main>
</body>
</html>
Embedding PHP code within HTML allows you to create dynamic web
pages by integrating server-side logic directly into your HTML structure.
This approach is fundamental in web development, enabling the
generation of content that can change based on various factors, such as
user input or data from a database.
For example:
<!DOCTYPE html>
<html>
<head>
<title>My Dynamic Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>
<?php
phpinfo();
?>
</p>
</body>
</html>
Important Considerations:
File Extension: Ensure your file has a .php extension so that the server
processes the PHP code within it.
Server Configuration: The server must have PHP installed and properly
configured to execute PHP code.