Theory of PHP Programming (5th Sem) .
Theory of PHP Programming (5th Sem) .
IL
Sahil Kumar Prof.
Program BCA
UNIT ➖01
Introduction to PHP
IL
pages, the name was changed. Now, PHP stands for "PHP: Hypertext Preprocessor," which is
a recursive acronym.
PHP (Hypertext Preprocessor) has undergone significant evolution since its creation in 1995
by Rasmus Lerdorf. Here’s a summary of its key developments and how it compares to
interfaces with external systems:
➖
Evolution of PHP
1. PHP/FI (1995) ➖
H
Initial release by Rasmus Lerdorf.
Simple set of Common Gateway Interface (CGI) binaries written in C.
Provided basic functionality for web development, such as form handling and database
SA
interaction.
2. PHP 3 (1997) ➖
Complete rewrite by Andi Gutmans and Zeev Suraski.
Introduced a more robust and extensible platform.
Added support for a wider range of databases and protocols.
3. PHP 4 (2000) ➖
Introduction of the Zend Engine 1.0, improving performance and reliability.
Enhanced session handling and output buffering.
Improved support for object-oriented programming (OOP).
4. PHP 5 (2004) ➖
Zend Engine II introduced.
Significant improvements in OOP capabilities (private/public/protected, abstract classes,
interfaces).
Introduction of SimpleXML, a more robust extension for XML manipulation.
Improved MySQL support with MySQLi.
➖
2
5. PHP 5.3 (2009)
Added namespaces, late static binding, and lambda functions.
Introduction of the PDO (PHP Data Objects) extension for database access.
6. PHP 7 (2015) ➖
Major performance improvements (up to twice as fast as PHP 5.6).
Introduction of scalar type declarations and return type declarations.
Anonymous classes and improved error handling with throwable errors and exceptions.
7. PHP 8 (2020) ➖
Introduction of the Just-In-Time (JIT) compilation.
Union types, named arguments, attributes for metadata, and match expressions.
Enhancements to the type system and improvements in error handling.
IL
● Comparison to Interfaces with External Systems ➖
PHP’s evolution has significantly impacted how it interfaces with external systems:
1. Database Interfaces
H ➖
I. Early PHP (PHP/FI to PHP 4): Basic MySQL support with direct functions
(mysql_connect(), mysql_query()).
II. PHP 5: Introduction of MySQLi and PDO for a more flexible and secure database
interaction, supporting multiple databases (MySQL, PostgreSQL, SQLite, etc.).
III. PHP 7+: Continued improvements in database interfaces with better error handling,
SA
security, and performance.
IL
extensions.
III. PHP 7+: Improved FFI (Foreign Function Interface) allowing calling functions from C
libraries directly in PHP scripts.
PHP’s growth from a simple scripting tool to a robust, high-performance language is evident.
Its ability to interface with external systems has also evolved, offering greater flexibility,
security, and performance for modern web development needs.
➖
H
● Hardware and Software requirements
Recommended: ➖
I. Processor: Quad-core processor (e.g., Intel Core i5 or AMD equivalent)
II. RAM: 8 GB or more
III. Storage: 256 GB SSD
IV. Monitor: Full HD (1920x1080) resolution or higher
2. Software Requirements ➖
Operating System:
Windows 7/8/10/11, macOS, or Linux (Ubuntu, Fedora, etc.)
Web Server :
I. Apache HTTP Server
4
II. Nginx
PHP:
I. PHP 7.4 or later (PHP 8.x recommended)
Database:
I. MySQL
II. PostgreSQL
III. SQLite
IV. MariaDB
IL
II. PHPStorm
III. Sublime Text
IV. NetBeans
Version Control:
I. Git (GitHub, GitLab, Bitbucket)
H
Dependencies and Package Management:
I. Composer
Optional Tools:
I. XAMPP or WAMP (for a complete local server environment on Windows)
II. MAMP (for macOS)
SA
III. Docker (for containerized development environments)
IV. Additional Libraries and Extensions
These requirements ensure a smooth PHP development experience, enabling you to work
efficiently on both small and large projects.
● PHP Scripting ➖
PHP (Hypertext Preprocessor) is a scripting language that's used for web development. It's
executed on the server and then translated into HTML code for the client-side, which is then
outputted by the web browser. PHP is open-source, free to download and use, and is available
on all major operating systems and web servers.
IL
Structure
A PHP script is made up of a series of statements, which can be assignments, function calls,
loops, conditional statements, or empty statements. Statements usually end with a semicolon.
File structure
A PHP file is made up of HTML code, CSS code, JavaScript code, and PHP code. The file
H
extension for PHP is ".php".
** PHP scripting involves writing code that is executed on the server to create dynamic web
pages. PHP (Hypertext Preprocessor) is embedded within HTML, making it a powerful tool for
building interactive and data-driven websites. Here's a brief guide to get you started with PHP
scripting:**
➖
SA
Basic PHP Script
1. PHP Tags:
➖
PHP code is enclosed within <?php ... ?> tags.
Ex
<?php
echo "Hello, World!";
?>
2. Variables: :-\
➖
Variables in PHP start with a $ sign.
Ex
<?php
$greeting = "Hello, World!";
echo $greeting;
?>
➖
6
3. Data Types:
PHP supports various data types, including strings, integers, floats, arrays, objects, and
➖
booleans.
Ex
<?php
$string = "Hello, World!";
$int = 10;
$float = 10.5;
$bool = true;
$array = array("one", "two", "three");
?>
IL
Basic PHP development involves understanding the core concepts of the language, how to set
up a development environment, and how to write simple scripts. Here's a guide to get you
started with basic PHP development.
2. Verify Installation:
SA
I. Once installed, ensure your server is running. Open your web browser and navigate to
http://localhost. You should see a welcome page indicating that your server is running.
<?php
echo "Hello, World!";
?>
Run the Script:
Open your web browser and navigate to http://localhost/index.php. You should see "Hello,
World!" displayed on the page.
7
PHP Basics
1. PHP Syntax:
Ex:->
<?php
// This is a single-line comment
/*
This is a multi-line comment
*/
// Output text
echo "Hello, World!";
IL
?>
➖
2. Variables:
Ex
<?php
$name = "John";
$age = 25;
➖
➖
3. Data Types:
Ex
SA
<?php
$string = "Hello, World!";
$integer = 42;
$float = 3.14;
$boolean = true;
$array = array("Apple", "Banana", "Cherry");
$null = null;
echo $string;
?>
➖
➖
4. Conditional Statements:
Ex
<?php
$age = 18;
➖
➖
5. Loops:
Ex
<?php
// For loop
for ($i = 0; $i < 5; $i++) {
echo "The number is: $i <br>";
}
// While loop
IL
$i = 0;
while ($i < 5) {
echo "The number is: $i <br>";
$i++;
}
}
echo $fruit . "<br>";
?>
➖
➖
SA
6. Functions:
Ex
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("John");
?>
➖
➖
7. Form Handling:
Ex
<!-- HTML Form -->
<form method="post" action="index.php">
Name: <input type="text" name="name">
<input type="submit">
</form>
<?php
9
// PHP Script to handle form data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Hello, " . $name;
}
?>
Connecting to a Database
1. Create a MySQL Database and Table:
Sql
IL
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
➖
➖
2. PHP Script to Connect and Query the Database:
Ex
<?php
H
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
SA
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform a query
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
10
echo "0 results";
}
$conn->close();
?>
2. Error Reporting:
➖
I. Enable error reporting during development to help identify and fix issues.
IL
Ex
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
3. Sanitise Input: ➖
H
I. Always sanitise and validate user input to prevent security vulnerabilities like SQL
injection and XSS.
➖
SA
5. Explore Frameworks:
I. Once comfortable with basic PHP, consider using frameworks like Laravel or Symfony to
streamline development and follow best practices.
This guide covers the essentials to get you started with basic PHP development. As you
become more experienced, you can delve into advanced topics and tools to enhance your
PHP skills.
1. Client Request:➖
I. A user makes a request to a web server by entering a URL in their web browser, clicking
a link, or submitting a form.
II. This request is sent to the server, typically as an HTTP GET or POST request.
➖
11
2. Server Receives Request:
I. The web server (e.g., Apache or Nginx) receives the request and determines that the
requested file is a PHP script based on the file extension (.php).
3. PHP Interpreter: ➖
I. The server hands over the PHP file to the PHP interpreter.
II. The PHP interpreter processes the script, executing the PHP code line by line.
4. Script Execution: ➖
I. During execution, PHP can perform various operations such as database queries, file
manipulations, and conditional logic.
II. PHP code is used to generate HTML, interact with databases, handle form data, and
perform other server-side operations.
IL
5. Output Generation: ➖
I. The PHP script generates output, typically in the form of HTML, which is sent back to the
web server.
II. The web server then sends this HTML content as the response to the client's request.
III. Integration with HTML: PHP scripts often include HTML code, and PHP can be
embedded within HTML using <?php ?> tags.
IV. Error Handling: PHP scripts should include error handling to manage database
connection issues, query failures, and other potential errors.
V. Security: Always sanitise and validate user input to prevent security vulnerabilities like
SQL injection and cross-site scripting (XSS).
This overview explains the basic working of PHP scripts, highlighting the interaction between
the client, server, PHP interpreter, and the resulting dynamic content generation.
2. PHP commands
A basic PHP command includes a function, an action, and a semicolon to indicate the end of
the command. When building functions, you can use parentheses and parameters.
3. Comments
PHP has three types of comment syntax:
I. Block comments: Use /* */
II. Inline comments: Use // or #
IL
Shorthand version
To print something, you can use a shorthand version that's similar to php echo and then
whatever you want to echo. You can omit the semicolon because it's a one-liner.
Processing PHP
To process PHP, you need to enclose your PHP code block within the PHP opening and
closing tags. For example, you can assign a variable and then echo it out.
➖
SA
Here are the primary data types in PHP:
1. Scalar Types ➖
a. Integer:
Whole numbers without a decimal point.
Example:
<?php
$integer = 42;
echo $integer; // Output: 42
?>
b. Float (Double):
Numbers with a decimal point or in exponential form.
Example:
<?php
$float = 3.14;
echo $float; // Output: 3.14
13
?>
c. String:
A sequence of characters, enclosed in single quotes (') or double quotes (").
Example:
<?php
$string = "Hello, World!";
echo $string; // Output: Hello, World!
?>
d. Boolean:
Represents two possible values: true or false.
Example:
<?php
IL
$boolean = true;
echo $boolean; // Output: 1 (true is displayed as 1)
?>
2. Compound Types ➖
a. Array:
Example:
<?php
// Indexed array
H
A collection of values, which can be indexed numerically or associatively.
b. Object:
An instance of a class, which can contain properties and methods.
Example:
<?php
class Person {
public $name;
public $age;
3. Special Types ➖
a. NULL:
Represents a variable with no value.
IL
Example:
<?php
$nullVar = null;
echo $nullVar; // Output: (empty output)
?>
b. Resource:
Example:
<?php
H
A special variable, holding a reference to an external resource (e.g., a database connection).
➖
context.
Ex
<?php
$var = "10";
$sum = $var + 20; // $var is converted to an integer
echo $sum; // Output: 30
?>
➖
Type Casting: Manually converting a variable from one type to another.
Ex
<?php
$var = "10";
$intVar = (int) $var; // Casting string to integer
15
echo $intVar; // Output: 10
?>
IL
Ex ➖
<?php
$var = 42;
if (is_int($var)) {
echo "Variable is an integer.";
}
?>
H
These data types form the basis of variable handling and manipulation in PHP, and
understanding them is crucial for effective programming in PHP.
➖
SA
● Displaying type information:
➖
➖
Testing for a specific data type
PHP has a number of functions to test for a specific data type in a variable:
I. gettype(): Returns the type of a variable as a string, such as boolean, integer, double,
string, array, object, resource, NULL, or unknown type. For example, `$type =
gettype($variable); echo $type;` will output integer if $variable is 10.
II. is_type(): A group of functions that return true if a variable is of a specific type. For
example, is_bool($value) returns true if $value is a boolean value.
III. var_dump(): Dumps information about a variable, including its type and value. For
example, var_dump($variable); will output string(5) "Hello" if $variable is "Hello".
The function returns true on success and false on failure. For example, the following code will
change the type of $foo from a string to an integer and the type of $bar from a boolean to a
➖
string !
Ex
<?php
$var = "10";
IL
$intVar = (int) $var;
echo $intVar; // Output: 10
?>
● Operators ➖
In PHP, operators are special characters or combinations of characters that perform operations
1. Arithmetic Operators
H
on variables and values. They are categorized into several types:
Arithmetic operators are used to perform common arithmetic operations such as addition,
subtraction, multiplication, etc.
SA
I. + (Addition): Adds two values.
II. - (Subtraction): Subtracts one value from another.
III. * (Multiplication): Multiplies two values.
IV. / (Division): Divides one value by another.
V. % (Modulus): Returns the remainder of a division.
VI. ** (Exponentiation): Raises a number to the power of another.
2. Assignment Operators
Assignment operators are used to write values to variables.
IL
4. Increment/Decrement Operators
These operators are used to increment or decrement a variable's value.
5. Logical Operators
H
Logical operators are used to combine conditional statements.
6. String Operators
String operators are used to manipulate strings.
7. Array Operators
Array operators are used to compare arrays.
8. Type Operators
Type operators are used to work with types.
9. Bitwise Operators
Bitwise operators are used to perform bit-level operations.
IL
IV. ~: NOT (inverts all the bits).
V. <<: Left shift (shifts bits to the left).
VI. >>: Right shift (shifts bits to the right).
➖
SA
● Variable manipulation
The definition of a manipulated variable is a factor that is purposefully and specifically changed
by the experimenter. The manipulated variable is also called the independent variable or test
variable. Variables are manipulated, or altered on purpose, to identify cause and effect
☹️
relationships.
Like - increment, decrement data , string declaring and initialising and etc .
In this example:
I. $varName is a variable that holds the string 'hello'.
II. $$varName uses the value of $varName as the name of a new variable. This creates a
new variable named $hello with the value 'world'.
Variable Scope ➖
Variable scope refers to the context within which a variable is defined and accessible.
IL
PHP has several types of variable scopes:
1. Local Scope
2. Global Scope
3. Static Scope
4. Function Parameters
1. Local Scope
function.
Ex
<?php
H
Variables declared within a function have a local scope and are only accessible within that
➖
function test() {
$localVar = "I'm local";
SA
echo $localVar; // Outputs: I'm local
}
test();
echo $localVar; // Error: Undefined variable
?>
2. Global Scope
Variables declared outside of any function have a global scope and are accessible from any
➖
part of the script, except inside functions unless explicitly specified.
Ex
<?php
$globalVar = "I'm global";
function test() {
global $globalVar;
echo $globalVar; // Outputs: I'm global
}
test();
?>
20
The global keyword allows you to access a global variable inside a function.
➖
Alternatively, you can use the $GLOBALS array:
Ex
<?php
$globalVar = "I'm global";
function test() {
echo $GLOBALS['globalVar']; // Outputs: I'm global
}
test();
?>
IL
3. Static Scope
Static variables maintain their values between function calls. They are initialized only once and
➖
retain their values across multiple calls to the function.
Ex
<?php
function test() {
static $count = 0;
}
$count++;
echo $count;
H
test(); // Outputs: 1
test(); // Outputs: 2
SA
test(); // Outputs: 3
?>
4. Function Parameters
Function parameters are local to the function and are initialized with the arguments passed to
➖
the function.
Ex
<?php
function greet($name) {
echo "Hello, $name!";
}
Summary
I. Dynamic Variables: Allow the creation of variable names dynamically during execution
using variable variables ($$ syntax).
21
II. Variable Scope: Defines where a variable can be accessed in a program.
V. Static Scope: Variables that retain their value across function calls.
VI. Function Parameters: Variables passed to a function and local to that function.
VII. Understanding variable scope is crucial for managing data and state within your PHP
programs effectively.
IL
H
SA
22
UNIT ➖ 02
Control Statements ➖
● if() and elseif() condition Statement, The switch statement, Using the?
➖
Operator, Using the while() Loop, The do while statement, Using the for()
Loop
Control statements allow you to direct the flow of execution in a PHP script based on
conditions or repetitive tasks.
IL
Here are some key control statements:
➖
statement allows you to check multiple conditions.
Ex
<?php
$age = 20;
➖
values.
Ex
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week!";
break;
case "Friday":
echo "End of the work week!";
23
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "It's a regular day.";
}
?>
➖
condition.
IL
Ex
<?php
$isAdult = ($age >= 18) ? "Yes" : "No";
echo $isAdult; // Outputs: Yes if $age >= 18, otherwise No
?>
➖
before checking the condition.
Ex
<?php
$i = 0;
do {
echo $i;
$i++;
} while ($i < 5);
?>
➖
24
6. Using the for Loop
The for loop is used when you know in advance how many times you want to execute a
➖
statement or a block of statements.
Ex
<?php
for ($i = 0; $i < 5; $i++) {
echo $i;
}
?>
Summary ➖
I. if and elseif Statements: Used to execute code based on one or more conditions.
IL
II. switch Statement: Used to perform different actions based on different conditions for a
single variable.
IV. while Loop: Executes a block of code as long as the condition is true.
H
V. do while Loop: Similar to while loop but guarantees execution of the code block at least
once.
These control statements are essential for directing the flow of execution and handling
SA
repetitive tasks in PHP programs.
Functions ➖
● Function definition, Creation, Returning values, Library Functions, User Defined
➖
functions, Dynamic function, default arguments, Passing
arguments to a function by value
Functions are reusable blocks of code designed to perform a specific task. They help organise
code, avoid redundancy, and improve readability.
➖
Syntax:
Ex
25
<?php
function functionName($parameter1, $parameter2) {
// Code to be executed
}
?>
Example:
php
Copy code
<?php
function greet($name) {
echo "Hello, $name!";
}
IL
greet("Alice"); // Outputs: Hello, Alice!
?>
2. Returning Values ➖
Functions can return values using the return statement.
Example: ➖
<?php
function add($a, $b) {
}
return $a + $b;
H
$result = add(5, 3); // $result is 8
SA
echo $result; // Outputs: 8
?>
3. Library Functions ➖
PHP comes with many built-in library functions that perform various tasks, such as string
manipulation, mathematical calculations, and array operations.
4. User-defined Functions ➖
User-defined functions are those that developers create to perform specific tasks not covered
by PHP's built-in functions.
➖
26
Example:
<?php
function multiply($a, $b) {
return $a * $b;
}
IL
Example:
<?php
function sayHello() {
echo "Hello, World!";
}
$functionName = 'sayHello';
?>
6. Default Arguments
H
$functionName(); // Outputs: Hello, World!
➖
Functions can have parameters with default values, which are used if no argument is passed.
➖
SA
Example:
<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}
Example: ➖
<?php
function increment($value) {
$value++;
echo $value; // Outputs: 6
27
}
$number = 5;
increment($number);
echo $number; // Outputs: 5
?>
Summary ➖
I. Function Definition and Creation: Functions are defined using the function keyword and
can have parameters.
II. Returning Values: Functions can return values using the return statement.
IL
III. Library Functions: PHP provides built-in functions for common tasks.
IV. User-defined Functions: Developers can create custom functions for specific tasks.
V. Dynamic Function Calls: Functions can be called dynamically using variable functions.
VI. Default Arguments: Functions can have parameters with default values.
VII.
H
Passing Arguments by Value: By default, arguments are passed by value, meaning the
function gets a copy of the variable.
VIII. Functions are essential for structuring and organising code, making it more maintainable
and reusable.
SA
String Manipulation ➖
➖
● Formatting String for Presentation, Formatting String for Storage, Joining
and Splitting String, Comparing String
String manipulation in PHP involves various operations such as formatting strings for
presentation, storage, joining and splitting strings, and comparing strings.
IL
When formatting strings for storage, you might consider escaping special characters or
ensuring a specific encoding. Functions like addslashes() or database-specific functions can
be used for these purposes.
Example: ➖
<?php
$string = "It's a PHP example.";
H
// Escaping single quotes for storage
$escapedString = addslashes($string);
echo $escapedString; // Outputs: It\'s a PHP example.
?>
➖
SA
3. Joining and Splitting String
a. Joining (Concatenation): ➖
You can concatenate strings using the . operator or implode() function for arrays.
Example: ➖
<?php
$firstName = "John";
$lastName = "Doe";
// Using concatenation
$fullName = $firstName . " " . $lastName;
echo $fullName; // Outputs: John Doe
Example: ➖
<?php
$string = "apple,banana,orange";
$fruits = explode(",", $string);
print_r($fruits); // Outputs: Array ( [0] => apple [1] => banana [2] => orange )
?>
4. Comparing Strings ➖
PHP provides several functions for comparing strings, such as strcmp(), strcasecmp(), and
operators like ==, ===, !=, etc.
IL
Example: ➖
<?php
$string1 = "apple";
$string2 = "banana";
if ($result < 0) {
H
$result = strcmp($string1, $string2);
Summary ➖
I. Formatting String for Presentation: Use interpolation or printf() for formatted output.
II. Formatting String for Storage: Use functions like addslashes() for escaping characters.
III. Joining and Splitting String: Use concatenation (.) or implode() for joining, and explode()
for splitting.
30
IV. Comparing Strings: Use functions like strcmp(), strcasecmp(), or operators (==, ===,
etc.) for comparison.
Understanding these operations allows you to effectively manipulate strings in PHP according
to different requirements, whether for presentation, storage, or comparison.
Array ➖
➖
● Anatomy of an Array, Creating index based and Associative array,
Looping array using each() and foreach() loop
IL
Arrays in PHP are versatile data structures that can store multiple values under a single
variable name. They can be indexed numerically (index-based arrays) or by strings
(associative arrays).
1. Anatomy of an Array ➖
An array in PHP can contain a collection of elements. Each element can be accessed using its
index (numeric or string).
Example:
<?php
➖
// Numeric array
H
$numericArray = array(10, 20, 30, 40, 50);
SA
// Associative array
$associativeArray = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
?>
➖
3. Associative Array:
Ex
<?php
$associativeArray = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
?>
In this example, $associativeArray is an associative array with keys "name", "age", and "city".
IL
a. Using foreach Loop:
The foreach loop is used to iterate over each element in an array.
➖
SA
Example with Associative Array:
<?php
$associativeArray = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
Summary ➖
I. Anatomy of an Array: Arrays can store multiple elements accessed by index or key.
IL
III. Index-based Arrays: Numerically indexed arrays store values accessed by numeric
indices.
01.
02.
H
foreach Loop: Iterates over each element in an array.
Understanding these concepts allows you to effectively work with arrays in PHP, iterating
SA
through elements and accessing values based on keys or indices.
33
UNIT ➖ 03
Forms ➖
● Working with Forms, Super global variables, Super global array,
Importing user input, Accessing user input, Combine HTML and PHP
code, Using hidden fields, Redirecting the user.
It looks like you're interested in learning more about forms and how to work with them in PHP.
Here's a brief overview of each topic:
IL
1. Working with Forms: Forms in HTML allow users to input data which can be submitted
to a server for processing. They use attributes like action (where the form data is sent)
and method (how it's sent: GET or POST).
2. Super Global Variables: In PHP, $_GET and $_POST are super global arrays used to
collect form data sent with GET and POST methods, respectively. $_REQUEST
combines both.
H
3. Importing User Input: PHP scripts use super global arrays ($_GET, $_POST,
$_REQUEST) to import form data based on the method specified in the form.
4. Accessing User Input: After form submission, PHP accesses user input through keys
SA
corresponding to form field names in $_GET or $_POST.
5. Combine HTML and PHP Code: PHP code can be embedded within HTML using
<?php ... ?> tags to dynamically generate content or process form data.
6. Using Hidden Fields: <input type="hidden"> fields store data that is not displayed to
users but can be submitted with the form.
7. Redirecting the User: After processing form data, PHP can redirect users to another
page using header("Location: newpage.php"); or JavaScript (window.location).
If you have specific questions or need examples on any of these topics, feel free to ask!
➖
34
Working with File and Directories
➖
Downloading. Generating Images with PHP: Basics computer Graphics,
Creating Image
Working with files and directories in PHP involves several essential tasks. Here's an overview
of each topic you mentioned:
IL
images, scripts, etc.
II. Directories: Also known as folders, directories are containers used to organize files
hierarchically on a file system.
II. Use fclose() to close an opened file handle after you've finished working with it.
II. rename() is used to change the name of a file or move it to a different location.
III. opendir() and closedir() are used to open and close a directory handle for reading its
contents.
II. PHP handles uploaded files via $_FILES super global array.
IL
II. Functions like imagecreate(), imagecolorallocate(), imagestring(), etc., create and
manipulate images programmatically.
7. Creating Images: ➖
I. Use PHP GD functions (imagecreate(), imagecopy(), etc.) to generate images
dynamically.
II.
H
Common tasks include creating thumbnails, adding watermarks, or generating charts.
If you have specific questions about any of these topics or need examples, feel free to ask!
SA
36
UNIT ➖ 04
Database Connectivity with MySql ➖
➖
● Introduction to RDBMS, Connection with MySql Database, Performing
basic database operation (DML) (Insert, Delete, Update, Select)
Certainly! Here's an overview of database connectivity with MySQL in PHP, covering RDBMS
concepts and basic operations (DML):
IL
1. Introduction to RDBMS
Relational Database Management Systems (RDBMS) organize data into structured tables
(relations) with rows (tuples) and columns (attributes). They ensure data integrity through
relationships defined by keys (primary, foreign).
a. Using mysqli:
Program Ex ➖
$servername = "localhost";
SA
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
➖
➖
b. Using PDO:
Ex
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
37
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $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();
}
➖
➖
a. Inserting Data
IL
Ex
$sql = "INSERT INTO table_name (column1, column2, column3)
VALUES ('value1', 'value2', 'value3')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Ex➖
b. Updating Data
H
➖
$sql = "UPDATE table_name SET column1='new_value' WHERE condition";
if ($conn->query($sql) === TRUE) {
SA
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
➖
➖
c. Deleting Data :
Ex
$sql = "DELETE FROM table_name WHERE condition";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
➖
➖
d. Selecting Data
Ex
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
38
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
These examples cover the basics of connecting to a MySQL database from PHP and
performing basic DML operations (Insert, Delete, Update, Select). Replace username,
password, database_name, table_name, column1, etc., with your actual database credentials
and schema details.
IL
🙂😀
HAPPY ENDING BY : SAHIL RAUNIYAR /
PTU-CODER
H
SA
39
Note:
Attempt Five questions in all, by choosing any One question each from Units I-IV. Unit V is
compulsory
UNIT-I
IL
I (a) State the differences between static website and dynamic website development. (6)
(b) Discuss the various looping statements used in PHP with suitable example. (7)
UNIT-II
H
III How do you define a function in PHP? What is difference between formal and actual
arguments? What happens when there is argument mismatch during function call? Create
a PHP program which finds the factorial of number recursively using functions.
SA
(13)
IV (a) Write a PHP program to find the number of characters in the string. (6)
(b) Discuss the functions for Inspecting arrays. (7)
UNIT-III
V (a) Discuss the two methods used in HTTP to handle form data. (5)
(b) Write a PHP code to connect to database. (5)
(c) Write a note on super global arrays. (3)
VI How do you create a query in PHP? How do you fetch the dataset? Discuss the four
fetching functions in detail.
(13)
UNIT-IV
VII What are cookies? Why are they used? How do you create, read and delete a cookie? (13)
40
UNIT-V
(c) What are the various ways to represent multi line and single line comments in PHP? (2)
IL
(d) What is static variable? (2)
(e) How PHP supports editing of data with HTML form? (2)
● Static Website:
○ Content remains fixed unless manually updated.
○ Written in HTML/CSS.
○ Limited interactivity and functionality.
○ Faster to develop and host.
● Dynamic Website:
○ Content is generated on-the-fly based on user interactions and
database queries.
○ Written in languages like PHP, Python, etc.
○ Interactive elements, user authentication, content management
systems (CMS), etc.
○ Requires server-side processing and often a database.
I (b) Looping statements used in PHP with examples (7)
41
PHP supports several looping constructs:
● for loop:
php
Copy code
for ($i = 0; $i < 5; $i++) {
echo $i . "<br>";
}
● while loop:
IL
php
Copy code
$i = 0;
while ($i < 5) {
echo $i . "<br>";
$i++;
}
H
● do-while loop:
SA
php
Copy code
$i = 0;
do {
echo $i . "<br>";
$i++;
} while ($i < 5);
php
Copy code
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color . "<br>";
42
}
UNIT-II
III How to define a function in PHP? Difference between formal and actual arguments? What happens
during argument mismatch?
● Defining a function:
php
Copy code
function calculateFactorial($n) {
IL
if ($n <= 1) {
return 1;
} else {
return $n * calculateFactorial($n - 1);
}
}
H
● Formal vs. Actual Arguments:
○ Formal arguments: Parameters declared in the function definition
($n in the example).
SA
○ Actual arguments: Values passed to the function during its
invocation (5 in calculateFactorial(5)).
● Argument Mismatch: PHP throws a warning or error depending on the
severity of the mismatch (e.g., too few arguments).
IV (a) PHP program to find the number of characters in a string (6)
php
Copy code
$string = "Hello, World!";
$length = strlen($string);
echo "Number of characters: " . $length;
UNIT-III
● GET: Sends form data in the URL query string ($_GET in PHP).
● POST: Sends form data in the body of the HTTP request ($_POST in
PHP).
IL
V (b) PHP code to connect to a database (5)
php
Copy code
$username = "username";
$password = "password";
H
$servername = "localhost";
$dbname = "database_name";
SA
$conn = new mysqli($servername, $username, $password,
$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
php
Copy code
$sql = "SELECT * FROM users WHERE id = 1";
$result = $conn->query($sql);
● Fetching Dataset:
php
Copy code
IL
// Using mysqli
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"];
}
// Using PDO
H
foreach ($result as $row) {
echo "Name: " . $row["name"];
}
SA
● Fetching Functions:
○ fetch_assoc(): Returns an associative array.
○ fetch_array(): Returns an array with both numeric and
associative indices.
○ fetch_object(): Returns the next row as an object.
○ fetch_row(): Returns a numeric array of the current row.
UNIT-IV
VII What are cookies? Why are they used? How to create, read, and delete a cookie? (13)
● Cookies: Small pieces of data stored on the client's computer by the web
server.
● Usage: Used to track user sessions, store user preferences, etc.
● Creating a Cookie:
php
Copy code
45
setcookie("username", "John Doe", time() + 3600, "/");
● Reading a Cookie:
php
Copy code
echo $_COOKIE["username"];
● Deleting a Cookie:
php
IL
Copy code
setcookie("username", "", time() - 3600, "/");
File permissions in PHP determine who can read, write, or execute a file.
H
They are managed by the file system and can be set using functions like
chmod().
VIII (b) Opening and closing files in PHP, various file opening modes (7)
● Opening a File:
SA
php
Copy code
$file = fopen("file.txt", "r") or die("Unable to open
file!");
● Closing a File:
php
Copy code
fclose($file);
UNIT-V
IL
php
Copy code
<?php include 'header.php'; ?>
php
Copy code
SA
/*
This is a
multi-line comment
*/
PHP processes form data using $_GET or $_POST super global arrays.
IX (f) Increasing session expire time (2)
These answers cover a broad range of PHP topics based on your structured
questions. If you need further clarification or more examples on any specific
topic, feel free to ask!
IL
H
SA
48
● Write a PHP script to insert records in the student table within the
course database having fields-student-id, student name, student age
through Form and display records in table format.
Sure, I'll provide you with a PHP script to insert records into a student table in
the course database using a form and then display the records in a table format.
First, ensure you have the course database and student table set up. Here is
IL
the SQL statement to create the student table:
sql
USE course;
H
CREATE TABLE student (
student_id INT AUTO_INCREMENT PRIMARY KEY,
SA
student_name VARCHAR(255) NOT NULL,
student_age INT NOT NULL
);
php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "course";
// Create connection
49
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
IL
$student_name = $_POST['student_name'];
$student_age = $_POST['student_age'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Insert Student Records</title>
50
</head>
<body>
IL
<input type="number" id="student_age" name="student_age"
required><br><br>
<input type="submit" value="Submit">
</form>
<h2>Student Records</h2>
<table border="1">
<tr>
H
<th>Student ID</th>
<th>Student Name</th>
SA
<th>Student Age</th>
</tr>
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row["student_id"] . "</td>
<td>" . $row["student_name"] . "</td>
<td>" . $row["student_age"] . "</td>
</tr>";
}
} else {
echo "<tr><td colspan='3'>No records
found</td></tr>";
51
}
$conn->close();
?>
</table>
</body>
</html>
Explanation:
IL
1. Database Connection: The script connects to the MySQL database using
the mysqli extension.
2. Form Submission Handling: When the form is submitted, the script checks
the request method and inserts the submitted data into the student table.
3. Retrieve and Display Records: After inserting data, the script retrieves all
records from the student table and displays them in an HTML table.
H
4. HTML Form: A simple HTML form is provided to input student_name and
student_age.
Usage:
1. Create the course database and student table using the provided SQL
SA
statements.
2. Save the PHP script in a file, e.g., student_form.php.
3. Run the script on a server with PHP and MySQL support.
4. Access the script via a web browser to insert and display student records.
IL
To connect PHP to a database and retrieve data, we typically use a relational
database like MySQL. PHP provides several extensions to interact with
databases, such as mysqli and PDO.
First, create a database and a table. For example, let's create a database called
school and a table called students.
SA
sql
USE school;
sql
IL
3. PHP Script to Connect and Retrieve Data
php
Copy code
<?php
H
$servername = "localhost";
$dbname = "school";
// Create connection
// Check connection
if ($conn->connect_error) {
// Retrieve data
$result = $conn->query($sql);
?>
IL
<!DOCTYPE html>
<html>
<head>
H
<title>Student Records</title>
</head>
SA
<body>
<h2>Student Records</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<?php
55
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
</tr>";
IL
}
} else {
}
H
$conn->close();
?>
SA
</table>
</body>
</html>
Explanation:
1. Database Connection:
○ The PHP script connects to the MySQL database using the mysqli
extension.
○ Replace username and password with your MySQL credentials.
2. SQL Query Execution:
56
○ The script executes an SQL query to select all records from the
students table.
3. Data Retrieval:
○ The while loop fetches each row from the result set and displays it in
an HTML table.
4. HTML Output:
○ The data is displayed in an HTML table format on a web page.
Summary
IL
SQL queries to retrieve data, and displaying that data in a readable format. The
mysqli extension in PHP provides a straightforward way to interact with MySQL
databases.
● What are cookies? How can you create, access and delete a cookies in
H
PHP with the help of an example ? Also differentiate between a session
and Cookie.
Cookies are small pieces of data stored on the user's computer by the web
browser while browsing a website. They are used to remember information about
the user, such as login details, preferences, and other data that can be retrieved
SA
later during subsequent visits to the same site.
1. Creating a Cookie
To create a cookie in PHP, you use the setcookie() function. The basic syntax
is:
php
IL
php
<?php
?>
H
2. Accessing a Cookie
SA
Cookies can be accessed using the $_COOKIE superglobal array.
php
<?php
if (isset($_COOKIE["user"])) {
} else {
?>
58
3. Deleting a Cookie
php
<?php
IL
setcookie("user", "", time() - 3600, "/");
?>
H
Example: Full Cookie Handling Script
php
<?php
// Create a cookie
SA
setcookie("user", "John Doe", time() + 3600, "/");
if (isset($_COOKIE["user"])) {
} else {
}
59
// Delete the cookie
?>
IL
Storage Stored on the client-side Stored on the server-side,
Location (user's browser). with a session ID stored
on the client-side.
Lifetime Can persist for a long time, Typically last until the
SA
depending on the expiration browser is closed, unless
time set. explicitly configured to last
longer.
php
IL
<?php
?>
H
Accessing Session Data:
php
SA
Copy code
<?php
if (isset($_SESSION["user"])) {
} else {
?>
61
php
Copy code
<?php
IL
session_destroy(); // Destroy the session
?>
In summary, cookies and sessions are both used to store user information, but
H
they differ in their storage location, security, lifetime, data capacity, and use cases.
Cookies are stored on the client-side and can persist for long periods, while
sessions are stored on the server-side and typically last for the duration of the
user's visit.
SA
● Write a PHP script to open, close, read and write data into a file. Also
describe various file permissions.
PHP Script to Open, Close, Read, and Write Data into a File
Here is a PHP script demonstrating how to open, close, read, and write data into a
file:
php
<?php
$file = 'example.txt';
fwrite($handle, $data);
IL
// Close the file
fclose($handle);
echo $line;
fclose($handle);
?>
63
Explanation:
1. Opening a File:
○ fopen($file, 'w'): Opens the file for writing. If the file does not
exist, it creates it. If it exists, it truncates (empties) the file.
○ fopen($file, 'r'): Opens the file for reading. The file must exist.
2. Writing to a File:
○ fwrite($handle, $data): Writes the specified data to the file.
3. Reading from a File:
○ fgets($handle): Reads a line from the file. It reads until it reaches a
IL
newline character or the end of the file.
4. Closing a File:
○ fclose($handle): Closes the opened file.
File permissions define who can read, write, or execute a file. They are usually
H
represented as octal values.
w 2 Write
permission
x 1 Execute
permission
Permissions are set for the file owner, the group, and others.
● rwxr-xr-- (Symbolic)
● 0754 (Octal)
64
This example means:
php
<?php
IL
$file = 'example.txt';
chmod($file, 0755);
?>
H
SA
Summary
php
<?php
$file = 'example.txt';
65
IL
fwrite($handle, $data);
fclose($handle);
H
// Set file permissions to read, write, and execute for the
owner, and read and execute for others
SA
chmod($file, 0755);
echo $line;
66
}
fclose($handle);
?>
This script covers the essential file operations and demonstrates how to manage
file permissions in PHP.
IL
● Write short answers of the following ➖
I. What is the use of === operator?
II. Explain the difference between $message and $$message.
III. What is the purpose of the super global variable called $_SERVER?
IV. What is the difference between include and require?
H
V. How a page is redirected in PHP?
VI. Name and explain the function used to delete a file from the system.
VII. How can the execution of a PHP script be stopped?
SA
What is the use of === operator?
The === operator in PHP is a strict comparison operator. It checks both the value
and the type of the variables being compared. This means that the comparison
will only return true if the values and types are identical.
php
<?php
$a = 42; // integer
$b = "42"; // string
php
<?php
$message = "greeting";
IL
$$message = "Hello, World!";
?>
H
What is the purpose of the super global variable called $_SERVER?
<?php
?>
● include and require are both used to include and evaluate a specified
file.
● If the file is not found, include generates a warning but the script continues
execution.
68
● If the file is not found, require generates a fatal error and stops the script
execution.
php
<?php
IL
?>
How is a page redirected in PHP?
A page can be redirected in PHP using the header() function. The Location
header is used to specify the URL to redirect to.
php
<?php
H
header("Location: http://www.example.com");
SA
exit(); // Ensure no further code is executed after
redirection
?>
Name and explain the function used to delete a file from the system.
php
<?php
$file = 'example.txt';
if (file_exists($file)) {
} else {
?>
How can the execution of a PHP script be stopped?
The execution of a PHP script can be stopped using the exit() or die()
IL
functions. Both functions output a message and terminate the script.
php
<?php
● How are functions created and invoked in PHP? Write a PHP functions that finds
the sum of N even numbers.
● How is recursion used in PHP? Explain with suitable example.
In PHP, functions are created using the function keyword followed by the function name, a
pair of parentheses (), and a block of code enclosed in curly braces {}. Functions are
invoked by calling their name followed by parentheses, optionally passing arguments.
IL
Syntax for Creating a Function
php
<?php
function functionName() {
// Code to be executed
}
?>
H
Syntax for Invoking a Function
php
<?php
SA
functionName(); // Call the function
?>
Here's a PHP function that calculates the sum of the first N even numbers:
php
<?php
function sumEvenNumbers($n) {
$sum = 0;
for ($i = 1; $i <= $n; $i++) {
$sum += $i * 2;
}
return $sum;
}
71
// Example usage
$n = 5;
echo "The sum of the first $n even numbers is: " .
sumEvenNumbers($n);
?>
Recursion is a programming technique where a function calls itself to solve smaller instances
of the same problem. In PHP, recursion is used similarly to other programming languages.
IL
The factorial of a number n is the product of all positive integers less than or equal to n. It is
denoted as n!. The factorial of n can be defined recursively as:
I. 0! = 1
II. n! = n * (n-1)! for n > 0
php
<?php
function factorial($n) {
H
if ($n === 0) {
return 1; // Base case: 0! = 1
SA
} else {
return $n * factorial($n - 1); // Recursive case
}
}
// Example usage
$number = 5;
echo "The factorial of $number is: " . factorial($number);
?>
1. Base Case: The base case is the condition that stops the recursion. In the factorial
example, the base case is 0! = 1.
2. Recursive Case: The function calls itself with a smaller problem, n - 1, until it reaches
the base case.
72
Summary
I. Creating and Invoking Functions: Functions in PHP are created using the function
keyword and invoked by calling their name followed by parentheses.
II. Example of Sum of N Even Numbers: A function sumEvenNumbers($n) calculates
the sum of the first N even numbers.
III. Using Recursion: Recursion is a technique where a function calls itself to solve smaller
instances of the same problem. The factorial example demonstrates how to use
recursion to calculate the factorial of a number.
IL
● Explain the syntax and usage of Multidimensional Arrays in PHP. Give examples.
● Explain the syntax and usage of any three string functions.
A multidimensional array is an array that contains one or more arrays. PHP supports
H
multidimensional arrays that can be either indexed or associative arrays. These arrays can be
used to store complex data structures.
Syntax
$array = array(
// more arrays
);
Usage
php
<?php
73
$students = array(
);
// Accessing elements
IL
echo "Name: " . $students[0][0] . " " . $students[0][1] . ", Age: " .
$students[0][2] . "\n";
echo "Name: " . $students[1][0] . " " . $students[1][1] . ", Age: " .
$students[1][2] . "\n";
echo "Name: " . $students[2][0] . " " . $students[2][1] . ", Age: " .
$students[2][2] . "\n";
?>
H
Example: Associative Multidimensional Array
SA
php
<?php
$students = array(
);
74
// Accessing elements
IL
?>
PHP provides a wide range of string functions to manipulate strings. Here are three commonly
used string functions:
1. strlen()
H
The strlen() function returns the length of a string.
Syntax:
SA
php
strlen(string);
Example:
php
<?php
?>
2. str_replace()
75
The str_replace() function replaces all occurrences of a search string with a replacement
string.
Syntax:
php
Example:
php
Copy code
IL
<?php
?>
3. strpos()
H
The strpos() function finds the position of the first occurrence of a substring in a string. It
returns the index of the first occurrence or false if the substring is not found.
SA
Syntax:
php
strpos(haystack, needle);
Example:
php
<?php
?>
Summary
I. Multidimensional Arrays: Used to store complex data structures in PHP. They can be
either indexed or associative arrays.
II. String Functions:
A. strlen(): Returns the length of a string.
IL
B. str_replace(): Replaces occurrences of a search string with a replacement
string.
C. strpos(): Finds the position of the first occurrence of a substring in a string.
● How are HTML Form controls connected to a database in PHP? Consider any
H
suitable example to explain.
Connecting HTML form controls to a database in PHP involves several steps. Here's a
step-by-step guide with an example:
SA
1. Create an HTML Form: The form collects user input.
2. Process Form Data with PHP: Retrieve the input data using PHP.
3. Connect to a Database: Use PHP to connect to a database.
4. Insert Form Data into the Database: Use SQL to insert the form data into a database
table.
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
77
</head>
<body>
IL
<input type="text" id="student_name" name="student_name"
required><br><br>
</form>
</body>
SA
</html>
php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$student_id = $_POST['student_id'];
$student_name = $_POST['student_name'];
78
$student_age = $_POST['student_age'];
$servername = "localhost";
IL
// Create connection
// Check connection
H
if ($conn->connect_error) {
} else {
$conn->close();
79
} ?>
Explanation:
1. HTML Form: The form collects the student's ID, name, and age.
2. Process Form Data: The process_form.php script retrieves the form data using the
$_POST superglobal array.
3. Connect to Database: The script creates a connection to the MySQL database using
the mysqli class.
4. Insert Data: The script inserts the form data into the student table using an SQL
INSERT query.
IL
Before running the example, make sure you have a MySQL database named course with a
table named student. The table should have the following structure:
sql
Copy code
);
Complete Workflow
1. Fill out the HTML form: The user enters their student ID, name, and age.
2. Submit the form: The form data is sent to process_form.php via POST method.
3. Process the form data:
80
○ The PHP script retrieves the submitted data.
○ It establishes a connection to the MySQL database.
○ The script inserts the form data into the student table.
○ It provides feedback on whether the insertion was successful or if there was an
error.
● Write SQL queries to fetch, edit and delete records in a dataset of an employee
IL
table having fields-empcode, ename, dob, qualifications and salary.
Assuming we have an employee table with the fields empcode, ename, dob,
qualifications, and salary, here are the SQL queries to fetch, edit, and delete records.
Table Structure
sql
H
CREATE TABLE employee (
SA
empcode INT PRIMARY KEY,
ename VARCHAR(100),
dob DATE,
qualifications VARCHAR(255),
salary DECIMAL(10, 2)
);
1. Fetch Records
sql
sql
sql
IL
2. Edit (Update) Records
sql
UPDATE employee
UPDATE employee
3. Delete Records
sql
sql
82
DELETE FROM employee
Here are all the queries in one place for easy reference:
sql
IL
sql
sql
H
SELECT * FROM employee WHERE salary > 50000;
sql
sql
UPDATE employee
Sql
UPDATE employee
sql
sql
IL
These queries cover the basic operations for fetching, updating, and deleting records in a
dataset of an employee table.
● What do you understand by Cookies? Create a cookie named “user” with the
H
value “Sushma Kohli” that expires after 15 days. How will this cookie be available
on the entire website? Also write code to retrieve it in PHP?
● What is a Session? Write PHP Code to show all the session variable values for a
SA
user session.
Understanding Cookies
Cookies are small pieces of data stored on the client-side (in the user's browser) and are used
to track and identify returning users. They are useful for maintaining user preferences, login
sessions, and other personalised settings across multiple pages of a website.
Creating a Cookie
To create a cookie in PHP, use the setcookie() function. Here's how to create a cookie
named "user" with the value "Sushma Kohli" that expires after 15 days:
php
<?php
84
// Calculate the expiration time (current time + 15 days)
?>
IL
● "/" indicates that the cookie is available across the entire website.
Retrieving a Cookie
php
<?php
H
if (isset($_COOKIE['user'])) {
} else {
SA
echo "Cookie 'user' is not set.";
?>
Understanding Sessions
Sessions are used to store information about a user across multiple pages of a website during
their visit. Unlike cookies, session data is stored on the server-side, making it more secure.
php
<?php
$_SESSION["email"] = "[email protected]";
$_SESSION["role"] = "admin";
IL
// Display all session variable values
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>
H
Summary
1. Cookies: Small pieces of data stored on the client-side. They can be used to maintain
SA
user preferences and sessions across multiple pages.
2. Sessions: Used to store user information on the server-side across multiple pages
during their visit.
$_SESSION["email"] = "[email protected]";
$_SESSION["role"] = "admin";
IL
echo "<pre>";
print_r($_SESSION);
○ echo "</pre>";
➖
H
● Describe the PHP functions for the following :
I. Opening and Closing a FIle.
II. File reading and writing.
Opening a File
To open a file, use the fopen() function. This function requires two parameters: the file path
and the mode in which the file should be opened.
Syntax:
php
fopen(filename, mode);
Modes:
IL
Example:
php
<?php
if ($file) {
H
echo "File opened successfully.";
} else {
SA
echo "Failed to open the file.";
?>
Closing a File
Syntax:
php
fclose(file);
Example:
Php
<?php
88
$file = fopen("example.txt", "r");
?>
Reading a File
IL
php
fread(file, length);
Example:
php
<?php
echo $content;
SA
fclose($file);
?>
Example:
php
<?php
echo $line;
89
}
fclose($file);
?>
Example:
php
IL
<?php
$content = file_get_contents("example.txt");
echo $content;
?>
Writing to a File
H
fwrite(): Writes a string to a file.
Syntax:
php
fwrite(file, string);
SA
Example:
php
<?php
fclose($file);
?>
file_put_contents(): Writes a string to a file (an easier way to write to a file compared to
fwrite()).
Syntax:
php
file_put_contents(filename, string);
90
Example:
php
<?php
?>
Summary
● Opening a File: Use fopen() with appropriate mode ('r', 'w', etc.).
● Closing a File: Use fclose() to close an opened file.
● Reading a File: Use fread() to read a specific number of bytes, fgets() to read a
IL
single line, or file_get_contents() to read the entire file.
● Writing to a File: Use fwrite() to write to a file or file_put_contents() for an
easier method to write to a file.
H
SA