0% found this document useful (0 votes)
9 views107 pages

XML and PHP Overview for B.Tech Students

This document covers Unit 4 of the Internet and Web Technology course, focusing on XML and PHP. It introduces XML, its advantages and disadvantages, key components, and the differences between XML and HTML, as well as DTD and XSD for validating XML documents. Additionally, it discusses transforming XML using XSL and XSLT, providing examples and comparisons of XML with other data formats.

Uploaded by

aneeshpatel83355
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views107 pages

XML and PHP Overview for B.Tech Students

This document covers Unit 4 of the Internet and Web Technology course, focusing on XML and PHP. It introduces XML, its advantages and disadvantages, key components, and the differences between XML and HTML, as well as DTD and XSD for validating XML documents. Additionally, it discusses transforming XML using XSL and XSLT, providing examples and comparisons of XML with other data formats.

Uploaded by

aneeshpatel83355
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chameli Devi Group of Institutions, Indore

Department of Computer Science & Engineering

Internet and Web Technology


(CS-504 A)

Unit - 4

B. Tech, 5th Sem

- Aniket Sugandhi -
UNIT - 4
XML : Introduction to XML, uses of XML, simple XML,
XML key components, DTD and Schemas, Using
XML with application. Transforming XML using XSL
and XSLT.

PHP: 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 to XML
 XML is a markup language, similar to HTML, but
designed to store and transport data.
 It is not a programming language—it does not
perform logic or calculations.
 XML is self-descriptive, i.e. the tags describe the
data.
 XML allows users to create their own tags (that’s
why it’s “extensible”).
 It is based on SGML (Standard Generalized
Markup Language) and was developed by W3C.
Why XML was created?
 In early computing, data exchange between
systems was difficult because:
 different platforms stored data differently
 data formats were not standardized
 integration between applications was complex

 XML solved this by offering:


 platform-independent
 hardware-independent
 software-independent
 standardized data representation
Uses of XML
 Data Exchange Between Applications

 Configuration Files

 Document Storage

 Data Representation in Industry

 RSS and Feeds

 Interfacing with APIs


Simple XML Example
<?xml version="1.0" encoding="UTF-8"?>
<Student>
<Name>Aniket</Name>
<RollNo>32</RollNo>
<Branch>Computer Engineering</Branch>
<Subjects>
<Subject>DBMS</Subject>
<Subject>Operating Systems</Subject>
<Subject>Computer Networks</Subject>
</Subjects>
</Student>
Advantages of XML
 Human and machine readable

 Platform independent

 Supports Unicode (global languages)

 Self-descriptive

 Flexible and extensible

 Industry-standard for structured data


Disadvantages of XML
 Verbose (more text compared to JSON)

 Parsing is slower

 Not ideal for lightweight web apps

 More memory consumption


HTML Vs XML

Feature XML HTML

Store &
Purpose Display data
transport data

Tags User-defined Predefined

Case sensitivity Sensitive Not sensitive

Structure Strict Flexible

Errors Not tolerated Browser adjusts


XML Key Components / Rules
 XML Declaration - This is usually the first line in an
XML document.

<?xml version="1.0" encoding="UTF-8"?>

 Elements - Elements are the building blocks of XML.

Example:
<Name>Rahul</Name>
XML Key Components / Rules
 Root Element - Every XML document must have
one and only one root element.
Example:
<Student>
...
</Student>

 Attributes - Attributes provide additional


information about elements.

Example:
<Student id="25" branch="CE">
XML Key Components / Rules
 Nested / Child Elements - XML follows a
hierarchical parent–child structure.
Example:
<Student>
<Name>Rahul</Name>
<Marks>
<Subject>DBMS</Subject>
<Subject>OS</Subject>
</Marks>
</Student>

 Comments - Used for explanations inside XML.


<!-- This section contains subject list -->
Example of XML
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
XML DTD
 An XML document with correct syntax is called
"Well Formed".

 An XML document validated against a DTD is both


"Well Formed" and "Valid".

 DTD stands for Document Type Definition.

 A DTD defines the structure and the legal elements


and attributes of an XML document.
Why DTD Needed?
 XML is flexible — anyone can create any tags.
Without rules, different systems may use different
structures for the same data.
 Example:
<StudentName>Rahul</StudentName>
 Someone else may write:
<Name>Rahul</Name>
 This leads to incompatibility.
 DTD ensures consistency and standardization,
especially when XML is used to exchange data
between systems.
Types of DTD
 Internal DTD
Defined inside the XML document.

 External DTD
Defined in a separate file.

 Both work identically, only the location differs.


Internal DTD
Example:
<?xml version="1.0"?>
<!DOCTYPE Student [
<!ELEMENT Student (Name, RollNo, Branch)>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT RollNo (#PCDATA)>
<!ELEMENT Branch (#PCDATA)>
]>
<Student>
<Name>Aniket</Name>
<RollNo>32</RollNo>
<Branch>Computer Engineering</Branch>
</Student>
External DTD
Step 1 — DTD File ([Link])

<!ELEMENT Student (Name, RollNo, Branch)>


<!ELEMENT Name (#PCDATA)>
<!ELEMENT RollNo (#PCDATA)>
<!ELEMENT Branch (#PCDATA)>
External DTD
Step 2 — XML File

<?xml version="1.0"?>
<!DOCTYPE Student SYSTEM "[Link]">
<Student>
<Name>Rahul</Name>
<RollNo>21</RollNo>
<Branch>IT</Branch>
</Student>
External DTD
Complete Example: DTD with Elements,
Attributes, Lists, Multiplicity

Step 1: DTD File ([Link])

<!ELEMENT Student (Name, Branch, Subjects)>


<!ELEMENT Name (#PCDATA)>
<!ELEMENT Branch (#PCDATA)>
<!ELEMENT Subjects (Subject+)>
<!ELEMENT Subject (#PCDATA)>
<!ATTLIST Student id ID #REQUIRED>
<!ATTLIST Subject code CDATA #IMPLIED>
External DTD
Step 2: XML File

<?xml version="1.0"?>
<!DOCTYPE Student SYSTEM "[Link]">
<Student id="S01">
<Name>Aniket</Name>
<Branch>Computer Engineering</Branch>
<Subjects>
<Subject code="CE301">DBMS</Subject>
<Subject code="CE302">Networks</Subject>
</Subjects>
</Student>
Advantages of DTD
 Ensures structure and correctness of XML

 Reusable across projects

 Lightweight and easy to write

 Supported by all XML parsers

 Good for simple hierarchical data


Limitations of DTD
 Cannot define data types (string, integer, date)

 No namespace support

 Not XML syntax (inconsistent with XML style)

 Limited validation capabilities

 Not suitable for complex enterprise data


XML Schema
XML Schema is an XML-based language
used to validate:
Structure of XML documents
Data types
Order of elements
Allowed values
Occurrence constraints (how many times
an element may appear)
Hierarchy of elements
Why XSD instead of DTD?
 Because DTD was limited:
 No data types
 No namespaces
 Not written in XML syntax
 Weak validation

 XSD solves all these by providing:


 Strong data typing
 Full XML syntax
 Namespace support
 Reusable and modular design
XML Schema
 XML Schema is Written in XML

 Unlike DTD, XSD uses the same XML syntax.

 This means:
 Easy to read
 Easy to parse with XML tools
 Easy to maintain

 Example:
<xs:element name="student" type="xs:string"/>
Key Components of XSD
 Elements - Defines an XML element.

 Example:
<xs:element name="name" type="xs:string"/>

 Attributes - Defines attributes of an element.

 Example:
<xs:attribute name="id" type="xs:int" use="required"/>
Key Components of XSD
 Complex Types - Define elements that contain
sub-elements or attributes.

 Example:

<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age" type="xs:int"/>
</xs:sequence>
</xs:complexType>
Key Components of XSD
 Simple Types - Define single values (no children).

 Example:

<xs:simpleType name="AgeType">
<xs:restriction base="xs:int">
<xs:minInclusive value="1"/>
<xs:maxInclusive value="100"/>
</xs:restriction>
</xs:simpleType>
Data Types in XSD
 Built-in Simple Types

xs:string
xs:integer
xs:decimal
xs:boolean
xs:date
xs:time
xs:ID
xs:float
XML Schema Example
XML (Student Data)

<student>
<name>Rahul</name>
<age>21</age>
<email>rahul@[Link]</email>
</student>
XML Schema Example
XML Schema (XSD)
<xs:schema xmlns:xs="[Link]
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:int">
<xs:minInclusive value="1"/>
<xs:maxInclusive value="100"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="email" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Advantages of XSD
 Strong data typing (int, decimal, date, etc.)

 Written in XML → easily parsed

 Namespace support

 Clear validation rules

 Supports complex structures

 Allows reusability (include/import)

 Better error messages

 Industry standard
Limitations of DTD
 More complex syntax

 Harder for beginners

 Complex as compared to DTD


Uses of XSD
Real-Life Uses of XML Schema

Banking systems (ISO 20022 uses XSD)


Healthcare records (HL7 XML)
E-commerce product catalogs
Web APIs
Configuration files
Data interchange between enterprises
DTD vs XSD
Feature DTD XSD
Syntax Not XML XML

Data Types No Yes

Namespaces No Yes

Extensible No Yes

Object-Oriented Yes (inheritance via


No
Features extensions)

Validation Strength Weak Strong

Common &
Usage Today Rarely used
Recommended
Using XML with Application
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
</body>
<script>
var parser, xmlDoc;
var text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";
parser = new DOMParser();
xmlDoc = [Link](text,"text/xml");
[Link]("demo").innerHTML =
[Link]("year")[0].childNodes[0].nodeValue;
</script>
</html>
Transforming XML Using XSL and XSLT
 XML is mainly used to store data, but it does not
control how that data looks when displayed.

 To display XML data in a formatted and readable


way, we use:

 XSL – eXtensible Stylesheet Language

 XSLT – XSL Transformations (a part of XSL)


Transforming XML Using XSL and XSLT
 XSL (Extensible Stylesheet Language) is a set of
languages used to style or transform XML
documents.
 XSL includes:

 XSLT – transforms XML into HTML, text, or another XML

 XPath – selects parts of XML documents

 XSL-FO – formatting objects (for PDF etc.)


Transforming XML Using XSL and XSLT
 XSLT (XSL Transformations) is used to transform XML
data into other formats such as:

 HTML (most common)


 Another XML file
 Plain text
 JSON (in advanced cases)
 XSLT uses templates and rules to match XML
elements and transform them.
Transforming XML Using XSLT

 To display XML data using XSL:

 XML file contains data

 XSL (stylesheet) contains transformation rules

 Browser or XSLT processor converts XML → HTML or


another format using XSL
Example - XML + XSLT Transformation
 XML File: [Link]
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="[Link]"?>
<students>
<student>
<name>Aniket</name>
<age>21</age>
<course>CSE</course>
</student>
<student>
<name>Amit</name>
<age>22</age>
<course>IT</course>
</student>
</students>
Example - XML + XSLT Transformation
 XSLT File: [Link]
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="[Link]
<!-- Template to match root element -->
<xsl:template match="/students">
<html>
<body>
<h2>Student Details</h2>
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>Course</th>
</tr>
Example - XML + XSLT Transformation

<!-- Loop through each student node -->


<xsl:for-each select="student">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="age"/></td>
<td><xsl:value-of select="course"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>
Example - XML + XSLT Transformation
 Output (HTML Table)

 When you open [Link] in a browser, it displays:

Student Details

Name Age Course


Aniket 21 CSE
Amit 22 IT
XML Using XSLT Example
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "[Link]"?>
<class>
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
XML Using XSLT Example…

<?xml version = "1.0" encoding = "UTF-8"?>


<xsl:stylesheet version = "1.0"
xmlns:xsl = "[Link]
<xsl:template match = "/">
<html>
<body>
<h2>Students</h2>

<table border = "1">


<tr bgcolor = "#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
XML Using XSLT Example…
<xsl:for-each select="class/student">
<tr>
<td>
<xsl:value-of select = "@rollno"/>
</td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "marks"/></td>
</tr>
</xsl:for-each>

</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Why Use XSLT?

 Clean separation of data (XML) and presentation (XSL)

 Reusability

 Can transform XML into multiple formats

 Supports powerful XPath expressions

 Used in web services, data processing, and reporting


Introduction to PHP
 PHP is an acronym for "PHP: Hypertext
Preprocessor"
 PHP is a widely-used, open source scripting
language
 PHP scripts are executed on the server
 PHP is free to download and use
 It is powerful enough to be at the core of the
biggest blogging system on the web (WordPress)!
 It is deep enough to run the largest social network
(Facebook)!
 It is also easy enough to be a beginner's first server
side language!
Introduction to PHP
 PHP files can contain text, HTML, CSS, JavaScript,
and PHP code
 PHP code is executed on the server, and the result
is returned to the browser as plain HTML
 PHP files have extension ".php“
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and
close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your
database
 PHP can be used to control user-access
 PHP can encrypt data
Introduction to PHP

 PHP runs on various platforms (Windows, Linux,


Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free.
 PHP is easy to learn and runs efficiently on the
server side
Features
 Open source: PHP is free to download and use.

 Platform independent: PHP code can run on any


platform.

 Faster: PHP scripts are usually faster than other


scripting language.

 PHP automatically converts a variable's data type.


Advantages
Disadvantages
How PHP Works? (Execution Flow)

 User sends request from browser →


[Link]/[Link]
 Request reaches the web server (Apache/NGINX)
 Server detects file is .php → sends to the PHP
interpreter
 PHP code runs on server
 Server returns pure HTML to browser
 Browser displays the output
PHP Syntax
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
Variables in PHP
 Variables are storage locations.
Rules :
 A variable starts with the $ sign.
 A variable name cannot start with a number.
 A variable name must start with a letter or the
underscore character.
 A variable name cannot start with a special character.
 A variable name can only contain alpha-numeric
characters and underscores.
 $name, $Name and $NAME are three different
variables.
Variables in PHP

 Automatically typed (no need to declare type)


 Example:
<?php
$name = "Aniket";
$age = 21;
$cgpa = 8.4;

echo "Name: $name, Age: $age, CGPA: $cgpa";


?>
PHP Decision
<?php
$marks = 75;
if($marks >= 90)
echo "Grade A";
elseif($marks >= 60)
echo "Grade B";
else
echo "Grade C";
?>
PHP Decision
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops

<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
PHP Loops (continued…)

<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
PHP Loops (continued…)

<?php
for ($x = 0; $x <= 10; $x++)
{
echo "The number is: $x <br>";
}
?>
PHP Loops (continued…)
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
PHP and HTML Integration
 PHP can be embedded inside HTML or can
generate HTML.
 This makes PHP very suitable for web
development.
 Example:
<!DOCTYPE html>
<html>
<body>
<h2>Welcome</h2>
<?php
echo "<p>This is PHP inside HTML</p>";
?>
</body>
</html>
Arrays in PHP
 Arrays store multiple values in a single variable.

 PHP supports:

Indexed Arrays

Associative Arrays

Multidimensional Arrays
PHP Arrays
 Indexed Arrays: These arrays use numeric keys,
starting by default from 0 for the first element, 1 for the
second, and so on.

<?php
$fruits = array("Apple", "Banana", "Orange");
echo $fruits[0]; // Output: Apple
?>

<?php
$colors = ["Red", "Green", "Blue"];
echo $colors[1]; // Output: Green
?>
PHP Arrays
 Associative Arrays: These arrays use named keys
(strings) to access their values, providing a more
descriptive way to organize data.

<?php
$person = array("name" => "John Doe", "age" => 30,
"city" => "New York");
echo $person["name"]; // Output: John Doe
?>
PHP Arrays
 Multidimensional Arrays: These arrays contain one or
more arrays within themselves, allowing for the storage
of complex, hierarchical data structures.

<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array(“Mahindra",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold:
".$cars[0][2].".<br>"; //Output: Volvo: In stock: 22, sold: 18.
?>
PHP Functions
 In PHP, a function is a block of statements that can be
used repeatedly in a program.

 Functions are defined to perform specific tasks and can


accept arguments (inputs) and return values (outputs).
They promote code reusability and organization.

 A function in PHP is defined using the function


keyword, followed by the function name, a pair of
parentheses (which may contain parameters), and curly
braces that enclose the function's code block.
PHP Functions
 Syntax:
<?php
function functionName($parameter1, $parameter2) {
// Code to be executed
return $value; // Optional: return a value
}
?>
 To execute a function, it must be "called" by its
name, followed by parentheses, and any required
arguments.
PHP Functions
 Example:

<?php
function greet($name){
return "Hello $name!";
}
echo greet("Aniket");
?>
PHP Browser Control
 PHP can control various features of a browser.
 This is important as often there is a need to reload the
same page or redirecting the user to another page.
 Some of these features are accessed by controlling the
information sent out in the HTTP header to the browser,
this uses the header() command such as:
header("Location:[Link]");
 We can also control the caching using same header()
command
header("Cache-Control: no-cache");
 Or can specify the content type like,
header("Content-Type: application/pdf");
PHP Browser Detection
 The range of devices with browsers is increasing so it is
becoming more important to know which browser and
other details you are dealing with.
 The browser that the server is dealing can be identified
using:

$browser_ID = $_SERVER['HTTP_USER_AGENT’];

 Typical response of the above code is follows:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36


(KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36
PHP Strings
 In PHP, a string is a sequence of characters used to
store and manipulate text. It is a fundamental
data type and can contain letters, numbers,
symbols, and special characters.
 Single Quoted Strings- Enclosed in single quotes ('').
Text within single quotes is treated literally,
meaning variables and most escape sequences
are not interpreted.
 Double Quoted Strings- Enclosed in double quotes
(""). Double-quoted strings interpret variables and
most escape sequences (like \n for newline, \t for
tab).
PHP Strings
<?php
$name = 'John';
echo 'Hello, $name!'; // Output: Hello, $name!
echo 'This is a single-quoted string with a newline \n.'; //
Output: This is a single-quoted string with a newline \n.
?>
<?php
$name = 'Jane';
echo "Hello, $name!"; // Output: Hello, Jane!
echo "This is a double-quoted string with a newline.\n";
// Output: This is a double-quoted string with a newline.
?>
PHP Strings
 Most of the time in PHP we suppose to do
manipulation of strings, whether it be input from
the user, database or files that have been written.
 String can be thing as a array of characters, so it is
possible to do something like this,
$mystring = "Welcome to CDGI Indore";
print($mystring[7]);
 This uses an index as an offset from the beginning
of the string starting at 0.
 Often, there are specific things that need to be
done to a string, such as reversing, extracting part
of it, finding a match to part or changing case etc.
PHP Strings
 PHP provides numerous built-in functions for
manipulating strings, including:
 strlen(): Returns the length of a string.
 str_word_count(): Counts the number of words in a
string.
 strpos(): Searches for a specific text within a string.
 str_replace(): Replaces occurrences of a substring
within a string.
 substr(): Extracts a part of a string.
 trim(): Removes whitespace or other characters
from the beginning and end of a string.
 String concatenation: The dot (.) operator is used to
join two or more strings.
PHP Strings
 <?php
echo strlen("Hello world!");
?>
 <?php
echo str_word_count("Hello world!");
?>
 <?php
echo strrev("Hello world!");
?>
 <?php
echo strpos("Hello world!", "world");
?>
 <?php
echo str_replace("world", “AI", "Hello world!");
?>
PHP File Handling
 File handling in PHP involves a set of functions used to
interact with files on the server, including creating,
reading, writing, appending, and deleting files.

 Major file handling functions:


fopen(): Opens a file and returns a file pointer
resource. It takes two arguments: the file name and
the access mode (e.g., "r" for read, "w" for write, "a"
for append).
fclose(): Closes an open file pointer, releasing the
resource.
PHP File Handling
fread(): Reads a specified number of bytes from an
open file. It takes the file pointer and the number of
bytes to read as arguments.
fwrite(): Writes a string to an open file. It takes the
file pointer and the string to write as arguments.
file_get_contents(): Reads the entire content of a file
into a string. This is a convenient function for reading
small to medium-sized files.
file_put_contents(): Writes a string to a file. If the file
does not exist, it creates it. If it exists, it overwrites
the content by default (or appends if FILE_APPEND
flag is used).
PHP File Handling
 Access Modes for fopen():
 "r": Read-only. File pointer at the beginning.
 "w": Write-only. Truncates the file to zero length or
creates a new file. File pointer at the beginning.
 "a": Append-only. Creates a new file if it doesn't exist. File
pointer at the end of the file.
 "r+": Read and write. File pointer at the beginning.
 "w+": Read and write. Truncates the file or creates a new
one. File pointer at the beginning.
 "a+": Read and write. Creates a new file if it doesn't exist.
File pointer at the end.
PHP File Handling
 <?php
echo readfile("[Link]");
?>
 <?php
$myfile = fopen("[Link]", "r") or die("Unable to open
file!");
echo fread($myfile,filesize("[Link]"));
fclose($myfile);
?>
 <?php
$myfile = fopen("[Link]", "r") or die("Unable to open
file!");
echo fgets($myfile);
fclose($myfile);
?>
PHP File Handling (continued)
 <?php
$myfile = fopen("[Link]", "r") or die("Unable to open
file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
 <?php
$myfile = fopen("[Link]", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
PHP Form Processing
 Form processing means collecting user input from
HTML forms and handling it in PHP on the server.

 PHP form handling involves collecting, validating,


sanitizing, and processing data submitted through
HTML forms.

 This process is crucial for creating interactive and


secure web applications.
PHP Form Processing
 PHP uses superglobal variables (arrays) to access
submitted form data:

 $_POST: Used to retrieve data submitted via the POST


method.

 $_GET: Used to retrieve data submitted via the GET


method.

 $_REQUEST: Contains data from both $_POST and


$_GET, along with $_COOKIE.
PHP Form Processing
 <html>
<body>
<form action="[Link]" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

 <html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
PHP Form Validation
 PHP form validation is the process of ensuring that
user-submitted data through an HTML form meets
specific criteria before it is processed or stored.
 This is crucial for maintaining data integrity, preventing
security vulnerabilities like SQL injection, and providing
a better user experience by giving immediate feedback
on incorrect or incomplete input.
 Sanitization: Clean the input data to remove potentially
harmful characters. Common functions include trim() to
remove whitespace, stripslashes() to remove
backslashes, and htmlspecialchars() to convert special
characters to HTML entities.
PHP Form Validation
 Validation: Check if the data meets specific rules.
Examples include:
Required fields: Ensure essential fields are not
empty.
Data type validation: Check if input is a valid email,
number, URL, etc. (e.g., using filter_var() with
FILTER_VALIDATE_EMAIL or regular expressions).
Length constraints: Verify minimum or maximum
length for fields like passwords.
Format validation: Use regular expressions
(preg_match()) for complex patterns like phone
numbers or specific usernames.
PHP Form Validation
 Handle Validation Errors: If validation fails for any field,
store error messages and display them to the user,
typically next to the problematic input field, guiding
them to correct the input.

 Process Valid Data: If all validation checks pass,


proceed with processing the data, such as storing it in a
database or sending an email.
PHP Form Validation
 <?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;
}
?>
PHP Form Required
 To create a PHP form with required fields, both client-
side (HTML) and server-side (PHP) validation are
necessary for robust error handling and user
experience.

 Client-Side Validation (HTML): The required attribute in


HTML5 can be used directly on input fields to enforce
client-side validation, preventing form submission if
required fields are empty.
PHP Form Required
<form action="process_form.php" method="post">

<label for="name">Name:</label><br>
<input type="text" id="name" name="name"
required><br><br>

<label for="email">Email:</label><br>
<input type="email" id="email" name="email"
required><br><br>

<input type="submit" value="Submit">

</form>
PHP Form Required
 Server-Side Validation (PHP): Server-side validation is
crucial as client-side validation can be bypassed.

 In the process_form.php file (or wherever your form


data is handled), check if the required fields are empty
using PHP's empty() function.
PHP Form Required
 <?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}?>
PHP Cookies
 Cookies in PHP are small pieces of data stored in the
user's web browser by a web server.

 They are used to remember information about the user


and their interactions with a website, enabling features
like session management, personalization, and
tracking.

 The setcookie() function is used to create or modify a


cookie. It must be called before any output is sent to the
browser, as cookies are part of the HTTP header.
PHP Cookies
 <?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); //
86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
PHP Session
 PHP sessions provide a mechanism to store user-
specific information on the server, making it accessible
across multiple pages during a user's visit to a website.

 This is particularly useful for maintaining user state,


such as login status, shopping cart contents, or user
preferences.

 session_start(): This function must be called at the


beginning of any PHP script that needs to utilize
session variables. It either initiates a new session or
resumes an existing one based on a session ID,
typically passed via a cookie named PHPSESSID.
PHP Session
 $_SESSION Superglobal: This is an associative array
used to store and retrieve session data. Data is stored
as key-value pairs within this array.

 Accessing Session Data: Once stored, session data


can be accessed on subsequent pages (after calling
session_start()) by referencing the $_SESSION array.

 session_destroy(): This function is used to end a


session and clear all associated session data on the
server. To completely remove the session variables,
session_unset() can be used in conjunction with
session_destroy().
PHP Session
 How Sessions Work:
 When session_start() is called, PHP generates a unique
session ID for the user if one doesn't already exist.
 This session ID is then sent to the user's browser, usually
in a cookie (e.g., PHPSESSID).
 On subsequent requests, the browser sends this session
ID back to the server.
 PHP uses this ID to retrieve the corresponding session
data stored on the server, making it available through the
$_SESSION superglobal.
 Session data is stored on the server-side, offering a more
secure alternative to cookies for sensitive information, as
it is not directly exposed or modifiable by the client.
PHP Session
 <?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>
PHP Session
 <?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
OOPS with PHP
 class Fruit {
public $name;
public $color;
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
OOPS with PHP
 <?php
class Fruit {
public $name;
public $color;

function __construct($name, $color) {


$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
?>
OOPS with PHP
 <?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
OOPS with PHP
 PHP Destructor

 PHP Constants

 PHP Abstract Classes

 PHP Interfaces

 PHP Static Methods

 PHP Static Variables

You might also like