Unit 1 Introduction to PHP Updated
Unit 1 Introduction to PHP Updated
Unit 1
Introduction to PHP
Introduction to PHP
PHP, which stands for Hypertext Preprocessor, is a popular server-side scripting language
designed for web development. It is used to create dynamic web pages and can be embedded into
HTML. PHP code is executed on the server, which means the code is processed on the web server
before the result is sent to the web browser. PHP can interact with databases, manage sessions,
create cookies, and generate dynamic page content. It is widely used for building websites and
web applications.
One of the key features of PHP is its ability to seamlessly integrate with various database
management systems, such as MySQL, PostgreSQL, and SQLite, making it an ideal choice for building
dynamic, database-driven websites and web applications.
PHP code is typically processed on a web server by a PHP interpreter, which generates the
resulting web page. This allows PHP to create dynamic web content, interact with databases,
handle forms, and perform many other tasks needed for web development.
1
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
2
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
3
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Step 2: After downloading XAMPP, double click on the downloaded file and allow XAMPP to make changes
in your system. A window will pop-up, where you have to click on the Next button.
Step 3: Here, select the components, which you want to install and click Next.
4
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Step 4: Choose a folder where you want to install the XAMPP in your system and click Next.
5
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Step 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.
Step 7: A finish window will display after successful installation. Click on the Finish button.
6
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run the php program on the
localhost.
How to run PHP programs on XAMPP, see in the next tutorial.
7
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
8
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
<h1>Hello </h1>
<?php
echo "Hello world";
?>
</body>
</html>
Output
When you access this PHP file through a web server, the PHP code will be executed on the server, and the
resulting HTML will be sent to the browser for display. The browser will only see the HTML output and
won't know that PHP was used to generate it.
9
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Understanding PHP
Understanding PHP (Hypertext Preprocessor) is essential for developing dynamic web applications.
1. What is PHP?
o PHP is a server-side scripting language used for web development. It's embedded within
HTML to create dynamic content, interact with databases, manage sessions, and perform
other server-side tasks.
2. Basic Syntax:
o PHP code is enclosed within <?php and ?> tags.
o Statements end with a semicolon (;).
3. Variables:
o Variables in PHP start with a dollar sign ($), followed by the variable name.
o They can store various data types like strings, integers, floats, arrays, objects, etc.
o Example: $name = "John";
4. Data Types:
o PHP supports several data types including:
String
Integer
Float (floating-point numbers)
Boolean (true or false)
Array
Object
Null
Resource
5. Operators:
o PHP supports various operators like arithmetic, assignment, comparison, logical, etc.
6. Control Structures:
o PHP provides control structures like if, else, elseif, switch, while, do-while, for,
foreach, etc., for flow control.
7. Functions:
o PHP allows you to define and call functions to organize code into reusable blocks.
o Built-in functions are also available for common tasks.
8. Arrays:
o Arrays in PHP can store multiple values in a single variable.
o They can be indexed arrays, associative arrays, or multidimensional arrays.
9. Forms Handling:
10
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
o PHP can process form data submitted via GET or POST methods using $_GET and
$_POST superglobal arrays.
10. Database Interaction:
o PHP can interact with databases like MySQL, PostgreSQL, SQLite, etc., using database-
specific extensions (e.g., mysqli, PDO).
o It allows executing SQL queries, fetching results, and performing database
transactions.
11. File Handling:
o PHP provides functions for handling files and directories on the server, such as reading,
writing, deleting files, etc.
12. Sessions and Cookies:
o PHP enables session management and cookie handling for maintaining user state across
multiple requests.
13. Error Handling:
o PHP offers error reporting and handling mechanisms to debug and manage errors gracefully.
14. Security:
o PHP provides features like input validation, data sanitization, and protection against
common security vulnerabilities like SQL injection, XSS (Cross-Site Scripting), CSRF
(Cross-Site Request Forgery), etc.
15. Object-Oriented Programming (OOP):
o PHP supports object-oriented programming concepts like classes, objects, inheritance,
encapsulation, and polymorphism.
11
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
<!-- DOCTYPE html-->
<html>
<head>
<title> PHP and HTML </title>
</head>
<h1>
<?php
echo "Divya","Setty";
?>
</h1>
<p> Embedding PHP and HTML </p>
</body>
</html>
Output:
12
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Output:
13
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example :
$name = "John"; // Variable assignment
2. Multi-line comment : Multi-line comments start with /* and end with */. They can span
multiple lines and are useful for longer explanations or commenting out blocks of code.
Syntax
/*
This is a multi-line comment.
It can span multiple lines.
*/
Example:
/*
$name = "John";
$age = 30;
*/
3. Doc Comments (Documentation Comments): Doc comments are a special type of multi-line
comment used to document functions, classes, methods, or variables. They follow a specific
format and are commonly used by automated documentation generators like PHPDoc.
14
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
/**
* This function calculates the sum of two numbers.
*
* @param int $a The first number
* @param int $b The second number
* @return int The sum of $a and $b
*/
function sum($a, $b)
{
return $a + $b;
}
15
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
2. Using HTML and PHP intermixed: You can mix HTML and PHP to generate dynamic content.
<!DOCTYPE html>
<html>
<head>
<title>Whitespace Example</title>
</head>
<body>
<?php
// PHP code block
$name = "John"; // Multiple spaces before and after the assignment
$age = 30; // Spaces between the variable name and value
$country= "USA"; // Uneven spacing around the assignment
?>
<h1>Welcome, <?php echo $name; ?>!</h1>
<p>You are <?php echo $age; ?> years old and from <?php echo $country; ?>.</p>
</body>
</html>
Output:
3. Using header() function: This function sends a raw HTTP header to the browser.
Example:
<?php
header('Location: http://www.example.com/');
echo “Welcome”,”to”,”Computer”,”lab”;
?>
16
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
Or
<?php
header(“Content-Type: text/plain“);
echo “Welcome”,”to”,”Computer”,”lab”;
?>
Output
4. Using Server-Side Includes (SSI): If your server is configured for it, you can include the output
of another script directly in your PHP file.
Example:
<?php
include 'footer.php';
?>
17
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
5. Using Output Buffering: You can use output buffering to capture the output of PHP code and
then decide whether to send it or discard it.
Example:
<?php
ob_start();
echo "Hello, World!";
$content = ob_get_clean();
echo $content;
?>
6. Sending JSON data: For AJAX requests or API responses, you can encode data as JSON and send
it to the browser.
Example:
<?php
$data = array("name" => "John", "age" => 30, "city" => "New York");
header('Content-Type: application/json');
echo json_encode($data);
?>
Data types in PHP
In PHP, data types can be classified into two main categories: primitive data types and compound data
types. Primitive Data Types:
1. Scalar Types:
o Integer: Represents whole numbers, such as 1, 100, -500, etc.
Example:
```php
$integerVar = 10;
```
Note: Single triple quote (‘’’) or double triple quotes(“””) used to represent multi-line strings.
o Float (Floating Point Numbers): Represents numbers with decimal points, such as 3.14,
-0.5, etc.
Example:
```php
$floatVar = 3.14;
```
18
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
o String: Represents a sequence of characters, enclosed within single quotes (' ') or
double quotes (" ").
Example:
``php
$stringVar = "Hello, World!";
```
o Boolean: Represents a binary value, either true or false.
Example:
```php
$boolVar = true;
```
2. Special Scalar Types:
o NULL: Represents a variable with no value or a variable that has been explicitly set to
null.
Example:
```php
$nullVar = null;
```
Compound Data Types:
1. Array: Represents a collection of elements, which can be indexed or associative. Indexed arrays
use numeric keys, while associative arrays use string keys.
Example:
// Indexed array
$indexedArray = array(1, 2, 3);
// Associative array
$assocArray = array("name" => "John", "age" => 30);
// Multidimensional array
$multiArray = array(
array("John", "Doe"),
array("Jane", "Smith")
);
```
19
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
2. Object: Represents instances of classes. An object is an instance of a class, and it can contain
properties and methods.
Example:
class Person
{
public $name;
public $age;
These are the main data types in PHP, and understanding them is crucial for effective programming. They
provide flexibility and versatility in handling different types of data in PHP applications.
Example:
// Regular function
function regularFunction($name)
{
echo "Hello, $name!";
}
20
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Keywords in PHP
In PHP, keywords are reserved words that have special meanings and are used to perform specific tasks
or define certain elements of the language syntax. These keywords cannot be used as identifiers (such as
variable names, function names, etc.) because they have predefined meanings within the PHP language.
Here are some important categories of keywords in PHP:
1. Control Structures Keywords:
o if, else, elseif: Used for conditional statements.
o switch, case, break, default: Used for switch statements.
o while, do, for, foreach: Used for loop control.
o continue, break: Used for loop control flow.
2. Function and Class Keywords:
o function: Used to define a function.
o class, extends, implements: Used to define classes and interfaces.
o new: Used to instantiate objects.
o return: Used to return values from functions.
o static: Used to declare static properties and methods in classes.
3. Variable Keywords:
o global: Used to access global variables inside functions.
o static: Used to declare static variables inside functions or methods.
o const: Used to declare constants.
4. Include/Require Keywords:
o include, include_once: Used to include and execute a file.
o require, require_once: Similar to include, but generates a fatal error if the file cannot be
included.
5. Namespace Keywords:
o namespace, use: Used to define and import namespaces.
6. Error Control Keywords:
o try, catch, finally: Used for exception handling.
o throw: Used to throw exceptions.
7. Other Keywords:
o echo, print: Used to output data.
o isset, empty: Used to check variable existence and emptiness.
o define: Used to define constants.
o abstract, final, public, protected, private: Used for visibility and inheritance control in
classes.
22
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Using these keywords correctly and understanding their functionalities is essential for writing clear and
efficient PHP code. Improper use or misunderstanding of keywords can lead to syntax errors or
unexpected behavior in your PHP applications.
Using Variables
Using variables in PHP is straightforward. Variables are used to store and manipulate data within a PHP
script. Here's how you can use variables in PHP:
1. Variable Declaration and Assignment: You can declare a variable in PHP using the $ symbol
followed by the variable name. You can then assign a value to the variable using the assignment
operator =.
Example:
$name = "John";
$age = 30;
3. Variable Interpolation: In double-quoted strings, you can directly include variables within the
string, and their values will be interpolated.
Example:
echo "My name is $name and I am $age years old.";
4. Concatenation: You can concatenate variables with strings or other variables using the
concatenation operator.
Example:
echo "My name is " . $name . " and I am " . $age . " years old.";
23
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example
$globalVar = "I'm a global variable.";
function myFunction()
{
$localVar = "I'm a local variable.";
echo $globalVar; // Accessing global variable inside function
}
myFunction();
echo $localVar; // This will cause an error because $localVar is not accessible outside the function.
6. Variable Types: PHP is loosely typed, meaning you don't need to declare the type of a variable
explicitly. PHP automatically converts the variable to the appropriate type depending on the
context.
Example
$num = 10; // Integer
$floatNum = 3.14; // Float
$str = "Hello"; // String
$bool = true; // Boolean
7. Dynamic Variables: You can use variable variables to create variable names dynamically.
Example:
$varName = "name";
$$varName = "John"; // Creates $name variable with value "John"
echo $name; // Outputs: John
These are some basic examples of how to use variables in PHP. Variables are fundamental to PHP
programming and are used extensively in writing dynamic and interactive web applications.
Constants in PHP
In PHP, constants are like variables but once defined, they cannot be changed or redefined during
the execution of the script. They are useful for defining values that remain constant throughout the
execution of a script.
Constants are defined using the define() function or the const keyword. Here's how you can define
constants:
24
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Once defined, constants can be accessed throughout the script without the need to prepend the $ symbol.
Example:
echo PI; // Outputs: 3.14
// Access constants
echo SITE_NAME; // Outputs: My Website
echo PI; // Outputs: 3.14
Constants are useful for storing configuration values, defining database credentials, or any other value
that should remain constant throughout the execution of a script.
Expressions in PHP
In PHP, an expression is a combination of values, variables, operators, and function calls that evaluates to
a single value. Expressions can be simple or complex, and they are used extensively in PHP code for
performing calculations, comparisons, and other operations.
2. String Concatenation: String concatenation involves joining two or more strings together using
the concatenation operator (.).
Example:
$greeting = "Hello, " . "World!"; // Evaluates to "Hello, World!"
4. Logical Expressions: Logical expressions involve logical operations such as AND (&&), OR (||),
and NOT (!).
Example:
$isTrue = true && false; // Evaluates to false
5. Conditional (Ternary) Expressions: Conditional expressions allow you to choose between two
values based on a condition.
26
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
$age = 20;
$isAdult = ($age >= 18) ? "Yes" : "No"; // Evaluates to "Yes"
6. Function Call Expressions: Function call expressions involve calling a function and passing
arguments to it.
Example:
$length = strlen("Hello"); // Evaluates to 5
These are some common examples of expressions in PHP. Expressions are fundamental to writing PHP
code, and they are used extensively for performing various tasks such as calculations, string manipulation,
and decision making.
27
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Operators in PHP
Some of the operators in PHP is
1. Arithmetic Operators: Arithmetic operators used to perform Arithmetic Operations.
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (returns the remainder of a division)
Example:
$num1 = 10;
$num2 = 5;
// Addition
$sum = $num1 + $num2; // $sum contains 15
// Subtraction
$difference = $num1 - $num2; // $difference contains 5
// Multiplication
$product = $num1 * $num2; // $product contains 50
// Division
$quotient = $num1 / $num2; // $quotient contains 2
// Modulus
$remainder = $num1 % $num2; // $remainder contains 0
28
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
$x = 10;
$y = 5;
// Addition assignment
$x += $y; // $x now contains 15
// Subtraction assignment
$x -= $y; // $x now contains 10
// Multiplication assignment
$x *= $y; // $x now contains 50
// Division assignment
$x /= $y; // $x now contains 10
// Modulus assignment
$x %= $y; // $x now contains 0
Example:
$a = 10;
$b = 5;
// Equal to
$result1 = ($a == $b); // $result1 contains false
// Not equal to
$result2 = ($a != $b); // $result2 contains true
// Greater than
$result3 = ($a > $b); // $result3 contains true
// Less than or equal to
$result4 = ($a <= $b); // $result4 contains false
29
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
// Logical AND
$result5 = ($p && $q); // $result5 contains false
// Logical OR
$result6 = ($p || $q); // $result6 contains true
// Logical NOT
$result7 = !$p; // $result7 contains false
7. Array Operators:
+ Union (combines arrays)
== Equality (returns true if arrays have the same key/value pairs)
=== Identity (returns true if arrays have the same key/value pairs in the same order and of the
same types)
In PHP, array operators are used to manipulate arrays. There are mainly two array operators: union (+) and
equality (==, ===).
1. Union Operator (+):
o The union operator (+) combines two arrays. It returns an array containing all the elements
from both arrays, with duplicate values removed. If there are duplicate keys, the elements
from the left-hand array will be used, and the elements from the right-hand array will be
ignored.
30
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("b" => "blueberry", "c" => "cherry");
$result = $array1 + $array2;
print_r($result);
Output:
Array
(
[a] => apple
[b] => banana
[c] => cherry
)
2. Equality Operators (==, ===):
The equality operators (==, ===) are used to compare arrays for equality.
The == operator checks if two arrays have the same key/value pairs, regardless of the order of
elements.
The === operator checks if two arrays have the same key/value pairs in the same order and of the
same types.
Example:
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("b" => "banana", "a" => "apple");
// Using == operator
if ($array1 == $array2)
{
echo "Arrays are equal";
} else
{
echo "Arrays are not equal";
}
// Using === operator
if ($array1 === $array2)
{
echo "Arrays are identical";
} else
31
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
{
echo "Arrays are not identical";
}
Output:
Arrays are equal
Arrays are not identical
8. Ternary Operator:
The ternary operator in PHP is a shorthand way of writing conditional statements. It allows you to express
a conditional expression in a single line. The syntax of the ternary operator is:
General Syntax is
(condition) ? value_if_true : value_if_false;
In this example:
If the condition $age >= 18 evaluates to true, the value "Yes" is assigned to the variable
$isAdult.
If the condition evaluates to false, the value "No" is assigned to the variable $isAdult.
9. Type Operators:
instanceof Checks if an object is an instance of a specific class
These examples illustrate how different operators are used in PHP to perform arithmetic
calculations, comparisons, logical operations, string concatenation, and more. Understanding and using
operators effectively is crucial for writing PHP code efficiently.
32
UNIT 1