Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Web Programming notes

Full-stack development encompasses both front-end and back-end web application creation, requiring diverse skills in UI design, server-side logic, and database management. Developers utilize various technology stacks, such as MEAN and MERN, to build scalable applications while employing APIs for seamless data exchange. Testing is crucial in this process, ensuring functionality and security through methodologies like TDD and BDD, and utilizing various tools for unit, integration, and performance testing.

Uploaded by

Varun Shivan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Web Programming notes

Full-stack development encompasses both front-end and back-end web application creation, requiring diverse skills in UI design, server-side logic, and database management. Developers utilize various technology stacks, such as MEAN and MERN, to build scalable applications while employing APIs for seamless data exchange. Testing is crucial in this process, ensuring functionality and security through methodologies like TDD and BDD, and utilizing various tools for unit, integration, and performance testing.

Uploaded by

Varun Shivan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

Introduction to Full-stack development

Full-stack development involves creating web applications covering both front-end and back-end aspects,
along with effective database management. In this holistic approach, developers handle the entire application
stack, from the user interface (UI) to server-side logic and database functionality. For example, consider a
sign-in page on a website. The front-end, or client-side, presents the UI where users input data, and this
information is sent to the back-end, or server-side, for validation through the database.
• Full-Stack Developer Skills
A full-stack developer possesses skills across all layers of an application, integrating different technologies
and frameworks to create end-to-end solutions.
• Front-End Development
Front-end development focuses on UI design using core technologies like HTML, CSS, and JavaScript.
Responsive design ensures that web applications adapt uidly to various devices, providing a consistent user
experience. Additionally, web accessibility in front-end development involves designing interfaces usable by
people with disabilities.
• Back-End Development
On the back-end, developers manage server-side logic, handle client requests ef ciently, and engage in API
development. The choice of server environments, such as Node.js with Express, requires a careful
con guration for stable and ef cient back-end operations. API development involves creating endpoints for
seamless data interaction between the server and client, enhancing overall functionality.
• Database Management
Database management is crucial for the effective storage and retrieval of data using systems like MySQL,
PostgreSQL, or MongoDB. Database design principles, including normalization and indexing, optimize data
organization and retrieval speed. Database management ensures data integrity through transactions
following ACID properties.
• Version Control and Collaboration
Version control systems like Git facilitate collaborative development by tracking changes to code, enabling
teamwork and systematic codebase management. Branching and merging are essential functionalities,
allowing developers to work independently on features before merging changes.
APIs in Full-Stack Development
APIs play a vital role in connecting front-end and back-end systems, enabling seamless data exchange.
Different types of APIs cater to diverse purposes, including RESTful APIs, Library APIs, Operating System
APIs, Database APIs, and OAuth APIs, among others.
API Bene ts
In the context of full-stack applications, front-end components leverage APIs to request and retrieve data
from the backend, enabling seamless user interactions and dynamic content updates. APIs also facilitate
communication in microservices architectures, where different parts of an application are developed and
deployed independently.
Moreover, APIs are instrumental in integrating full-stack applications with third-party services or APIs,
enhancing functionality by connecting with services like payment gateways, social media platforms, or
mapping services. They play a crucial role in versioning different parts of applications, ensuring smooth
updates and feature introductions without disrupting existing functionality. Additionally, APIs contribute to
secure communication, implement mechanisms such as API keys or OAuth tokens, and play roles in user
authentication and authorization.
API Types
Different types of APIs serve diverse purposes, including RESTful APIs, Library APIs, Operating System
APIs, Database APIs, and OAuth APIs, among others.
Deployment and Hosting
To make an app live, developers deploy it on a hosting platform. Choosing a platform involves
considerations like Heroku for a user-friendly experience, AWS for extensive cloud services, or Netlify for
simplicity and a focus on static sites. Scalability and performance requirements are crucial, and platforms
like AWS provide scalable solutions with resource adjustments based on demand. Load balancing and
fi
fi
fi
fl
fi
caching mechanisms optimize performance by distributing incoming traf c across multiple servers and
storing frequently accessed data, respectively. These measures contribute to a smoother user experience.

Web Stacks and Technology Choices


A web stack, or technology stack, refers to a combination of software components used in web development,
providing the infrastructure for creating and running web applications.
• AMP Stack
One common type is the AMP stack, including Apache, MySQL, and PHP. Apache serves web pages,
MySQL manages structured data, and PHP is a server-side scripting language for dynamic content.
Variations include LAMP (Linux, Apache, MySQL, PHP/Python/Perl), WAMP (Windows, Apache, MySQL,
PHP/Python/Perl), and XAMPP (Cross-platform, Apache, MariaDB/MySQL, PHP, Perl).
• LAMP Stack
The LAMP stack, with Linux as the OS, is open-source, cost-effective, and exible, offering seamless
integration for web development. However, its installation process may be complex for beginners.
• WAMP Stack
WAMP, designed for Windows, simpli es the setup on Windows machines, providing a user-friendly
experience and streamlined testing.
• XAMPP Stack
XAMPP is a cross-platform solution with a user-friendly interface, offering exibility with standard or full
versions. It includes additional tools like phpMyAdmin, OpenSSL, and content management systems.

Choosing the Right Stack


Choosing the right stack involves considering compatibility with the operating system, programming
languages, database requirements, performance demands, security features, exibility for customization, and
ease of use. LAMP and WAMP are OS-speci c, while XAMPP is cross-platform. Considerations include the
preferred programming language, database type, performance optimization, security mechanisms, exibility,
and the skill level of the development team. For extensive customization, stacks like LAMP may be suitable,
while stacks like XAMPP prioritize simplicity and rapid development.

Modern Web Stacks


Modern web stacks play a crucial role in ef cient and streamlined web application development. One
prominent example is the MEAN (MongoDB, Express.js, Angular, Node.js) stack, which utilizes JavaScript
throughout the entire development process. MongoDB, a NoSQL database, manages data, Express.js
facilitates server-side development, Angular handles the front end, and Node.js is the runtime environment.
MEAN excels in real-time applications, offers exibility in component selection, and bene ts from a large
developer community.

MERN Stack
A similar stack, MERN (MongoDB, Express.js, React, Node.js), replaces Angular with React, emphasizing
reactivity and seamless integration. MERN leverages React’s virtual DOM for ef cient UI development and
bene ts from a vibrant development community.

MEAN vs. MERN


MEAN and MERN are well-suited for Single-Page Applications (SPAs), real-time applications, and scalable
solutions. MEAN is known for unifying the development language, exibility, and adaptability, while
MERN excels in building ef cient and interactive user interfaces.
Comparing MEAN and MERN, MEAN uses Angular for comprehensive UI development, suitable for large-
scale enterprise projects. MERN, with React, prioritizes simplicity, ease of learning, and exibility, making
it ideal for smaller to medium-sized applications. MEAN is preferred for large-scale enterprise architecture,
offering a uni ed and opinionated framework, while MERN is suitable for projects prioritizing exibility
and adaptability.
fi
fi
fi
fi
fi
fi
fl
fl
fi
fl
fl
fl
fi
fl
fi
fl
fl
Both stacks have advantages and are chosen based on project requirements, development team expertise, and
scalability needs. MEAN is favored for comprehensive and integrated frameworks, while MERN excels in
exibility and simplicity. Examples of companies using MEAN and MERN stacks include Shutterstock,
Tumblr, Forbes, YouTube, and Facebook, Instagram, WhatsApp, DropBox, and Net ix, respectively.

RESTful APIs
RESTful APIs, following a set of architectural principles, are designed to be simple, scalable, and exible.
They adhere to the stateless principle, where each client request contains all necessary information for the
server to understand and ful ll it without storing the client state between requests. These APIs utilize
standard HTTP methods—GET for retrieval, POST for creation, PUT for updating or creating, and DELETE
for removal.
• Key Abstractions
Key abstractions in RESTful APIs are resources, identi ed by Uniform Resource Identi ers (URIs),
representing entities like objects, data, or services. These APIs provide a uniform interface for interacting
with resources, ensuring consistency in access, manipulation, and navigation. Resources are represented in
formats such as JSON or XML, and clients interact with representations rather than the resources directly.
• API Endpoints
API endpoints are speci c URLs or URIs exposed by an API for client interaction. They correspond to
functions or operations, with the HTTP method indicating the action. A complete API endpoint combines the
base URL, endpoint path, and any additional parameters. For instance, GET https://api.example.com/users
retrieves a list of users.
• Fetch API
The Fetch API, a modern JavaScript API, simpli es HTTP requests. It initiates requests and handles
responses asynchronously. For example, the fetch function is used to request data, with subsequent .then()
blocks processing the response and handling errors.

Real-World Use Cases


Real-world use cases for APIs abound in various domains, including e-commerce, social media integration,
mapping services, nance, and document collaboration platforms. E-commerce platforms integrate APIs
from payment gateways (e.g., PayPal, Stripe) for secure online transactions. Social media APIs (Facebook,
Twitter) enable app integration, allowing users to share content and log in using social credentials. Mapping
APIs (Google Maps, Mapbox) power location-based services, navigation, and displaying geographic data.
In the nancial sector, APIs facilitate integration with banking systems, stock market data, and payment
processing, supporting seamless transactions in ntech applications. APIs also play a crucial role in
document collaboration platforms (Google Docs, Microsoft Of ce 365), enabling integration with third-
party apps for collaborative editing across different environments.

Full-Stack Testing Overview


Testing is a critical aspect of full-stack development, ensuring the reliability, functionality, and security of
software applications. It spans both frontend and backend components, including interactions between them.
Unit tests verify individual pieces of the user interface and backend functions, while API testing validates
correct endpoint responses and adherence to speci cations. Integration tests ensure seamless interaction
between frontend and backend, and end-to-end tests simulate real user interactions.

Importance of Testing in Web Development


Testing in web development holds paramount signi cance for several reasons. It ensures robustness,
security, and a positive user experience. Comprehensive testing guarantees that applications meet speci ed
requirements, identifying and rectifying issues early. It covers usability aspects, security vulnerabilities, and
performance considerations, contributing to a high-quality end product.
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fl
fi
Testing Methodologies
• Test-Driven Development (TDD) involves writing tests before implementing code, facilitating early
issue identi cation and cleaner, more maintainable code.
• Behavior Driven Development (BDD) emphasizes collaboration, using a common language for
executable speci cations and aligning development with user expectations.
Test Documentation
Test documentation is crucial, providing a structured record of testing activities, establishing traceability,
and serving as evidence of conducted tests. Well-documented test cases support reusability, defect
management, and onboarding new team members.
Real-World Testing Challenges
Real-world testing presents challenges such as unclear requirements, tight schedules, integration
complexities, cross-browser/platform compatibility, and security vulnerabilities. Mobile application testing
involves diverse devices and platforms.
Automated vs. Manual Testing
Automated testing offers ef ciency, consistency, and effectiveness in regression, performance, and load
testing. Manual testing allows exploration, intuition, and adaptability, making it effective in projects with
evolving or unclear requirements. A combination of automated and manual testing is often employed based
on project needs and resource considerations.
Testing Types
• Unit testing involves testing individual components or functions of the code to ensure they work as
intended. It focuses on verifying correctness at the smallest unit level and validates that individual
functions or methods produce the expected output for a given set of inputs.
• Integration testing tests how different components work together in the entire system. It veri es
that data is correctly exchanged between frontend (user interface) and backend (server) components,
ensuring that the integrated system functions as a cohesive unit.
• End-to-end testing involves validating the entire application ow from start to nish, focusing on
testing user journeys and interactions throughout the application. The primary goal is to ensure that
all integrated components work together seamlessly to provide a smooth user experience.
• Performance testing assesses the system’s behavior under speci c conditions, such as varying
levels of user traf c or data loads. It evaluates the system’s speed, responsiveness, and stability under
different scenarios.
• Security testing is designed to identify vulnerabilities and weaknesses in the application’s
architecture and code. It focuses on ensuring robust protection against potential security threats and
malicious attacks.
• Usability testing evaluates the user-friendliness of the application, focusing on assessing the overall
user experience and interface. The primary purpose is to ensure that the application is intuitive and
easy to use for its intended audience.
• Regression testing con rms that existing functionalities within the application remain unaffected
after code changes or updates. It aims to prevent unintended side effects that could arise from
modi cations to the codebase.
• User Acceptance Testing (UAT) is conducted to validate whether the application meets the user
requirements and expectations. The primary purpose is to ensure alignment with user expectations
before the application is deployed.

Test-Driven Development (TDD) and Behavior Driven Development (BDD)


In Test Driven Development (TDD), developers create unit tests for speci c functionalities before
implementing the corresponding code. TDD focuses on small, incremental development cycles, with tests
driving the coding process, promoting early issue detection, and enhancing code reliability.
Behavior Driven Development (BDD) involves collaboration among developers, testers, and business
stakeholders to create scenarios that describe the desired behavior. BDD uses frameworks like Gherkin to
write scenarios in a human-readable format, enhancing communication. The choice between TDD and BDD
depends on project requirements, team dynamics, and the desired level of collaboration between technical
fi
fi
fi
fi
fi
fi
fl
fi
fi
fi
fi
and non-technical stakeholders. Each approach has strengths and can be used alone or in combination for
comprehensive test coverage.
Testing Tools
• In Unit Testing:
Jest (JavaScript/React): Language: JavaScript (Node.js). Features: Simple and powerful testing
environment, supports snapshot testing, and ef cient mocking capabilities.
JUnit (Java): Language: Java. Features: Widely used testing framework for Java, supports the creation of
unit tests to verify the correctness of individual units in the code.
• In Integration Testing:
TestNG (Java): Language: Java. Features: Testing for Java applications, provides exibility and power
beyond traditional testing frameworks, and supports integration testing scenarios.
Supertest (JavaScript/Node.js): Language: JavaScript (Node.js). Features: Integration testing for Node.js
applications, particularly for testing HTTP endpoints and APIs, supports assertions, and integrates well with
Node.js projects.
• In End-to-End Testing:
Selenium: Languages: Supports various programming languages (Java, JavaScript, Python, etc.). Features:
Versatile tool for automating browser-based testing, suitable for end-to-end testing scenarios, widely adopted
for cross-browser testing.
Cypress: Language: JavaScript. Features: End-to-end testing for JavaScript applications, focuses on a fast
and reliable testing experience, and provides real-time testing and debugging capabilities.
• In Performance Testing:
Apache JMeter: Language: Java. Features: Widely used open-source tool for performance testing,
simulates a large number of users, assesses application performance, and supports various protocols.
Locust (Python): Language: Python. Features: Python-based performance testing tool, used for load testing
web applications, focuses on scalability and ease of use, and enables simulation of user behavior through
code.
• In API Testing:
Postman: Features: Comprehensive API testing tool, allows creation, management, and execution of API
tests, supports automated testing, suitable for integration into continuous integration pipelines.
Insomnia: Features: API testing with a user-friendly interface for creating and executing API requests,
organizing requests into workspaces, supporting automated testing, and providing a straightforward UI.
• In Security Testing:
OWASP Zed Attack Proxy (ZAP): Features: Security testing tool designed for nding vulnerabilities in
web applications and providing automated scanners and various tools to identify and address security issues.
Burp Suite (Java): Language: Java. Features: Java-based security testing tool for web applications, includes
scanning, crawling, and analyzing application security, and offers a comprehensive set of tools for
penetration testing and vulnerability assessment.
• In Continuous Integration and Automation:
Jenkins: Features: Popular open-source automation server, supports building, deploying, and automating
projects, and integrates into CI/CD pipelines for automated testing at various development stages.
Travis CI: Features: Cloud-based CI/CD service for automating builds and tests in GitHub repositories,
con gured through YAML les, supports integration with testing tools, and provides automated testing with
each code change.
Best Practices in Full Stack Testing
• Test Automation: Implement automated testing for ef ciency, reduced human error, and continuous
integration. Bene ts include faster feedback, improved accuracy, and ef cient resource utilization.
• Continuous Integration (CI): Integrate testing into CI pipelines for automated builds. Bene ts
include early detection of issues and consistent testing environments.
• Use of Mocks and Stubs: Simulate external dependencies with tools for isolated testing. Bene ts
include faster execution and controlled test environments.
• Parallel Testing: Run tests concurrently for a signi cant reduction in test execution time. Bene ts
include a faster feedback loop for developers and testers.
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
fi
•Effective Test Data Management: Consistently manage and refresh test data for up-to-date and
relevant tests. Promotes test consistency and avoids false positives.
• Comprehensive Documentation: Document test cases, scenarios, and results for improved
collaboration. Enhances communication within the team and aids in troubleshooting.
Testing Strategies
• Component Testing: Test individual components in isolation for early issue detection. Crucial for
verifying the correctness of isolated functionalities.
• Integration Testing: Verify interactions between integrated components. Identi es collaboration
issues and ensures seamless communication.
• User Journey Testing: Validate end-to-end user scenarios for a satisfactory user experience.
Essential for ensuring the application meets user expectations.
• Cross-Browser Testing: Verify application compatibility across different web browsers. Ensures
consistent performance and appearance for a broad user reach.
These best practices and testing strategies collectively contribute to a robust and reliable full-stack testing
approach, addressing various aspects of functionality, collaboration, user experience, and compatibility.

Setting Up XAMPP for Frontend and Server-Side Development


XAMPP Installation Process
Visit the XAMPP Website:
• Go to the of cial XAMPP website.
• Download the appropriate installer based on your operating system (Windows/Linux).
• For Windows, choose the executable installer (.exe).
• For Linux, download the installer package (.tar.gz).
Execute the Installer:
• Run the downloaded installer and follow the on-screen instructions.
Select Components:
• During installation, specify preferences and select components such as Apache, MySQL, PHP, and
Perl.
XAMPP Control Panel
Launch the XAMPP Control Panel:
• After successful installation, locate the XAMPP Control Panel.
• Default installation directories:
• Windows: “C:\xampp”
• Linux: “/opt/lampp”
• Execute “xampp-control” to launch the Control Panel.
Manage Components:
• The Control Panel allows you to start, stop, and restart various components, including Apache,
MySQL, FileZilla, Mercury, and Tomcat.
Accessing XAMPP Dashboard and phpMyAdmin
Access XAMPP Dashboard:
• With Apache running, open a web browser and enter “localhost” to access the XAMPP dashboard
and projects.
phpMyAdmin Interface:
• Use the “Admin” button next to MySQL in the XAMPP Control Panel to open the phpMyAdmin
interface for MySQL database management.
• Log in with the default credentials: Username: “root,” Password: (leave it blank).
Test PHP Con guration
• Create a PHP le with a simple script.
• Save the le in the “htdocs” directory within the XAMPP installation.
• Access the PHP le through “localhost/demo.php” in a web browser to con rm correct PHP
con guration.
fi
fi
fi
fi
fi
fi
fi
fi
Frontend Development in XAMPP
Project Setup
Create a Project Folder:
• Navigate to the XAMPP installation directory.
• Locate the “htdocs” folder and create a new project folder (e.g., “/xampp/htdocs/my-frontend-
project”).
HTML Form Creation:
• Develop a basic HTML form within the project folder.
• Include input elds for name, email, gender, and website.
Styling with CSS:
• Enhance the form’s appearance by styling it using CSS.
• Separate HTML and CSS for better organization.
Integration with Bootstrap:
• Link Bootstrap’s CSS and JavaScript libraries to the HTML le.
• Utilize Bootstrap classes to enhance styling and interactivity.
JavaScript Functionality
Add JavaScript Code:
• Introduce JavaScript to enhance form functionality.
• Intercept form submissions, capture data, and log in to the console for custom processing.
Run the Project:
• Start the XAMPP server.
• Access the project through “localhost/my-frontend-project.”
• Fill in the form and submit to see data logged in the browser console.
Example html:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FrontEnd Form</title>
</head>
<body>
<div class="container mt-5">
<form id="myForm">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="form-group">
<label for="gender">Gender:</label>
<select class="form-control" id="gender" name="gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
</div>
<div class="form-group">
<label for="website">Website:</label>
<input type="url" class="form-control" id="website" name="website" required>
</div>
fi
fi
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>

Example html and CSS


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Combined HTML and CSS</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
.container {
max-width: 400px;
margin: 50px auto;
background-color: #ffa500;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
label {
font-weight: bold;
color: #333333;
}
input,
select {
width: 100%;
padding: 8px;
margin-bottom: 15px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background-color: #007bff;
border: none;
color: #fff;
padding: 10px;
cursor: pointer;
border-radius: 4px;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="gender">Gender:</label>
<select id="gender" name="gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<label for="website">Website:</label>
<input type="url" id="website" name="website" required>
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
Example html and Bootstrap
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FrontEnd Form</title>
<!-- Add Bootstrap CSS link -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- Link your custom CSS le -->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container mt-5">
<form id="myForm">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="form-group">
<label for="gender">Gender:</label>
<select class="form-control" id="gender" name="gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
fi
</div>
<div class="form-group">
<label for="website">Website:</label>
<input type="url" class="form-control" id="website" name="website" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<!-- Add Bootstrap JS and Popper.js (for Bootstrap) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<!-- Link your custom JavaScript le -->
<script src="script.js"></script>
</body>
</html>
Example JavaScript
document.getElementById("myForm").addEventListener("submit", function (event) {
event.preventDefault(); // Prevents the default form submission behavior
const formData = new FormData(this);
for (const [name, value] of formData) {
console.log(`${name}: ${value}`);
}
});
Server-Side Development in XAMPP
Project Setup
Create Server-Side Project:
• In XAMPP’s htdocs directory, create a new folder for the server-side project (e.g., “/xampp/htdocs/
my-server-project”).
Database Setup
• Set up a MySQL database to store form data.
PHP Server-Side Script
• Develop a PHP le (e.g., "process_form.php”) for server-side logic.
• Use conditional statements to check form submissions.
Data Validation and Sanitization
• Validate and sanitize input data within the PHP script.
• Check for required elds, validate email addresses, and sanitize inputs.
Database Interaction
Interact with MySQL Database:
• De ne database connection parameters.
• Use MySQLi or PDO extension for connection, prepare SQL statements, and execute queries to
insert form data.
Connection Handling:
• Verify successful database connection.
• Use prepared statements to prevent SQL injection.
• Close the connection after completing database operations.
Form Submission
Adjust Form Action:
• Modify the HTML form tag to include the “action” attribute, specifying the PHP le for form
submission.
Adjust Database Parameters:
• Set the correct database connection parameters in the PHP script.
fi
fi
fi
fi
fi
Form Submission Process:
• When the form is submitted, data is sent to “process_form.php.”
• The script validates, sanitizes, and inserts data into the MySQL database.
This process ensures a seamless transfer of data from the frontend to the server-side script for validation,
sanitization, and storage in the MySQL database. Adjustments to database connection parameters and PHP
script con gurations may be needed based on speci c server setups.
Example PHP
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Retrieve form data
$name = $_POST["name"];
$email = $_POST["email"];
$gender = $_POST["gender"];
$website = $_POST["website"];

// Validate and sanitize input (you can add more validation as needed)
$name = htmlspecialchars(trim($name));
$email = lter_var($email, FILTER_VALIDATE_EMAIL) ? $email : null;
$gender = in_array($gender, ["male", "female", "other"]) ? $gender : null;
$website = lter_var($website, FILTER_VALIDATE_URL) ? $website : null;

// If all data is valid, proceed to database interaction


if ($name && $email && $gender && $website) {
// Database connection parameters
$servername = "your_mysql_server";
$username = "your_mysql_username";
$password = "your_mysql_password";
$dbname = "your_mysql_database";

// Create a database connection


$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert data into the database


$sql = "INSERT INTO user_data (name, email, gender, website) VALUES ('$name', '$email', '$gender',
'$website')";
if ($conn->query($sql) === TRUE) {
echo "Data inserted successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the database connection


$conn->close();
} else {
echo "Invalid form data!";
}
fi
fi
fi
fi
} else {
echo "Invalid request!";
}
?>

Frameworks in Software Development: A Comprehensive Overview


Frameworks are essential tools in software development, providing developers with pre-built structures,
tools, and conventions that streamline and standardize the development process. They enhance ef ciency,
maintainability, and organization, offering solutions to common challenges. Libraries, which contain pre-
written code for speci c functionalities, and frameworks, which include tools like debuggers and testing
frameworks, contribute to the development lifecycle.
Types of Frameworks
1. Web Application Frameworks:
a. Examples: Django and Ruby on Rails
b. Focus on building web applications with features like routing, templating, and database interactions.
2. PHP Frameworks:
a. Examples: Laravel, Symfony, and CodeIgniter
b. Built on the PHP language, these frameworks enhance web development with features like database
abstraction layers and authentication systems.
3. Desktop Application Frameworks:
a. Examples: Electron and PyQt
b. Facilitate the development of desktop applications with cross-platform compatibility.
4. Mobile App Frameworks:
a. Examples: React Native and Flutter
b. Designed for building mobile applications for iOS and Android platforms.
5. Testing Frameworks:
a. Examples: JUnit and PHPUnit
b. Provide tools and conventions for writing and running tests.
6. Game Development Frameworks:
a. Examples: Unity and Phaser
b. Tailored for creating video games with features like rendering, physics, and asset management.
7. JavaScript Frameworks:
a. Examples: React.js and Angular
b. Focus on enhancing the development of JavaScript-based web applications.
8. Microframeworks:
a. Examples: Flask and Slim
b. Lightweight frameworks with minimalistic structures, suitable for small to medium-sized applications.
9. Full-Stack Frameworks:
a. Examples: MEAN (MongoDB, Express.js, Angular, Node.js) and Django
b. Encompass both frontend and backend components for comprehensive web development.
10. API Frameworks:
a. Examples: FastAPI and Spring Boot
b. Specialized frameworks for building robust APIs.

PHP Frameworks: Enhancing Web Development


PHP, being robust, versatile, and widely used in web development, serves as the foundation for many
popular websites. Notable PHP frameworks include:
• Laravel: Features: Eloquent ORM, Blade Templating, MVC Architecture, Artisan Console, and
robust security.
• Symfony: Embraces the MVC architecture and promotes modularity, scalability, and maintainability.
• CodeIgniter: Utilizes ActiveRecord for simpli ed database interactions and promotes rapid
development.
fi
fi
fi
• Yii: Known for its security measures, active community, and comprehensive documentation.
• Zend Framework (Laminas): Offers a collection of professional PHP packages for building
modern web applications.

PHP Frameworks’ Contribution to Productivity


• PHP frameworks, such as Laravel, Symfony, and CodeIgniter, contribute signi cantly to increased
productivity in web development through various features and practices:
• Code Reusability: PHP frameworks promote code reusability by offering reusable modules,
components, and templating engines. Laravel, for example, allows developers to create consistent
layouts and reuse UI elements, minimizing redundant coding efforts.
• Rapid Development: Laravel’s elegant syntax and expressive code, coupled with features like
Eloquent ORM, enable rapid development. Automation tools like Artisan in Laravel automate
common tasks, further accelerating project timelines.
• MVC Architecture: Frameworks like Symfony embrace the Model-View-Controller (MVC)
architecture, ensuring a clear separation of concerns. This separation enhances modularity,
scalability, and maintainability. Changes in one component do not necessitate alterations in others,
making development more ef cient.
• Object Relational Mapping (ORM): ORM simpli es database interactions by creating a mapping
between the object model and the database schema. CodeIgniter’s ActiveRecord, for instance, allows
developers to interact with databases using PHP methods instead of raw SQL queries, improving
code readability.
• Database Migrations: Laravel’s migration system and similar features in other frameworks provide
version control for database schema changes. This ensures seamless updates across different
development stages, maintaining data integrity and simplifying the deployment process.
• Security Measures: PHP frameworks prioritize security, as seen in Yii’s comprehensive measures.
Built-in features and active encouragement of secure coding practices, such as input validation and
output encoding, protect against common vulnerabilities like XSS and CSRF.
• User Authentication and Authorization: MVC’s separation simpli es user authentication and role-
based access control. Models manage user data and authentication logic, Views handle interfaces,
and Controllers govern ows. This structured approach streamlines implementation, ensuring a
cohesive, scalable, and maintainable approach.
• Active Communities: PHP frameworks bene t from active developer communities, facilitating
discussions, knowledge exchange, and continuous improvement. Laravel, for example, provides
extensive documentation and tutorials, creating a collaborative ecosystem where developers
contribute and stay updated with the latest features and security patches.

Microframeworks: Lightweight and Flexible


Microframeworks are designed to be lightweight, offering a minimalist approach to web development.
Examples like Slim, Silex, and Lumen prioritize simplicity and exibility, making them suitable for
scenarios such as rapid prototyping and the development of small- to medium-sized applications.

Characteristics of Microframeworks:
• Minimalistic Structure: Microframeworks provide only essential functionalities, ensuring a
lightweight and fast-paced development process without extensive built-in features.
• Flexible Component Selection: Developers can selectively integrate components based on project
needs, allowing for a tailored approach to development by leveraging preferred libraries or
extensions.
• Simpli ed Routing: These frameworks offer straightforward routing mechanisms, making it easy to
de ne endpoints and handle incoming HTTP requests ef ciently.
• Third-Party Libraries/Extensions: Microframeworks rely on third-party libraries or extensions for
features like authentication, allowing developers to choose the most suitable and secure methods for
their projects.
fi
fi
fl
fi
fi
fi
fi
fl
fi
fi
• Database Interaction: They enable database interactions using third-party libraries, providing
freedom to select databases and interaction methods tailored to project requirements.
• Input Validation: Microframeworks facilitate streamlined input validation through third-party
libraries or custom implementations, ensuring data integrity and security with user inputs.
• Template Engines: While often minimalist, microframeworks integrate with various template
engines, empowering developers to choose and use templates suited to their project’s UI rendering
needs.

Use Cases for Microframeworks:


• Rapid Prototyping: Microframeworks are excellent for quick project setups and prototyping,
allowing developers to visualize and iterate on concepts without the overhead of a full-stack
framework.
• RESTful APIs: They are ideal for developing lightweight RESTful APIs. For instance, Lumen,
Laravel’s microframework, excels in creating ef cient APIs, making it suitable for projects requiring
streamlined backend services.
• Learning and Experimentation: Microframeworks offer a simpler entry point into web
development, making them suitable for learning and experimentation. Selective component
integration with tools like Composer allows for precise customization.
• Advantages: Microframeworks are light, ensuring speed and simplicity. They are easier to
customize, making them suitable for projects with speci c requirements. They are ideal for
ef ciently handling high volumes of requests, such as in microservices or real-time applications.
• Considerations: They may have limitations for larger projects, potentially requiring additional
dependencies for complex integrations. Choosing between a microframework and a full-stack
framework depends on factors such as project size, complexity, and speci c requirements.

Choosing Between Microframeworks and Full-Stack Frameworks:


The choice depends on factors such as project size, complexity, and developer preferences.
Microframeworks are suitable for small projects, speci c functionalities, quick development, and full
control. Full-stack frameworks are ideal for medium to large projects, complex functionalities, consistent
project layouts, comprehensive solutions, and robust web development.
fi
fi
fi
fi
fi
Introduction to MVC
MVC, or Model-View-Controller, is an architectural pattern designed to structure code in a way that
enhances organization, scalability, and maintainability. Introduced by Trygve Reenskaug, MVC addresses
challenges in handling large and complex data in applications. It breaks down applications into three
interconnected components: Model, View, and Controller. This separation of concerns allows multiple
developers to work on different sections simultaneously.
Popular MVC Frameworks
Several popular MVC frameworks include:
• Django
• Laravel
• Cake PHP
• Ruby on Rails
• Spring
• Spring Boot
Features of MVC
• Separation of Concerns: Business logic, UI logic, and input logic are separated, enhancing code
organization, scalability, and reusability.
• Control Over HTML and URLs: Provides complete control over web application architecture,
allowing for user-friendly and ef cient URLs.
• TDD Support: Encourages Test Driven Development (TDD) by facilitating unit testing due to its
modular nature.
• Flexibility & Maintainability: Adaptable and easily extendable, promoting a modular structure for
streamlined maintenance.
Components of MVC
• Model: Manages data and associated logic, ensuring data integrity and consistency. Handles data
transfers between controllers and business logic.
• View: Presents information to users based on the model’s data, responsible for user interface
rendering.
• Controller: Manages user interaction, interprets input, and orchestrates communication between the
model and the view.
MVC Flow
The ow involves user actions in the view prompting the controller to act, which then updates the model or
executes business logic. The updated information is transferred back to the view for display.
Routing in PHP Application Architecture
Routing plays a vital role in linking URLs to speci c controller actions or methods. Leading PHP
frameworks like Laravel, Symfony, and Slim provide robust routing mechanisms.
Advantages of MVC
• Maintainable Code: Supports easy extension and ongoing maintenance.
• Independent Testing: Allows testing of components separately, promoting Test-Driven
Development (TDD).
• Parallel Development: Enables large teams to collaborate ef ciently on various aspects of the
application.
• Avoids Unnecessary Complexity: Breaking down the application into distinct components enhances
overall clarity.
• Front Controller Pattern: Streamlines request handling through a single controller.
• Logical Grouping: Contributes to code organization for scalability and maintainability.
Challenges of MVC
• UI Handling Challenges: Readability, modi cation, and testing of the User Interface can be
cumbersome.
• Complex Data Processing: Separation of concerns can lead to complex data processing and
potential inef ciencies.
fl
fi
fi
fi
fi
fi
• UI Framework Compatibility Issues: Possible con icts between the chosen MVC and popular UI
frameworks.
• Maintenance Overhead: Maintaining controller code, especially with numerous Individual Action
methods, can pose challenges.
• Complex Unit Testing: Model unit testing complexities may arise due to dependencies on the view
layer.
Model - Data Management in MVC
Data management is a foundational aspect of web development, encompassing the entire lifecycle of data
from user input to storage, manipulation, and presentation. It is the backbone of web applications, impacting
security, functionality, performance, and user experience. Properly managing user input is crucial for data
accuracy, validity, and protection against vulnerabilities.
In the Model-View-Controller (MVC) architecture, the Model plays a central role in managing data and
business logic. It encapsulates data-related operations, including retrieval and storage, and enforces business
rules and validation to ensure data integrity. Creating a Model involves structuring PHP classes with
properties representing data elds and establishing connections to the database.
In the collaboration between the Model and Controller, the Controller is the conductor, orchestrating actions
within the Model. The Controller receives data from the Model, manipulates it if necessary, and prepares it
for presentation to the user. This collaboration streamlines the ow of information, with the Controller
ensuring data accuracy and functionality, and the Model providing necessary data for user-friendly
presentations in the View. The symbiotic relationship between Model, Controller, and View contributes to a
seamless and interactive user experience in web applications.
CRUD Operations
CRUD operations (Create, Read, Update, Delete) are fundamental in database interactions, representing the
language of the Model. Data validation and sanitization are essential for securing and maintaining data
integrity.
View - User Interface (UI) in MVC
The User Interface (UI) is a crucial element in web development, signi cantly in uencing user interaction
with a web application. A well-designed UI enhances user engagement, allowing for easy exploration,
selections, and seamless navigation. Positive User Experience (UX) fostered by a robust UI can boost
conversion rates and business growth, complementing SEO efforts to draw in more relevant traf c.
In the MVC architecture, the View is pivotal, responsible for representing the visual presentation and user
interface of a web application. It is the presentation layer, displaying data in a visually understandable and
interactive format. Views utilize HTML, CSS, and sometimes JavaScript or template engines to structure
and render data, promoting separation of concerns for maintainability and scalability.
Creating Views involves crafting HTML templates, supplemented by CSS, outlining the layout and design
for UI components. Embedded logic, such as PHP within HTML, may be used to display content
dynamically based on conditions. Responsive design is prioritized to adapt content to diverse screen sizes,
ensuring a consistent user experience.
Rendering data in Views involves presenting Model information, often achieved through fetching data from
the Model. PHP loops and conditional statements are utilized to dynamically render content based on
retrieved data, tailoring the user interface dynamically.
View components enhance reusability and maintainability, allowing the creation of modular views for code
consistency. Templating engines like Smarty or Blade further streamline view management, providing tools
for implementing reusable templates.
The collaboration between the View and Model involves the Model providing data to the View for accurate
and updated content. In collaboration with the Controller, the View interacts to process user input
seamlessly, ensuring a smooth ow of information in web applications. This collaborative relationship
among Model, View, and Controller contributes to a cohesive and interactive user experience.
Controllers in MVC
In web development, effective management of application logic is pivotal for orchestrating data ow, and
Controllers play a central role in this process within the MVC architecture. Acting as the core component
handling application logic, Controllers ensure structured processes, especially in scenarios like e-commerce
fi
fl
fl
fl
fi
fl
fi
fl
platforms or content management systems. Controllers facilitate a systematic ow by coordinating actions
and decisions based on user input and system events. They act as intermediaries between the Model and
View, managing data formatting for the user interface and determining the overall behavior of the
application. Orchestrating the entire application, Controllers initiate actions based on user requests, deciding
which part of the Model should handle speci c tasks and which View should be rendered.
Routing is fundamental in directing user requests to corresponding Controller actions and de ning a
roadmap for the application’s logic based on URLs. Controllers logically group similar actions, allowing for
collective application rules. Controller actions, representing methods within a controller, handle speci c user
interactions, establishing a one-to-one mapping between user requests and corresponding actions.
Middleware and lters in Controllers contribute to request handling by managing pre-processing tasks and
modifying data.
In collaboration with the Model, Controllers initiate and coordinate data manipulation operations, such as
retrieving, updating, or deleting data. Working with the View, Controllers determine the appropriate user
interface based on user interactions, ensuring a cohesive and interactive user experience. Overall,
Controllers are the linchpin in managing application logic, ensuring organized processes and a seamless ow
of data in web development.
Overall, MVC architecture provides a systematic and organized approach to web development, offering
advantages in maintainability, scalability, and code organization. Challenges exist, but the proper
implementation of MVC principles contributes to a robust and ef cient web application development
process.
fi
fi
fi
fl
fi
fi
fl
Laravel: A Comprehensive PHP Framework
Laravel is an open-source PHP web framework designed for robust and scalable applications, known for its
elegant syntax and developer-friendly tools. It follows the MVC architectural pattern, emphasizing code
organization and separation of concerns.
Key features of Laravel
Key features include:
• Authentication and Authorization: Laravel simpli es authentication with an integrated system,
streamlining setup for quick implementation. The MVC architecture supports faster development,
enhancing collaboration among developers. Eloquent ORM facilitates seamless database querying
with an intuitive, object-oriented interface.
• Artisan Command-Line Tool: Laravel includes Artisan, automating repetitive tasks and
streamlining the development process. It generates skeleton code, database structures, and MVC
les, reducing manual coding efforts.
• Migration System: Laravel offers a robust migration system for secure database expansion using
PHP code. Database changes are carried out reliably, maintaining security standards.
• Template Engine: The framework includes a powerful template engine for dynamic website
creation, incorporating widgets.
• Security Measures: Laravel utilizes Bcrypt Hashing for inherent web application security,
encrypting and securely storing passwords.
• Libraries and Modular Design: Leveraging object-oriented and pre-installed libraries, Laravel
enhances application functionality. The framework is structured into modules, allowing developers to
build responsive and modular applications.
Advantages of Laravel
Laravel simpli es authentication and authorization processes, ef ciently controlling access to resources.
Integration with caching backends optimizes application performance, and seamless mail service enhances
communication. Laravel’s error handling, automation testing support, and business logic separation
contribute to a smoother development process.
Disadvantages of Laravel
Integration challenges with existing systems or third-party applications may arise. Due to extensive features
and the MVC architecture, beginners may face a steeper learning curve. Abstraction layers might introduce a
slight performance overhead, and dependencies on third-party packages can add complexity. Version
upgrades may pose compatibility issues, requiring adjustments in existing code or packages.
Versatility Across Industries
Laravel enjoys wide industry adoption, spanning IT, nance, healthcare, travel, sales, and entertainment. It
empowers diverse applications, including social networks, e-commerce platforms, multi/single-page apps,
static/dynamic websites, enterprise-level applications, and content management systems.
Laravel’s strengths lie in its comprehensive feature set, developer-friendly tools, and adaptability across
various domains, while considerations for potential challenges emphasize the need for strategic planning
during development and maintenance.
Comparison of PHP Frameworks
PHP frameworks serve as the backbone of web development, offering a structured and organized approach
to application building. They adhere to design patterns like MVC (Model-View-Controller), enhancing code
organization and promoting best practices. Key features common to PHP frameworks include MVC
architecture, built-in security measures, and support for database abstraction.
• Symfony: It is written in PHP, Symfony follows the MVC pattern and is highly modular, offering
reusable components for better code organization. Its documentation and community support are
robust, making it suitable for large-scale projects with complex requirements. Symfony’s exibility
and scalability, coupled with modularity, cater to developers working on expansive projects
demanding customization.
• CodeIgniter: It is recognized for its lightweight nature and simplicity, CodeIgniter offers a
minimalistic approach to web development. It emphasizes performance, making it suitable for
fi
fi
fi
fi
fi
fl
projects with speci c speed and ef ciency requirements. It requires minimal con guration, making it
easy to set up and ideal for small- to medium-sized applications.
• Yii: It is known for high-performance capabilities and a component-based architecture, Yii is
ef cient and suitable for large-scale applications. It offers excellent caching support for optimized
performance, making it recommended for projects with high traf c and complex features.
• Laminas (formerly Zend Framework): It is not a traditional framework but a collection of PHP
packages emphasizing modularity and reusability. It relies on Composer for package management,
providing individual components that can be used independently. It is well-suited for complex and
enterprise-level applications due to its modular and exible nature.
• Phalcon: It is a unique PHP framework written in C and C++ for maximum performance, with a
core implemented as a C-extension. It is renowned for high-speed execution, making it one of the
fastest PHP frameworks available. It is ideal for performance-critical applications requiring optimal
speed and ef ciency, especially in scenarios where low overhead is crucial.
These PHP frameworks cater to various development needs, offering a diverse range of features and
capabilities within the PHP ecosystem. Developers can choose based on project requirements, preferences,
and the desired balance between simplicity, performance, and scalability.
Steps for Creating a Web Application Using MVC Architecture with Laravel
The fundamental steps of creating a robust web application using the Model-View-Controller architecture.
The tools required are Text editor (e.g., VS Code), PHP and a web server (such as Apache or Nginx),
Composer, and MySQL or PostgreSQL.
Setup and Installation
Setting up PHP and server con gurations often involves a series of steps, especially when working with
frameworks like Laravel. Here are simpli ed steps for the setup and installation process:
Setup PHP and Server Con guration:
XAMPP Installation:
Download XAMPP from the of cial website.
Run the installer and follow on-screen instructions to install it.
During installation, you will have options to choose components like Apache, MySQL, and PHP. Ensure that
PHP is selected.
Environment Variables Setup:
Once XAMPP is installed, set up the path globally:
Open “Settings” and search for “Environment Variables.”
Select “Path” in the System Variables and click “Edit.”
Add the XAMPP PHP path (usually located in “C:\xampp\php”) to the list of paths.
Save the changes.
Installing Composer
Download Composer. Visit the of cial Composer website and download the Composer setup. Run the
installer and follow the installation process.
Install Laravel using Composer - Open the command prompt.
Run the following command - composer global requires laravel/installer
This command will install Laravel globally on your system.
Creating a New Laravel Project
Begin by installing Laravel through Composer. Use the command composer create-project laravel/laravel
your-project-name. This command creates a new Laravel project, fetching all the necessary dependencies.
After installation, use php artisan key:generate to generate the application key. The key is crucial for
securing your application, and this command ensures that a unique and secure key is in place. Next,
con gure your database settings in the .env le, and nally, run migrations with php artisan migrate to create
the required tables in the database. Migrations help in version controlling your database schema.
The development server is started and the Laravel application will be accessible at http://localhost:8000.
Using Laravel’s Artisan command, you can effortlessly generate a model with php artisan make:model
ModelName. This command creates a new model le in the “app” directory. The model is an eloquent
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
fi
representation of your database table, allowing seamless interaction between your application and the
database.
Create Model
Generate Model:
Use Artisan to create a model
php artisan make:model Task
De ne the model’s properties and relationships
// app/Models/Task.php
class Task extends Model {
protected $ llable = ['title', 'description'];
}
Create Controller
Generate Controller:
Use Artisan to create a Controller
php artisan make:controller TaskController
De ne actions for handling requests
// app/Http/Controllers/TaskController.php
public function index() {...}
public function create() {...}
Create Views
Create Blade Views:
Develop Blade views for various pages
resources/views/tasks/index.blade.php
resources/views/tasks/create.blade.php
De ne Routes
Set Up Routes:
De ne routes in the web.php le
// routes/web.php
Route::get('/tasks', 'TaskController@index’);
Route::get('/tasks/create', 'TaskController@create');

Introduction to Lumen
Lumen, developed by Laravel, is a microframework tailored for the swift construction of high-performance
microservices and APIs. Its lightweight design ensures faster performance and optimized resource usage
compared to Laravel.
Key Features of Lumen
• Lightweight Design
• Designed to be lightweight and minimalistic.
• Provides essential functionalities in a stripped-down version of Laravel.
• Microservices and API Development
• Geared toward high-speed processing and minimal overhead.
• Speci cally tailored for the development of microservices and APIs.
Installation
Use Composer to install Lumen: composer create-project --prefer-dist laravel/lumen project-name.
Creates a new Lumen project with necessary dependencies.
Environment Con guration
• Store environment-speci c con gurations in the .env le.
• Con gure database and other settings using key–value pairs.
Route De nition
• De ne web routes in routes/web.php and API routes in routes/api.php.
• Segregate routes for better organization.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Controller Generation
• Generate controllers using Artisan’s make:controller command.
• Controllers organize logic and handle incoming requests for web or API routes.
Database Interaction with Eloquent
• Utilize Eloquent, Laravel’s ORM, for database tasks.
• Create models representing database tables, de ning relationships, and data retrieval methods.
Middleware Application
• Apply middleware to routes or groups of routes.
• Perform tasks like authentication, logging, or modifying requests.
Lumen’s Strengths
Lumen’s focus on speed, ef ciency, and scalability positions it as an ideal choice for projects requiring high-
performance microservices and API development. Its seamless integration with Laravel’s ecosystem,
coupled with its lightweight design, makes it a powerful tool for rapid and ef cient web development.
Example: $router->get('/protected', ['middleware' => 'auth', 'uses' => ‘Controller@method']);.

Selecting the Right PHP Framework


Selecting the right PHP framework involves a systematic approach. Begin by clearly de ning project goals,
scope, and essential functionalities. Establish the criteria, such as scalability, security, and community
support, to guide the framework selection process. Assess speci c project requirements, matching them with
the strengths of potential frameworks.
Delve into a comprehensive exploration of available frameworks, considering features, capabilities, and
community feedback. Prioritize functionalities aligned with project objectives, emphasizing those that
directly contribute to success. Test frameworks through experimentation and small prototypes to gain
practical insights into their strengths and limitations. Evaluate factors like ease of implementation,
debugging capabilities, and overall developer experience.
Analyze performance, scalability, and security aspects, considering benchmarks and real-world case studies.
Prioritize frameworks with robust built-in safeguards against vulnerabilities. Additionally, consider
exibility and customization options, ensuring adaptability to project needs. Plan for future growth and
maintenance by choosing a framework that accommodates updates and enhancements.
Future Trends in PHP Framework Development
Future trends in PHP framework development point toward the integration of Arti cial Intelligence (AI) and
Machine Learning (ML) into web applications. This involves PHP frameworks incorporating specialized
libraries for easier AI and ML implementation, revolutionizing user experiences with smarter and
personalized interactions. Security enhancements will focus on automatic data validation and improved
encryption methods to protect against evolving cyber threats. Comprehensive security guides will
accompany PHP frameworks, empowering developers to build secure web applications.
The future of PHP framework development includes adaptation for Progressive Web Apps (PWAs), offering
faster and more engaging web experiences. PHP frameworks aim to create seamless, responsive, and
dynamic web applications, blurring the lines between traditional websites and native applications. Real-time
capabilities will be integrated to meet the demand for applications like live chat, gaming experiences, and
collaborative tools. PHP frameworks will extend support to the Internet of Things (IoT), facilitating real-
time communication between web applications and connected devices.
Furthermore, expect blockchain integration in PHP frameworks for enhanced transparency, security, and
data integrity. Server-Side Rendering (SSR) will play a signi cant role in optimizing website performance
by pre-rendering pages on the server, improving load times and overall responsiveness. A growing trend in
PHP framework development is the emergence of low-code platforms, incorporating user-friendly interfaces
to streamline the development process and make web development more accessible to individuals with
varying coding knowledge.
fl
fi
fi
fi
fi
fi
fi
fi
Introduction to Web Application Pages
A web application encompasses both static and dynamic web pages. Static pages, characterized by xed
content, lack interactivity and are suitable for simpler websites. In contrast, dynamic pages adapt in real
time, responding dynamically to user actions and integrating with databases, providing up-to-the-minute
information for enhanced engagement.
Static pages
• Have xed content.
• Lack interactivity.
• Suited for simple websites.
Dynamic pages
• Adapt in real time.
• Respond dynamically to user actions.
• Integrate with databases.
• Common in applications like E-Commerce sites.
Evolution of Server-Side Scripting
Integral role of server-side scripting
Server-side scripting is integral to dynamic pages, involving embedded scripts executed by the server upon a
client’s request. Server-side scripting languages empower developers to implement logic, handle databases,
and create dynamic pages. The evolution of server-side scripting traces back to C programs in the 1990s,
followed by Perl for CGI applications and Shell scripting.
Evolution timeline
1990s
• C programs.
• Perl for CGI applications.
• Shell scripting.
Late 1990s
• Emergence of PHP, ASP, and JSP.
• Adoption of MVC architecture.
• Evolution with frameworks like Laravel, Django, Flask, and Express.
Client-Side and Server-Side Scripts
Scripts are programs interpreted at runtime, mainly for task automation. They are classi ed into client-side
and server-side scripts.
Client-Side Scripts
• For example, JavaScript.
• Run in the user’s browser.
• Enhance web page presentation and behavior.
• Validate user input in real time.
Server-Side Scripts
• For example, PHP.
• Execute on the web server.
• Manage tasks like processing form data and interacting with databases.
Work ow
In a typical work ow:
• Client requests an HTML page.
• Server-side scripts generate dynamic content.
• Differences include languages, source code visibility, execution environment, performance, and
application examples.
Client-Side Scripting
Client-side scripting, using languages like JavaScript:
• Validates user input in real time.
• Improves user satisfaction.
• Optimizes server resources.
fi
fl
fl
fi
fi
• Instrumental in designing interactive web pages.
Server-Side Scripting Capabilities
Server-side scripting, with languages like PHP:
• Offers exibility in generating custom responses.
• Enables complex data manipulation and calculations.
• Facilitates seamless integration with extensions.
• Ensures scalability and ef ciency.
Web Servers and Their Role
Web servers, whether software applications or hardware devices, utilize HTTP to respond to client requests
over the World Wide Web. They play a crucial role in delivering information and services across the digital
landscape.
Popular Web Servers
• Apache—Known for exibility.
• Nginx—Recognized for high performance.
• Microsoft Internet Information Services (IIS) —Provides a robust platform on Windows servers.
PHP Integration for Dynamic Web Pages
PHP (Hypertext Preprocessor) seamlessly integrates server-side scripting into HTML, facilitating dynamic
web page generation. It is versatile and enables tasks such as dynamic content generation, server le
management, form data processing, database interaction, and data security enhancement.
Database Fundamentals in Backend Technologies
Databases, structured collections of data, are fundamental to backend technologies for ef cient data
management. Relational databases organize data into tables with rows and columns, providing an effective
means of handling complex datasets. Examples of popular relational databases include MySQL,
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. MySQL, an open-source RDBMS, is
widely used in conjunction with PHP, offering platform independence and organized table-based data
storage.
Understanding the dynamics of web pages, server-side scripting, and the role of databases is essential for
building robust and interactive web applications. The evolution of technologies and the integration of
scripting languages continue to shape the landscape of web development.
fl
fl
fi
fi
fi
Introduction to PHP Fundamentals
Variables
In PHP, variables act as containers for storing temporary information. Identi ed by a leading dollar sign ($),
variables store values assigned to them, and their exibility allows dynamic handling of various data types.
When naming variables, adherence to speci c rules ensures clarity and functionality in code, such as starting
with a letter or underscore, and including alphanumeric characters. A variable name cannot use characters
like +, -, %, ( , ), ., and &.
Data Types
Understanding data types is crucial in PHP. Integer types represent whole numbers, double types handle
oating-point numbers, Boolean types have true or false values, NULL signi es the absence of a value,
string captures sequences of characters, arrays store multiple values, and objects encapsulate data and
functions.
Variable Examples

Echo
A PHP script demonstrates the declaration of variables with different data types and their echo outputs. The
echo construct is versatile, displaying variable values, plain text, concatenated strings, HTML integration,
expressions, and Boolean values. Echo contributes to dynamic content generation, making PHP a robust
language for web development.
Display Output: Echo Examples

Variable Concatenation:

Variable Interpolation:

Variable Modi cation:


fl
fi
fi
fl
fi
fi
Constants
Constants in PHP are immutable values de ned using the de ne() function, adopting uppercase characters,
and adhering to variable-naming rules. Constants provide a structured approach for handling unchanging
elements, enhancing code clarity and maintenance.
Constants Examples

Use the Constant in Calculations

Operator Precedence
In PHP, understanding operator precedence and associativity is crucial for crafting effective and error-free
expressions.

PHP Operators
A PHP script demonstrates basic arithmetic operations, conditional operator usage for decision-making,
comparison operators for numeric relationships, logical operators for decision trees, and compound
assignment operators for incremental modi cations.
1.Arithmetic Operations Script:
fi
fi
fi
2.Conditional Operator Script:

3.Comparison Operators Script:

4.Logical Operators Script:

5.Compound Assignment Operators Script:


Control Structures in PHP:
Conditional Statements:
Conditional statements in PHP allow you to execute different blocks of code based on speci ed conditions.
The most common conditional statements are:
• if: Executes a block of code if a speci ed condition is true.
• else: Executes a block of code if the condition in the preceding if statement is false.
• elseif: Allows you to specify multiple conditions to be tested in order.
• switch: Provides a way to handle multiple possible conditions or values in a more structured manner
than multiple if-else statements.

Syntax:

Example

For Switch-Case
fi
fi
Example

Example

Loops
Loops in PHP enable the execution of a block of code repeatedly as long as a certain condition is true. The
main types of loops are:
• for: Executes a block of code a speci ed number of times.
• while: Repeats a block of code as long as a speci ed condition is true.
• do-while: Similar to while, but the block of code is executed at least once, even if the condition is
initially false.
• foreach: Iterates over elements in an array or other iterable data structures.
For Loop
fi
fi
While Loop

Do-While Loop

Examples

Break and Continue Statements


• Break Statement: Used to exit a loop prematurely, before the loop condition becomes false. It is
often used in conjunction with conditional statements to exit a loop based on a certain condition.
·Continue Statement: Skips the rest of the current iteration of a loop and proceeds to the next iteration. It is
useful when you want to skip speci c iterations based on a certain condition without exiting the loop
entirely.

These control structures provide essential tools for managing the ow of execution in PHP programs. They
allow developers to create exible and dynamic scripts by making decisions based on conditions, repeating
code execution with loops, and controlling the ow within loops using break and continue statements.
Functions
In PHP, functions are crucial for modularizing code. There are two main types: system functions (pre-built,
like date, time, and string functions) and custom functions (created by developers for speci c tasks). System
functions enhance code ef ciency, while custom functions improve reusability and readability.
System Functions in PHP: Date function, Date and Time function, String functions.
Date Function: Formats current date and time.

Date and Time Functions: Obtain the current date and timestamp.
fi
fl
fi
fl
fl
fi
String Functions:

Custom Functions in PHP:


Function De nition & Function Call:

Function with Parameters:

Function with Return Value:

Array
In PHP, arrays are fundamental data structures that store and organize elements, each identi ed by an index.
They are versatile, accommodating various data types, and come in two primary types: numeric arrays and
associative arrays.
Numeric Arrays:
Numeric arrays use numerical indices for element access, typically starting from 0. They can be initialized
using either the array() construct or square brackets []. Here is an example:
$array = array("Apple", "Banana", "Orange");
// OR
$array = ["Apple", "Banana", "Orange"];
The count() function determines the array length, and a for loop iterates through the elements, demonstrating
sequential access.
fi
fi
Associative arrays:
Associative arrays use string indices, providing a descriptive way to organize data. They are created using
the array() construct with key–value pairs.

Example

Output - Name: John Doe Age: 25 City: New York Email: john@example.com
Updated Age: 26 Gender: Male Iterating through the array: name: John Doe age: 26 city: New York email:
john@example.com gender: Male
The array $userDetails is populated with user attributes, and values are accessed using speci c keys.
Dynamic modi cations, such as updating the age and introducing a new key–value pair, illustrate the
adaptability of associative arrays.
Errors
Errors in programming can be categorized into different types, such as Syntax Errors, Logical Errors, and
Runtime Errors. Syntax Errors involve violations of programming language syntax rules, while Logical
Errors result from aws in the program’s logic, leading to unexpected outcomes. Runtime Errors occur
during program execution and may include scenarios like attempting to divide by zero or accessing an out-
of-bounds array index, posing challenges during execution.
Exception Handling
Exceptions are events that cause unexpected outcomes in a program, primarily triggered by runtime errors.
Exception handling is a technique used to manage errors effectively, allowing developers to gracefully
handle unexpected situations. PHP provides keywords for exception handling:

Encapsulating potentially error-prone code in the try block, handling speci c exceptions in the catch block,
and executing necessary cleanup in the nally block ensures robust error management. For example, when
fetching data from an external API, a try block can handle successful API calls, while a catch block manages
exceptions like network errors. The nally block ensures that essential cleanup operations are performed.
PHP provides several important exceptions, including:
Exception: The base class that provides common methods and properties for exceptions.
DivisionByZeroError: Used for divide by zero errors.
OutOfBoundsException: Captures index out-of-bound scenarios for arrays.
RunTimeException: A generic exception for various runtime errors.
Example - DivisionByZeroError Exception:
In this example, the code attempts to divide by zero, triggering a DivisionByZeroError exception. The catch
block handles the exception by printing a message, and the nally block is executed regardless of whether an
exception occurred. This demonstrates how exception handling in PHP ensures graceful management of
unexpected scenarios, enhancing program reliability.
fi
fl
fi
fi
fi
fi
fi
Basic Exception Handling

PHP Sessions
In PHP, sessions are a vital mechanism for maintaining stateful interactions between web servers and users,
enabling the persistence of user-speci c data across multiple pages or visits. Sessions facilitate a seamless
and personalized browsing experience by storing information such as user credentials, preferences, and
shopping cart contents. The process begins with a user-initiated login, triggering the server to create a
unique session identi er (sessionid) that links the browser to server-side session data.
The “$_SESSION” superglobal array is a powerful tool for developers, allowing the secure storage and
retrieval of session variables. To initiate a session, “session_start()” is invoked, marking the commencement
of user-speci c data management. The stored session data is maintained on the server, while a session
identi er cookie on the client side ensures the association between the browser and the session.

Storing data within sessions involves simple assignments, like “$_SESSION['user_id'] = 123,” ensuring the
continuity of user details throughout their session.

To conclude a session, “session_destroy()” is utilized, clearing all associated data. PHP sessions provide a
robust foundation for creating dynamic and stateful web applications, enhancing user experiences through
personalized and uninterrupted interactions.

Example
fi
fi
fi
fi
PHP Cookies
Cookies in PHP serve as essential tools for storing small data snippets on a client’s browser, enabling the
preservation of user details across web sessions. This cyclical exchange between the client and server
involves the browser initiating a request, receiving a cookie from the server, and subsequently forwarding it
in future requests. Using the setcookie() function in PHP, developers can customize parameters such as
name, value, expiration time, path, domain, and security options. This customization empowers web
applications to offer personalized experiences, utilizing cookies as ef cient data carriers. Setting a cookie
involves specifying its name, value, expiration time, and optional parameters.
Set and Retrieve Cookie:

Retrieve All Cookies:

Deleting a Cookie:
fi
Form handling in PHP
Form handling in PHP is integral to web development, involving creating HTML forms processed on the
server side using PHP scripts. Web forms enable user interaction by submitting data, with PHP handling this
data on the server, performing processing, and responding to users. Two common methods for sending form
data are the GET and POST methods. The GET method appends encoded user information to the page
request, visible in the URL, while the POST method transfers information via HTTP headers, suitable for
sensitive or binary data.
A practical example demonstrates form handling using HTML and PHP scripts. A basic web form captures
user input, with the PHP script processing the data. The “Input.html” le contains the form, and when
submitted, the data is sent to “Welcome.php” using either the GET or POST method. The PHP script
retrieves the values and generates a welcome message displayed on the web page. This exempli es the
fundamental role of PHP in handling user input for interactive web applications.
PHP Forms: GET Method
Input.html

PHP Forms: POST Method


Input.html
fi
fi
PHP File Inclusion
PHP’s le inclusion features, accomplished through include() and require() functions, facilitate modular
code creation. The include() function allows the evaluation of another le within the current script, fostering
code reusability, while issues during inclusion generate warnings. In contrast, the require() function, with
similar syntax, halts script execution upon issues, providing a robust approach to modularizing code.

MySQL in Web Development: A Foundation for Ef ciency


MySQL, a popular relational database management system, plays a pivotal role in web development,
powering numerous applications with its ef ciency and exibility. Structured Query Language (SQL) is the
language employed to interact with MySQL databases, providing a standardized means to manage and
retrieve data.
Creating and Structuring Databases and Tables
Create a Database: CREATE DATABASE mydatabase;
Create a Table:

Insert Data into the Table:


INSERT INTO users (id, username, email, birthdate) VALUES
(1, 'JohnDoe', 'john.doe@example.com', '1990-05-15'),
(2, 'JaneSmith', 'jane.smith@example.com', '1985-09-22');
fi
fi
fi
fl
fi
Fundamental SQL Commands for Data Manipulation
Retrieving Speci c Data
The SELECT command is fundamental, enabling the retrieval of speci c data from a database. With
SELECT, one can de ne conditions, sorting preferences, and projections, tailoring the output to meet precise
requirements.
SELECT username, email FROM users WHERE birthdate > '1990-01-01';
Updating Existing Data
The UPDATE command facilitates the modi cation of existing data within a database. It allows changes to
be applied selectively based on speci ed conditions.
UPDATE users SET birthdate = '1992-03-20' WHERE username = 'JaneSmith';
Connecting PHP to MySQL: A Vital Integration
Connecting PHP with a MySQL database involves using extensions like MySQLi or PDO. The
mysqli_connect function establishes a connection by specifying host, username, password, and database
name. After connecting, mysqli_select_db selects the desired database. It is crucial to close the connection
with mysqli_close when done.
Opening a Connection

CRUD Operations in PHP: Managing Data Effectively


CRUD operations on a database involve creating, reading, updating, and deleting data. Creating a database
requires connecting, formulating an SQL query, executing it, and closing the connection. An example creates
a database named “EmployeeDB.”
Creating a Database in PHP

Creating a Table in PHP


fi
fi
fi
fi
fi
Creating a table involves specifying columns, data types, and constraints. Executing the SQL query creates
the “Employee” table.

Inserting Data in PHP


Inserting data uses the INSERT INTO query, adding a new record to the “Employee” table.

Reading Data in PHP


Reading data involves the SELECT * FROM query, fetching and echoing records from the “Employee”
table.
Updating Data in PHP
Updating data uses the UPDATE query, modifying records based on a condition.

Deleting Data in PHP


Deleting data uses the DELETE FROM query, removing records based on a condition.

Understanding the foundational SQL commands and PHP-MySQL integration is crucial for effective data
management and manipulation in web development.
Data Serialization Formats in Web Programming
Data serialization formats in web programming are crucial for organizing and exchanging computer data,
especially in the face of diverse hardware architectures and operating systems. The challenge arises when
data needs to be transferred between systems with inherent differences, such as Windows to Unix or between
Java and .NET applications with varying data types. The solution lies in platform-and-language-neutral data
serialization formats like JSON and XML, acting as a common language for universal comprehension and
interaction.
Serialization involves transforming structured data into a byte stream for ef cient storage, transmission, or
network transfer, while deserialization reverses this process to reconstruct the original data object. These
processes are fundamental in modern software development, facilitating tasks like data storage, network
communication, and ef cient data manipulation. Serialized data nds its home in les and databases. Files
on disks allow data retention even when applications are inactive, while databases support ef cient storage
and retrieval of serialized objects. Popular text-based serialization formats include XML, known for its
hierarchical structure, and JSON, valued for its simplicity in web development and APIs.
Choosing the Right Serialization Format
Choosing the right serialization format depends on factors like data complexity, human readability, speed,
and storage space constraints. Formats like XML and YAML suit complex data hierarchies, while JSON and
CSV are preferred for simplicity and speed. The decision ultimately hinges on the speci c requirements of
the application at hand.
Common Serialization Formats
XML (eXtensible Markup Language)
XML, or eXtensible Markup Language, is a versatile meta-language for storing and transferring data.
Utilizing tags similar to HTML, XML enables users to de ne their tags, attributes, and hierarchies, offering
exibility for the structured representation of data. It nds primary use in storing and exchanging structured
data between systems and applications, excelling in readability for humans and machines. XML
accommodates highly structured data common in databases and loosely structured content like letters or
articles, showcasing its adaptability.
The need for XML arises from the limitations of HTML, which has a xed set of tags and lacks restrictions
on tag arrangement. XML addresses these issues by allowing users to de ne their tags, attributes, and
hierarchies, providing a customized and structured language suitable for various data representations. It
imposes rules for clear and unambiguous data structure, making it ideal for organizing diverse types of
information without the constraints of prede ned HTML tags.
JSON (JavaScript Object Notation)
JSON (JavaScript Object Notation) is a widely used data format known for its simplicity, making it both
human-readable and machine-understandable. Its concise and straightforward structure facilitates easy
readability and manipulation, particularly in web development, data exchange, and communication between
systems. JSON’s compatibility, ef ciency, and support across various programming languages contribute to
its prevalence in modern web and application architectures.
YAML (YAML Ain’t Markup Language)
YAML, humorously standing for "YAML Ain't Markup Language," is a robust tool for data serialization and
con guration les. Serving as a superset of JSON, YAML extends capabilities while maintaining
compatibility. Its human-friendly syntax enhances readability, supporting a wider range of complex data
types for intricate data representations. YAML allows comments within data, aiding documentation and
maintainability, and its les can be manually modi ed while retaining structure and readability.
Use Cases for Each Format
Utility and use cases for XML, JSON, and YAML:
• XML: Well-suited for structured document storage, making it an ideal choice when dealing with
documents that require a strict hierarchical structure and prede ned tags to represent data elements.
• JSON: Primarily used in web APIs and for data interchange between servers and clients due to its
lightweight, readable, and straightforward format, facilitating seamless data transmission.
• YAML: Preferable for con guration les and human-readable data representations where
conciseness and readability are crucial. YAML’s succinct yet clear syntax makes it advantageous for
con guration settings and serializing complex but easily understandable data structures.
Each format excels in different scenarios, providing distinct advantages based on the speci c requirements
of the application or system at hand.
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Introduction to XML
XML, or Extensible Markup Language, is a versatile structured data format designed for both human
understanding and computer processing. Its strength is handling semi-structured data, making it suitable for
diverse applications. XML’s exibility allows users to create custom tags, accommodating various data types
such as web content, con guration settings, or structured documents. For instance, in a library system, XML
tags can represent book details like titles, authors, and publication dates, ensuring clear organization.
XML Document Structure
XML documents follow speci cations outlined in XML, identi ed by the .xml le extension. These
documents use tags and attributes to create a hierarchical tree-like structure, ensuring consistency and
clarity. The fundamental structure includes a single root element encompassing all others, facilitating
ef cient interpretation by both humans and machines. The core building block of an XML document is the
XML element, de ned by opening and closing tags. These elements encapsulate content, forming the basic
organizational format of XML. Attributes within XML elements provide additional details or metadata,
contributing to a more detailed representation of data.
Example XML Document
XML document that describes information about a baseball player

XML documents are portable and can be viewed and edited using text editors. Web browsers can display
XML in a formatted manner, but specialized software, called an XML parser, is needed to process XML
documents. The parser veri es adherence to rules such as a single root element, proper start and end tags,
and correct nesting, ensuring the integrity of XML documents.
XML for Complex Structures - XML Nesting
XML supports nesting, allowing the creation of complex structures. For example, a library system could
have a root element “library” containing nested “book” elements, each with details like title, author, and
publication year, showcasing XML’s ability to represent intricate data relationships.
Part-I
fi
fi
fi
fi
fl
fi
fi
fi
Part-II

XML Validation
XML validation is essential for ensuring the reliability and integrity of XML documents, serving several
crucial purposes. First and foremost, it ensures well-formedness by checking syntax rules and verifying
proper tags, nesting, attributes, and closing structures. This adherence to syntax rules is vital for the
document to be considered well-formed according to XML speci cations. Validation also ensures that XML
documents adhere to a prede ned structure or schema. Schemas de ne rules for elements, attributes, data
types, and their relationships. Validating against a schema ensures consistency and conformity to these
guidelines, promoting data integrity and accuracy. This is crucial for maintaining compatibility between
different systems, as standardized XML documents can be easily exchanged and interpreted without
compatibility issues.
Moreover, XML validation helps catch errors early in the development process. By detecting issues during
development, developers can debug and rectify problems before they impact production environments,
enhancing the overall reliability of XML-based systems. A well-formed XML document must adhere to
syntax rules, including having a single root element, matching opening and closing tags, case sensitivity,
proper nesting, and quoted attribute values. Validation plays a crucial role in ensuring that these
requirements are met. Various methods are employed for XML validation, including Document Type
De nition (DTD), XML Schema De nition (XSD), and Relax NG. These schema languages de ne the
structure and constraints of XML documents, enabling thorough validation.
XML Validation Tools
Several tools facilitate XML validation, offering different approaches to developers. Online validators like
XMLLint provide web-based validation services, command-line tools like xmllint offer validation through
terminals for automation, and Integrated Development Environments (IDEs) like XMLSpy or Oxygen XML
Editor integrate comprehensive XML validation tools, enhancing the overall XML development experience.
These tools contribute to accurate and standards-compliant XML creation and management by checking
syntax, validating against speci c schemas, and detecting errors.
Check whether the XML document is well-formed.
fi
fi
fi
fi
fi
fi
fi
The XML document is NOT WELL FORMED!
<city> element is not closed properly
<root> element is not closed
XML Schema (XSD)
XML Schema, also known as XML Schema De nition (XSD), serves dual purposes in handling XML data.
Firstly, it describes the structure and content of an XML document, outlining elements, attributes, and their
relationships. Secondly, it validates XML documents against prede ned rules, acting as a blueprint for
elements, attributes, data types, and constraints. The schema de nes elements, attributes, and data types,
allowing the speci cation of allowed values and constraints. This detailed description of XML documents
promotes data integrity, consistency, and conformity to prede ned guidelines. XML Schemas nd extensive
use in scenarios requiring data exchange between different systems, preventing inconsistencies and errors by
enforcing prede ned constraints.
XML Schema ensures the well-formedness of XML documents by describing their syntax, including proper
nesting, correct tag structures, and case sensitivity. When an XML document complies with an XML
Schema, it is termed “Valid,” meeting both syntax and structural constraints. Elements, the fundamental
building blocks of XML documents, are de ned in XML Schema using the xs:element tag.
<xs:element name = "x" type = "y"/>
This tag, part of the XML Schema namespace (xs), speci es the name and type of the element, forming the
blueprint for its structure.
XML Schema supports two main types of element de nitions: simple and complex. Simple types are
associated with primitive data types like integers or strings, while complex types act as containers for other
element de nitions, providing structured hierarchies within XML documents.
Prede ned Simple Types
xs:integer
xs:Boolean
xs:string
xs:date
Example: <xs:element name = "phone_number" type = "xs:int" />
A practical example of a complex type in XML Schema is illustrated, showcasing the de nition of a
“Contact” element with child elements like name, company, and phone. This structure ensures speci c order
and types for child elements within the “Contact” element.
Complex Type Example
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Global Types
Global types in XML Schema allow the creation of types that can be referenced throughout the entire
schema, ensuring consistency and reusability. For instance, a global type called “AddressType” can be
de ned, and various elements can reference this global type, promoting uniformity and simplifying
maintenance.
Global Type Example

The concept of global types is further demonstrated in an example where “AddressType” is de ned globally
and referenced by elements “Address1”and “Address2.” This approach enables consistent structuring across
different sections of the XML document and facilitates maintenance.
XML Tree Structure
An XML tree structure, inherent in XML documents, organizes data hierarchically through parent–child
relationships. It maintains order and relationships among elements, allowing nesting for a clear
representation. Elements, enclosed in tags, represent entities, while attributes offer additional details. This
structure is exempli ed in a bookstore scenario, where each book has attributes like category. The XML tree
is then utilized to create an XML Schema. The schema de nes elements, types, and constraints, ensuring a
fi
fi
fi
fi
standardized structure. In the provided XML Schema for a bookstore, it speci es the “bookstore” element
with a complex type, including elements like “title,” “author,” “year,” and “price” with de ned types and
constraints. This schema guides the creation of XML documents adhering to the de ned structure.
Create an XML document for the following tree structure.

Create XML schema for the tree structure.


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
fi
fi
fi
XML in Web Applications
XML plays a pivotal role in web programming, with RSS News Feeds being a prominent application. RSS,
based on XML, standardizes content distribution, enabling users to subscribe to and aggregate updates from
diverse sources. Major news outlets utilize RSS feeds, demonstrating XML’s role in seamless data exchange.
An example RSS feed in XML format illustrates its structured components, such as title, link, and
description, facilitating content consumption. In National Weather Web Services, XML is employed for
weather data exchange. SOAP communicates XML-formatted weather information to client applications.
The National Digital Forecast Database exempli es this, providing up-to-date weather forecasts through
XML responses. A snippet of XML from the National Weather Service show cases digital weather markup
language (DWML), detailing weather forecasts for a location with elements like temperature, providing a
structured format for extracting weather-related data in web programming.
fi
Introduction to JSON
JSON (JavaScript Object Notation) has become a cornerstone in web development for data interchange due
to its simplicity and exibility. Its human and machine readability, compact text format, availability of
libraries in various programming languages, and platform independence contribute to its widespread
adoption in web-based APIs.
JSON Syntax and Data Types
JSON closely aligns with JavaScript, primarily consisting of key–value pairs organized in objects and
arrays. This structure allows it to represent complex data hierarchies ef ciently. JSON supports fundamental
data types like strings, numbers, objects, arrays, Booleans, and null, making it versatile for data interchange
between different systems and programming languages. While JSON has its de ned set of data types, it does
not directly support functions, dates, or unde ned values. Instead, types when serializing data, these are
typically converted or represented within the permitted JSON data. Examples illustrate the representation of
various data types in JSON, showcasing its applicability and simplicity in organizing and exchanging data.
JSON Structure

Example—Data Types in JSON

Creating JSON Objects and Arrays


JSON Arrays
JSON is a lightweight data interchange format that utilizes key–value pairs within objects and ordered lists
within arrays. Objects are enclosed in curly braces {} and consist of key–value pairs separated by commas,
where keys are strings and values can be any valid JSON data type. JSON is extensively used in web
development, especially in web APIs, con guration les, and NoSQL databases like MongoDB, providing a
versatile and schema-less approach to data storage. JSON objects are fundamental for representing
fl
fi
fi
fi
fi
fi
structured data, such as employee details. JSON arrays, enclosed in square brackets [ ], hold ordered lists of
values, accommodating various data types. Arrays nd applications in API responses, frontend development
for displaying lists, con guration les, log entries, database query results, and more, offering exibility and
versatility in representing dynamic data structures. Arrays can also be nested within objects or other arrays,
enabling the representation of complex and hierarchical data.
Example of a JSON array containing employee data:
In this JSON structure:
The main object contains a key “employees,” and its associated value is an array enclosed in square brackets
[].
Within the array, there are two objects representing employee data.
Each employee object contains keys for “id,” “name,” and “location,” with their respective values.
This structure represents a list of employees, where each employee object contains details such as their ID,
name, and location within the USA.
Array of employees

Nested JSON
Nested JSON, or JSON nesting, involves incorporating one JSON object as a value within another JSON
object or including JSON arrays within other JSON arrays, creating a hierarchical or nested structure. This
approach is employed to represent complex and structured data relationships. Use cases for nested JSON
include structured data representation, where hierarchical relationships like organizational charts or tree
structures are involved. APIs often return nested JSON structures to provide comprehensive information
about a resource, including nested details about pro les, preferences, or related entities. Con guration les
for applications may use nested JSON to represent various settings with sections or categories containing
further details. In document databases like MongoDB, nested JSON-like structures allow for exible and
nested data models. In front-end development, nested JSON is frequently used to represent complex data
structures, especially when dealing with nested components or hierarchical data in user interfaces.
In this example:
• The JSON structure contains an object with a key “artists” whose value is an array of artists.
• An object represents each artist within the “artists” array.
• The “Deep Purple” artist object includes the keys “artistname,” “formed,” and “albums.”
• The “albums” key holds an array of album objects for that particular artist.
• Each album object contains details such as “albumname,” “year,” and “genre.”
This demonstrates a nested JSON structure where an array of artists contains multiple albums, showcasing
the relationship between artists and their albums.
fi
fi
fi
fi
fi
fl
fl
fi
JSON Parsing in JavaScript
In web development, converting JavaScript objects to JSON and vice versa is essential for various purposes.
JSON parsing plays a crucial role in scenarios such as data interchange, facilitating lightweight information
exchange between servers and web applications. It is integral for ef cient data transmission between clients
and serv, ensuring structured and quick transfers. APIs widely employ JSON for effective communication
between different systems due to its human-readable format. JSON also nds extensive use in storing and
persisting data in databases, offering exibility for complex data structures. Additionally, JSON parsing is
crucial for securely handling data from external sources, preventing potential security vulnerabilities.
To convert a JSON string to a JavaScript object, the JSON.parse() method is employed in JavaScript. This
process is vital when handling data from external sources like APIs or les, enabling effective interaction
and manipulation of the received data.
Example JSON Parsing—Parse JSON string to JavaScript object
let jsonString = '{"name": "Shreyas", "age": 40}';
let jsObject = JSON.parse(jsonString);
console.log(jsObject);

Conversely, the JSON.stringify() method is used to convert a JavaScript object to a JSON string, crucial for
scenarios such as data transmission or storage. This method ensures the representation of data in a
standardized JSON format, allowing seamless sharing across different systems or APIs.
Convert JavaScript object to JSON string
let jsPerson = { name: "Shreyas", age: 40 };
let jsonString = JSON.stringify(jsPerson);
console.log(jsonString);

Creating a JSON Document


Creating a JSON document for an online bookstore system’s order processing is vital for ef cient data
exchange. The process involves several steps:
• Identify the Scenario: Understand the data scenario, including entities, attributes, and relationships.
fl
fi
fi
fi
fi
• De ne the Structure: Based on identi ed entities, de ne the JSON document’s overall structure,
considering objects, arrays, and values.
• Use a Text Editor: Open a text editor to write and save the JSON document.
• Start with an Object or Array: Choose between an object or array as the top-level structure,
depending on whether it represents a single entity or a collection.
• Add Key–Value Pairs: Include key–value pairs for each entity or attribute, adhering to JSON’s strict
rules.
• Handle Nested Structures: Represent nested structures clearly, maintaining proper indentation for
clarity.
• Validate JSON Syntax: Ensure correct formatting using an online JSON validator or a text editor
tool.
• Save the Document: Save the JSON document with a .json le extension or embed it in relevant
code/con guration les.
The example represents an order with customer details, items, and total cost. De ne the Structure: The
“order” object includes key–value pairs for order number, date, customer details, order items, and total
amount. Elements like order number, date, customer details (name, email, address), order item details (book
title, author, quantity, price), and total amount are integral to the JSON structure.
For the Customer—First name, Last name, Email, and Address.
For Order Item—BookId, Title, Author, Quantity, Price.
Example JSON Document for an Online Bookstore

This structured JSON representation ensures seamless order processing and effective integration with the
online bookstore system.
JSON in Web Programming
JSON plays a pivotal role in various web programming applications, notably in utilizing the Twitter API and
Google Maps integration. In the Twitter API, developers extract data in JSON format, including tweets, user
fi
fi
fi
fi
fi
fi
fi
pro les, search results, trends, and hashtags. This data enhances website interactivity, enabling features like
live tweet feeds and personalized user experiences. In the realm of Google Maps, JSON facilitates the visual
representation of geographical data through markers. These graphical icons, placed on the map, signify
speci c locations and offer animation effects, ensuring a seamless experience across both mobile and
desktop devices.
Moreover, JSON serves a crucial function in web applications by facilitating communication between the
user interface (UI) and backend server. It de nes the request and response format, with the UI sending
JSON-formatted requests for user interactions, and the backend responding in JSON with requested data or
action acknowledgments. API endpoints, asynchronous communication, and the exibility of JSON
contribute to the ef ciency of data exchange in modern web applications.

Introduction to YAML
YAML, a human-readable data serialization format, relies on indentation, key–value pairs, and sequences for
its syntax. It is commonly used in web programming for its readability and simplicity, particularly in
scenarios where human interaction is required, such as con guration les. YAML supports comments,
mapping (key–value pairs), and sequences (lists/arrays). Its sensitivity to spaces, case, and emphasis on
indentation for structure is noteworthy.
YAML Syntax Examples
Comment
# This is a comment
person:
name: John Doe # Inline comment
age: 30
Mapping (Key–Value Pairs)

YAML in Web Applications


YAML is crucial for communication between UI and backend servers in web applications, de ning request
and response formats in JSON-like structures. YAML’s readability is exempli ed in con guration les,
allowing easy editing and adjustments. Additionally, YAML excels in serializing complex data structures
with its structured approach, simplifying the representation of intricate information. Ansible, a popular
con guration management tool, employs YAML for expressing playbooks, showcasing its versatility in
orchestration.
YAML in Con guration Files
# Web Application Con guration
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
fi
YAML in Data
# Sample YAML Data

Hierarchy: YAML Supports Nested Structures


# Sample YAML with Nested Structures

YAML in Ansible
Ansible, a popular con guration management tool, employs YAML for expressing playbooks. YAML’s
versatility in orchestrating tasks and de ning con gurations makes it well-suited for Ansible’s use case.
Playbooks written in YAML provide a concise and readable way to describe automation tasks in Ansible.

YAML vs. JSON and XML


Compared to JSON, YAML is more human-readable and succinct, offering a human-friendly syntax. In
contrast to XML, YAML is less verbose, emphasizing simplicity and readability. YAML’s use of indentation
for hierarchy makes it an intuitive choice in scenarios requiring clear and organized representation of data
structures.
fi
fi
fi
Execution Environment
A browser displays an HTML document in a window on the screen of the client. The JavaScript Window
object represents the window that displays the document. All JavaScript variables are properties of some
object and the JavaScript Document object represents the displayed HTML document. Every Window object
has a property named Document. This is a reference to the Document object that the window displays. The
Document object is used more often than any other object in client-side JavaScript. Every Document object
has a forms array. Each forms array element has an elements array as a property. The elements represent the
HTML form elements, such as buttons and menus.
Critical Rendering Path
The critical rendering path is the sequence of steps the browser goes through to convert the HTML, CSS,
and JavaScript into pixels on the screen. Optimizing the critical render path improves render performance.
The critical rendering path includes the Document Object Model (DOM), CSS Object Model (CSSOM),
render tree, and layout.

Source: https://gist.github.com/gopal1996/de0b218253fcf8c9634bd8029d14eaf4
A request for a web page or app starts with an HTML request. The server returns the HTML response
headers and data. The browser then begins parsing the HTML, converting the received bytes to the DOM
tree. The browser initiates requests every time it nds links to external resources, be it stylesheets, scripts, or
embedded image references. Some requests are blocking, which means the parsing of the rest of the HTML
is halted until the imported asset is handled. The browser continues to parse the HTML, making requests and
building the DOM, until it gets to the end, at which point it constructs the CSS object model. With the DOM
and CSSOM completion, the browser builds the render tree, computing the styles for all the visible content.
After the render tree is complete, layout occurs, de ning the location and size of all the render tree elements.
Once complete, the page is rendered or “painted” on the screen.
We can improve page load speed by prioritizing which resources get loaded, controlling the order in which
they are loaded, and reducing the le sizes of those resources.

<script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags. You can place any number of
scripts in an HTML document. When including JavaScript code in an HTML document, one important
consideration is the placement of the script tags. Scripts can be placed in the <body>, the <head> section of
an HTML page, or both. The browser parses the HTML document from top to bottom. As it encounters the
scripts in the <head> section, the rest of the DOM element creations will be paused for the scripts to
download and execute. To solve the issue, it was recommended to place script tags at the bottom of the
HTML document, just before the closing </body> tag. It will ensure that all the DOM elements are
constructed and ready before we download and execute the scripts.
HTML provides the async and defer attributes to load the page faster and minimize the larger script loading
lag by downloading them in the background. The defer attribute tells the browser not to wait for the script.
Scripts with defer always execute when the DOM is ready. The async attribute means that a script is
completely independent and the browser does not block async scripts. Async scripts load in the background
and run when ready. The defer and async attributes are ignored if the <script> tag has no src.
fi
fi
fi
In practice, defer is used for scripts that need the whole DOM and/or their relative execution order is
important. async is used for independent scripts like ads. Their relative execution order does not matter.
Repaint and Re ow
Repaint occurs when changes are made to the appearance of the elements that change the visibility but do
not affect the layout.
• Visibility
• Background color
• Outline
Re ow means re-calculating the positions and geometries of elements in the document. Re ow happens
when changes are made to the elements that affect the layout of the partial or whole page.
• Resizing the window
• Changing the font
• Adding or removing a stylesheet
• Content changes, such as a user typing text in an input box
Example:

Document Object Model (DOM)


In the JavaScript binding to the DOM, the elements of a document are objects.
• Data: Properties
• Operations: Methods
Example:

A DOM tree is made up of individual components called nodes. The main node, from which every other
node springs, is called the document node. The node under the document node is the root element node. The
DOM has several different types of nodes:
• Document node: At the top of the hierarchy is the document node, representing the entire document.
• Element nodes: HTML elements like <div>, <p>, <h1>, etc., are represented as element nodes in the
DOM.
• Attribute nodes: Attributes of elements are represented as attribute nodes.
• Text nodes: The actual text content within elements is represented as text nodes.
• Comment nodes: The HTML comments in a document.
Some key points about the tree:
• Every node, except the root node, has one parent.
• Each node may have any number of children.
• Nodes with the same parent are siblings.
fl
fl
fl
Parent, child, and sibling relationship in an HTML document
<html>
<head>
<title>The HTML Family</title>
</head>
<body>
<section> <! I am a parent of 3 p elements, child of body >
<p>First</p> <! 1st child and sibling of 2 p elements >
<p>Second</p> <! 2nd p child and sibling of 2 p elements >
<p>Third</p> <! 3rd p child and sibling of 2 p elements >
</section>
</body>
</html>
The HTML DOM also provides a couple of keywords for navigating nodes using their positions relative to
their siblings or parents.
• The parentNode property returns the parent node of an element or node.
• The childNodes property returns a collection (list) of an elements’s child nodes.
• The nextSibling property returns the next node on the same tree level.
• The previousSibling property returns the previous node on the same tree level.
• The rstChild property returns the rst child node of a node.
• The lastChild property returns the last child node of a node.
Example:

Complex structures can be created and manipulated within the DOM by using properties and methods for
working with HTML documents. Listed below are a few of them:
• Cookie: This property gets or sets the name/value pairs of cookies in the document
• Doctype: This property gets the Document Type Declaration associated with the document
• documentElement: This property gets the element that is the root of the document
• links: This property gets a collection of all and elements in the document that contain the href
attribute
• createElement(): Creates a new element node
• addEventListener(): Assigns an event handler to the document
• appendChild(): Inserts a new child node to the element (as a last child node)
• cloneNode(): Clones the element
• click(): Replicates a mouse click on the element
fi









fi








Example:

DOM: Accessing Elements


• getElementById: Retrieves an element by its unique ID.
• getElementsByClassName: Retrieves elements by their class name.
• getElementsByTagName: Retrieves elements by their tag name.
• querySelector and querySelectorAll: Use CSS selectors to select elements.

Event Handling
Events are the things that happen within the browser (such as page loading) and things the user does (such as
clicking, pressing keys on the keyboard, and moving the mouse). The HTML DOM gives JavaScript the
ability to identify and respond to events in a web browser. When JavaScript does something in response to
these events, it is called event handling. The addEventListener method listens for events on any DOM node
and triggers actions based on those events.
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever
the speci ed event is delivered to the target.
Example:

Event delegation is a useful pattern that allows you to write cleaner code and create fewer event listeners
with similar logic. Capturing and bubbling allow us to implement one of the most powerful event handling
patterns called event delegation. This is useful for dynamically generated content. The idea is that if we have
a lot of elements handled in a similar way, then instead of assigning a handler to each of them, we put a
single handler on their common ancestor.
Manipulating Style Example:

DOM Asynchronous Operations:


When working with asynchronous operations, such as fetching data, the DOM can be updated dynamically
when the data becomes available
fi
DOM: Dynamic Content and Templating
Libraries can be used for dynamic content generation and rendering
• Handlebars
• Mustache
• Template literals

Self-Study
• Study the topics covered in this document in detail from the links shared in the references.
• Practice codes using DOM
Event-driven programming is a method of programming in which the ow of the program is determined by
events that occur. An event is a noti cation that something speci c has occurred in the browser. Following
are a few events:
• abort: The loading of a le is aborted
• change: An element value has changed since losing and regaining focus
• click: A mouse has been clicked on an element
• dbclick: A mouse has been clicked twice on an element
• keydown: A key is pressed down
• keyup: A key is released after being pressed
• mousewheel: A wheel button of a mouse is rotated
• submit: A form is submitted
• blur: An element has gone out of focus
• scroll: The document or an element has been scrolled
• unload: The document or included le is being unloaded
Inline Event Handler
The rst system for handling events was introduced along with the rst versions of JavaScript. The inline
event handler attributes are formed by adding the pre x to an event. To use them, add the event attribute to
an HTML element. When the speci ed event occurs, the JavaScript within the value of the attribute will be
performed.
Example:
<a href="homepage.html" onclick="alert('Home page!');"> Home </a>
If you put this markup into an HTML document and click the link, you see an alert window with the words
“Home page!”.
HTML4 de ned a collection of events that browsers implement. JavaScript can deal with these events.
These events are associated with HTML tag attributes. Tag attributes are used to connect the events to
handler.
The addEventListener method listens for events on any DOM node and triggers actions based on those
events. When the function speci ed as an action for the event runs, it automatically receives a single
argument, the Event object.
Example:

When elements are nested, it is important to know which one will happen rst. The outer element is
clickable, but so is the inner element. When you click on the inner element, should the event attached to the
outer element happen rst, or should the event attached to the inner element happen rst?
The most common way for events to be handled in a situation like this is called bubbling up. Events on the
inside-most element happen rst and then bubble up to the outermost elements. To use the bubble-up
method, set the last argument of the addEventListener() method to false, which is also the default value. The
other way to handle this scenario is called the capture method. In capture mode, the outermost events
happen rst, and the innermost events happen last.
Example:
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
Use preventDefault method of the event object to prevent the default behavior associated with an event; for
example, preventing the default action of a form submission.

Event delegation in JavaScript is a pattern that ef ciently handles events. Events can be added to a parent
element instead of adding to every single element. It refers to the process of using event propagation
(bubbling) to handle events at a higher level in the DOM than the element on which the event originated.
Cookies are data, stored in small text les, on your computer. JavaScript can create, read, and delete cookies
with the document.cookie property. You can also add an expiry date. By default, the cookie is deleted when
the browser is closed.
Example:
document.cookie = "username=Tine Jones; expires=Thu, 18 Jan 2024 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie
belongs to the current page.
Example:
document.cookie = "username=Tina Jones; expires=Thu, 18 Jan 2024 12:00:00 UTC;
path=/";
First, we create a function that stores the name of the visitor in a cookie variable. The parameters of the
function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days
until the cookie should expire (exdays).
Example:

We can create a function that returns the value of a speci ed cookie. It takes the cookiename as parameter
(cname).
Example:
fi
fi
fi
Deleting a cookie is very simple. You do not have to specify a cookie value when you delete a cookie. Just
set the expires parameter to a past date:
Example:

Self-Study
• Study the topics covered in this document in detail from the links shared in the references.
• Practice codes using event handling and cookies
JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive.
JavaScript can be connected to the objects of its environment to provide programmatic control over them.
JavaScript is case-sensitive and uses the Unicode character set.
Variables
Variables are symbolic names for values used in an application. The names of variables, called identi ers,
conform to certain rules. A JavaScript identi er usually starts with a letter, underscore (_), or dollar sign ($).
Subsequent characters can also be digits (0–9). Because JavaScript is case-sensitive, letters include the
characters A through Z (uppercase) as well as a through z (lowercase).
Let x = 2;
In a statement like let x = 2, the let x part is called a declaration, and the = 2 part is called an initializer. A
variable may belong to one of the following scopes:
• Global scope: The default scope for all code running in script mode.
• Module scope: The scope for code running in module mode.
• Function scope: The scope created with a function.
In addition, variables declared with let or const can belong to an additional scope:
• Block scope: The scope created with a pair of curly braces (a block).
You can create a read-only, named constant with the const keyword. A constant cannot change value through
assignment or be re-declared while the script is running.
const a = 10;
Data Types
• Seven primitive datatypes are as follows:
• Boolean: A variable can have a value as true or false.
• Null: A special keyword used to denote a null value.
• Unde ned: Can be used when the value is not de ned.
• Number: It represents an integer or a oating-point number, for example, 2 or 3.59.
• BigInt: An integer with arbitrary precision, for example, 9007199254740992n.
• String: A sequence of characters that represent a text value, for example, "Hello".
• Symbol: A data type whose instances are unique and immutable.
Statements
The most basic statement is a block statement, which is used to group statements. The block is delimited by
a pair of curly braces:
{
statement1;
statement2;
// …
statementN;
}
A conditional statement is a set of commands that executes if a speci ed condition is true. JavaScript
supports two conditional statements: if...else and switch.
if statement will execute a statement if a logical condition is true, and the optional else clause can be used to
execute a statement if the condition is false.
if (condition) {
statement1;
} else {
statement2;
}
In case, we need to check for multiple conditions, we can use multi-level if. In this case, only the rst logical
condition, which evaluates to true, will be executed.
if (condition1) {
fi
fl
fi
fi
fi
fi
fi
statement1;
} else if (condition2) {
statement2;
} else if (conditionN) {
statementN;
} else {
statementLast;
}
A switch statement allows a program to evaluate an expression and attempt to match the expression's value
to a case label. If a match is found, the program executes the associated statement.
switch (expression) {
case label1:
statements1;
break;
case label2:
statements2;
break;
// …
default:
statementsDefault;
}
The optional break statement associated with each case clause to ensure that the program breaks out of
switch once the matched case is executed, and then continues execution from the statement following
switch. If break is missing, the program executes the matched case and the following cases.
Loops offer a quick and easy way to do something repeatedly.
A “for” loop repeats until a speci ed condition evaluates to false.
for (initialization; condition; afterthought)
statement
The “do...while” statement repeats until a speci ed condition evaluates to false.
do
statement
while (condition);
A “while” statement executes its statements as long as a speci ed condition evaluates to true.
while (condition)
statement
Self-Study
• Study the topics covered in this document in detail from the links shared in the references.
• Practice questions for loops and conditional statements.

Objects are variables too. But objects can hold multiple values. The values are written as name: value pairs.
You can create an object using an object initializer.
const obj = {
property1: value1, // property name may be an identi er
fi
fi
fi
fi
2: value2, // or a number
"property n": value3, // or a string
};
var person = { rstName:"Kala",
lastName:"Tiwari",
age:40,
eyeColor:"black"}
You can access a property of an object by its property name.
objectName.property // person.age
or
objectName["property"] // person["age"]
We can also use constructor functions. For this, rst de ne the object type by writing a constructor function,
then create an instance of the object with new.
function Person(name) {
this.name = name;
this.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
}
let person1 = new Person('Bob');
let person2 = new Person('Sarah');
In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same
properties. Only comparing the same object reference with itself yields true.
Example:
const name1 = { name: "Rita" };
const name2 = { name: "Rita" };
name1 == name2; // return false
name1 === name2; // return false
The temporary objects created when you access a property/methods of a string, number, or Boolean are
known as wrapper objects. JavaScript allows us to work with primitives (strings, numbers, etc.) as if they
were objects using these wrapper objects.
var name = 'Tina';
console.log(name.length);//prints 4
console.log(name.toUpperCase()); //prints TINA
typeof 'Tina' //string
Javascript detects that you are trying to access a property of a string primitive. It creates a wrapper object
String to wrap the original string primitive. It accesses the length and toUpperCase on the wrapper object
instead of the original primitive. It discards the wrapper object, frees the memory, and continues.
In JavaScript, an object can inherit properties of another object. The object from where the properties are
inherited is called the prototype. When we try to access a property of an object, the property is not only
searched in the object itself. It is also searched in the prototype of the object, in the prototype of the
prototype, and so on—until a property is found that matches the name or the end of the prototype chain is
reached.
Example:
Example:
let o = {}; // o inherits object methods from Object.prototype
o.x = 1; // and it now has an own property x.
let p = Object.create(o); // p inherits properties from o and Object.prototype
p.y = 2; // and has an own property y.
let q = Object.create(p); // q inherits properties from p, o, and...
q.z = 3; // ...Object.prototype and has an own property z.
let f = q.toString(); // toString is inherited from Object.prototype
fi
fi
fi
q.x + q.y // => 3; x and y are inherited from o and p
In JavaScript, classes are mainly an abstraction over the existing prototypical inheritance mechanism—all
patterns are convertible to prototype-based inheritance. Classes are usually created with class declarations.
Syntax:
class MyClass {
// class body...
}
Example:
class MyClass {
// Constructor
constructor() {
// Constructor body
}
// Instance eld
myField = "try";
// Instance method
myMethod() {
// myMethod body
}
// Static eld
static myStaticField = "test";
// Static method
static myStaticMethod() {
// myStaticMethod body
}
// Static block
static {
// Static initialization code
}
// Fields, methods, static elds, and static methods all have
// "private" forms
#myPrivateField = "test";
}
Arrays
An array is a special variable, which can hold more than one value. Using an array literal is the easiest way
to create a JavaScript Array.
const array_name = [item1, item2, ...];
Examples:
var empty = []; // An array with no elements
var primes = [2, 3, 5, 7, 11]; // An array with 5 numeric elements
var misc = [ 1.1, true, "a", ]; // 3 elements of various types + trailing comma
var a = new Array(10);
var a = new Array(5, 4, 3, 2, 1, "testing, testing");
Few of the Methods and properties for arrays:
• The length property returns the length (size) of an array.
• Method toString() converts an array to a string of (comma-separated) array values.
• at() method returns an indexed element from an array.
• join() method also joins all array elements into a string.
• pop() method removes the last element from an array.
• push() method adds a new element to an array (at the end).
• shift() method removes the rst array element and "shifts" all other elements to a lower index.
• unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements.
fi
fi
fi
fi
• concat() method creates a new array by merging (concatenating) existing arrays.
• copyWithin() method copies array elements to another position in an array.
• Splice() method adds new items to an array.
• slice() method slices out a piece of an array.
Functions
A JavaScript function is a block of code designed to perform a particular task. The code inside the function
will execute when "something" invokes (calls) the function and when we reach a return statement, the
function will stop executing.
Syntax:
function myFunction(p1, p2,….) { //function with parameters
//statements
}
Example:
function sum(a, b) { //function de nition
var c = a + b;
return c;
}
sum(1); //function call
Self-Study
• Study the topics covered in this document in detail from the links shared in the references.
• Practice code using objects, object inheritance, and arrays and functions.

CSS oats were initially designed for text wrapping around images, but their versatility soon made them a
crucial component in web layout design. By using the oat property, elements can be moved to one side of
their containing element, allowing subsequent elements to ow around them.
The oat property allows you to take an element in normal ow and place it as far to the left or right of the
containing element as possible.
This is particularly useful for creating multi-column layouts and arranging content in a visually appealing
manner.
The element with the oat property is removed from the normal ow and all the other elements will oat
and display beside it; therefore, if we want to stop the following element from oating or moving up, we
need to clear it and it is achieved with the clear property.
The clear property accepts the following values:
• left: Clear items oated to the left.
• right: Clear items oated to the right.
• both: Clear any oated items, left or right.
Consider the following code example for a simple two-column layout using oats and clear:
The HTML and CSS code below demonstrates a simple webpage layout using CSS oat and clear
techniques.

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Floating Layout</title>
<link rel="stylesheet" href="style.css" >
fl
fl
fl
fl
fl
fl
fi
fl
fl
fl
fl
fl
fl
fl
fl
</head>

… </div>
<div class="column column2">
<h2>Column 2</h2>
<p>This is the content of the second column. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Mauris eget venenatis ligula. Ut lacinia at dolor vitae pulvinar. Aliquam pretium
dignissim eros. Integer faucibus, dui non aliquet bibendum, lectus orci lobortis odio, ornare
porttitor est tellus eget velit. Nulla eros elite malesuada id neque vel, viverra vehicula neque.
Nullam auctor turpis non leo iaculis nibus. Quisque blandit arcu venenatis libero tempor, ac
pulvinar ligula dapibus.
</p>
</div>
<div class="clear"></div>
<div id="box4" class="box">
<h3>Footer</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget venenatis ligula.
Ut lacinia at
dolor vitae pulvinar. .</p>
</div>
</div>
</body>
</html>

Style.CSS

.container {
width: 80%;
margin: 0 auto;
}

.column1 {
oat: left;
width: 20%;
box-sizing: border-box;
padding: 20px;
border: 1px solid black;
}
.column2 {
oat: left;
width: 80%;
box-sizing: border-box;
padding: 20px;
border: 1px solid black;
}
.box {
border: 1px solid black;
background-color: cadetblue;
text-align: justify;
padding: 10px;
margin-bottom: 10px;
}
fl
fl
fi
.clear {
clear: both;
}

Let's break down the code to understand how the layout is achieved:
1) Container: The .container class sets the width to 80% of the viewport and centers it with margin: 0
auto;.
2) Columns:Two columns, .column1 and .column2, are created using CSS oat.
3) .column1 is oated to the left with a width of 20%, while .column2 is oated to the left with a width
of 80%.
4) Both columns have box-sizing set to border-box to include padding and border in the de ned width.
Borders and padding are added for styling, creating a visual separation between the columns.
5) Clear x: The .clear class is used for clear x, ensuring that the container properly wraps around the
oated columns. This prevents layout issues that may arise due to oating elements.
The code results in a webpage layout with a header (box1), two columns (column1 and column2), and a
footer (box4). The use of CSS oat allows the columns to sit side by side, and the clear x ensures proper
wrapping the rest of the content(footer) within the container.

This layout is a basic example of how CSS oat and clear x can be employed to structure a webpage. While
these techniques are effective, modern layout approaches like Flexbox and CSS Grid are now widely used
for more complex and responsive designs.
fl
fi
fl
fl
fl
fi
fi
fl
fl
fl
fi
fi
Understanding Flexbox
Flexbox is designed to provide a consistent way to lay out and distribute space among items in a container,
even when the size of the items is unknown or dynamic. The main idea behind Flexbox is to give the
container the ability to alter its items' width, height, and order to best ll the available space and prevent
over ow or extra white space.
Flex Container and Flex Items
Flex Container: The parent element containing ex items. Applying display: ex; or display: inline- ex; to
an element turns it into a ex container.
Flex Items: The children elements within a ex container are referred to as ex items.
Main Axis and Cross Axis
Main Axis: The primary axis along which ex items are laid out. It is determined by the ex-direction
property.
Cross Axis: The perpendicular axis to the main axis, in uencing alignment through properties like align-
items and align-self.
main-start and main-end: The ex items are placed within the container starting from main-start and going to
the main-end.
cross-start and cross-end: Flex lines are lled with items and placed into the container starting on the cross-
start side of the ex container and going toward the cross-end side.

Creating a Flex container:


The rst step in using Flexbox is to designate a container as a ex container. This is achieved by setting the
display property to ex or inline- ex:
Converts an element into a ex container.
.container {
display: ex;
}
Flex Directions
The ex-direction property de nes the main axis along which the ex items are placed within the container.
It can take values like row, row-reverse, column, or column-reverse:
.container {
ex-direction: row; /* Default value */
}
Row: Items are laid out in a horizontal line (default).

Column: Items are laid out in a vertical line.


fl
fl
fi
fl
fl
fl
fl
fl
fl
fi
fl
fl
fi
fl
fl
fl
fl
fl
fl
fi
fl
fl
fl
fl
Row-reverse: Reverses the order of items in a row.

Column-reverse: Reverses the order of items in a column.

Arranging the items inside the ex container:


justify-content
This property aligns ex items along the main axis. It controls the distribution of space between and around
items:
ex-start (default): Items are aligned toward the start of the ex-direction.
justify-content: ex-start; /* Default value */

center: Items are aligned and centered along the main axis line.
fl
fl
fl
fl
fl
justify-content: center;

ex-end: Items are aligned toward the end of the ex-direction.


justify-content: ex-end;

space-around: Items are evenly distributed in the line with equal space around them.

justify-content:space-around;

space-between: Items are evenly distributed in the line; The rst item starts immediately after the main start
and the last item is near the main end. The space is distributed between all the other items
justify-content:space-between;

space-evenly: Items are distributed such that the spacing between any two items is equal. Also the space to
the edges for the rst item and last item is equal.
justify-content:space-evenly;

align-items
This property is used to align items along the cross-axis. align-items applies to all items within the container.
The ex items are laid out along the cross-axis on the current line.
.container {
align-items: stretch | ex-start | ex-end | center ;
}
ex-start: Items are placed at the start of the cross-axis.

center: Items are centered in the cross-axis.

ex-end: Items are placed at the end of the cross-axis.


fl
fl
fl
fl
fl
fi
fl
fl
fl
fi
stretch (default): Stretch to ll the container.

FLEX Properties
order
By default, ex items are laid out in the source order. However, the order property controls the order in
which they appear in the ex container.
ex-grow
This property de nes the ability of a ex item to grow if necessary. It accepts a unitless value that serves as a
proportion. It dictates what amount of the available space inside the ex container the item should take up. If
all items have ex-grow set to 1, the remaining space in the container will be distributed equally to all
children. If one of the children has a value greater than 1, that particular item would take up more space
depending on the ex-grow value. The ex-grow property de nes the rate at which the item size should
grow in relation to other elements.
ex-shrink: This de nes the ability for a ex item to shrink if necessary. This is the reverse of ex-grow.
ex-basis:This de nes the default size of an element before the remaining space is distributed. It can be a
length (e.g., 10%, 2rem, etc.) or a keyword.
FLEX Property
The ex property is a shorthand for ex-grow, ex-shrink, and ex-basis. It speci es how a ex item will
grow or shrink to t the available space:
.item {
ex: 2 1 50%;
/* ex-grow: 2; ex-shrink: 1; ex-basis: 50%; */
}
PracticalUse Cases
1. Responsive Design with Flexbox
Leveraging Flexbox properties to create responsive designs that adapt to different screen sizes.
.container {
ex-direction: column;
/* Stack items vertically on small screens */
}
@media screen and (min-width: 600px) {
.container {
ex-direction: row;
/* Arrange items in a row on larger screens */
}
}
2. Flexbox for Navigation Menus
fl
fl
fl
fl
fl
fl
fl
fl
fl
fl
fi
fl
fl
fi
fi
fi
fl
fi
fl
fl
fl
fl
fl
fl
fi
fl
fl
fi
fl
fl
Designing navigation menus with Flexbox for easy alignment and responsiveness.
.nav-container {
display: ex;
justify-content: space-around;
}
3. Flexbox for Card Layouts: Utilizing Flexbox to create card-based layouts.
Conclusion
CSS Flexbox is a powerful layout model that simpli es the process of creating exible and responsive
designs. Its intuitive and easy-to-understand properties make it an essential tool for web developers striving
to build modern and dynamic user interfaces. By mastering the concepts, developers can leverage Flexbox to
achieve complex layouts with less code and greater control over the visual presentation of their web pages.
Whether used independently or in conjunction with other layout models, Flexbox is a valuable addition to
the web developer's toolkit.
fl
fi
fl
Understanding CSS Grid
CSS grid layout, commonly known as CSS grid, is a two-dimensional layout system for the web that enables
the creation of complex grid-based layouts. It provides a powerful set of tools for de ning both the rows and
columns of an element, allowing for precise control over the placement and sizing of its children.
Grid Container and Grid Items:
Grid Container: The parent element that holds the grid items. Applying display: grid; or display: inline-grid;
to an element transforms it into a grid container.
Grid Items: The children elements within a grid container are referred to as grid items. These items are
placed within the de ned grid rows and columns.
Grid Lines and Grid Tracks:
Grid Lines: The horizontal and vertical lines that divide the grid into rows and columns are called grid lines.
They are referenced by their line numbers. In the below diagram, the line numbers are displayed in yellow
notes.

Grid Tracks: It is the space between two adjacent grid lines. Grid tracks can be rows or columns, forming the
structure of the grid. In the diagram below, the size of the tracks is displayed in yellow notes.

De ning a Grid:
The display property with a value of grid or is used to de ne an element as a grid container.
.container {
display: grid;
}
The above property de nes a single-column grid. You can de ne rows and columns on grid with the grid-
template-rows and grid-template-columns properties. These de ne grid tracks.
grid-template-rows and grid-template-columns
These properties de ne the number and size of the grid rows and columns. Sizes can be speci ed in pixels,
percentages, or using the fr unit (fractional unit).
Example: A grid with two columns (100px, 200px)
.container {
/* Two rows with speci c heights */
grid-template-rows: 100px 200px;
}
In addition to creating grids using lengths and percentages, we can use the fr unit to size grid rows and
columns exibly. This unit represents one fraction of the available space in the grid container.
Example: A grid with two columns with a 1:2 ratio
.container {
grid-template-columns: 1fr 2fr;
}
The explicit grid is the one created using grid-template-columns or grid-template-rows. The implicit grid is
created when content is placed. By default, tracks created in the implicit grid are auto-sized, which, in
fi
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
general, means that they are large enough to t their content. Grid tracks in an implicit track can be given a
size using the grid-auto-rows and grid-auto-columns properties.
Line-based placement:
Line-based placement in CSS grid refers to positioning grid items based on the line numbers of the grid
tracks (rows or columns). This approach allows for precise control over the placement of items within the
grid by specifying where they start and end in terms of grid lines.
grid-row and grid-column properties:
The grid-row and grid-column properties are used to position grid items based on the line numbers of the
grid tracks.
Example 1:
.item {
grid-row: 2 / 4;
grid-column: 1 / span 2;
}
The item starts at the second-row line and ends at the fourth-row line. It starts at the rst column line and
spans two columns.
Example 2:
In this example, a grid of four columns is de ned. The header starts from line 1 and extends up to line 4.

.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-gap: 20px;
}

header {
grid-column: 1 / 4;
grid-row: 1;
background-color: lightblue;
color: red;
}

In the image below, you can see the line numbers and the placement of the header between lines 1 to 4.

Grid Areas:
In CSS grid layout, a grid area refers to the rectangular space enclosed by four grid lines within the grid
container. It is the region where grid items are placed, and it is de ned by specifying the names or indices of
the starting and ending lines for both rows and columns.
Named regions of the grid are created by combining multiple cells. Grid areas make it easy to de ne and
place items within the layout.
De ning Grid Template Areas
fi
fi
fi
fi
fi
fi
CSS grid template areas allow developers to name speci c regions within a grid and assign those names to
grid items. This approach is particularly bene cial when dealing with intricate layouts that involve multiple
grid items and the need for clear organization.
Grid template areas are de ned in the grid-template-areas property of the grid container. The property value
consists of strings enclosed in quotation marks, representing the named areas of the grid. Each string
corresponds to a row in the grid, and the areas within that row are de ned by space-separated names.
.container {
display: grid;
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
}
In this example:
The grid has three rows: header, sidebar-content, and footer.
Each row has four areas: header, sidebar, content, and footer.
Assigning Areas to Grid Items
Grid items are assigned to the named areas using the grid-area property. The value of grid-area corresponds
to the name of the area de ned in grid-template-areas. This ensures that each grid item is placed in its
designated area within the grid.
.header {
grid-area: header;
}

.sidebar {
grid-area: sidebar;
}
.content {
grid-area: content;
}
.footer {
grid-area: footer;
}
In the below image, the grid area names are highlighted in the yellow notes. For example, the header spans
all three columns, the sidebar occupies only the rst column, as mentioned in the grid-template-areas
property.

Practical Implementation
1) Building responsive grids: Creating responsive grids that adapt to different screen sizes is a common
use case for CSS grid.
2) CSS grid is excellent for designing card-based layouts with consistent spacing and alignment.
3) CSS grid allows for the creation of multi-section page layouts with ease.
Best Practices
fi
fi
fi
fi
fi
fi
• Embrace exibility: Leverage the exibility of CSS grid to create versatile layouts that adapt to
various content and screen sizes.
• Combine grid with other layout techniques: CSS grid can be combined with other layout methods,
such as Flexbox or traditional positioning, for more intricate and feature-rich designs.
• Optimize for accessibility: Ensure that the grid layout is accessible by using semantic HTML and
providing alternative text for images.
Conclusion
CSS grid is a powerful layout system that brings a new level of exibility and control to web design. With
its intuitive syntax and comprehensive set of features, developers can easily create complex and responsive
layouts without relying on excessive markup or CSS hacks. Whether used for simple card layouts, multi-
section pages, or intricate responsive designs, a CSS grid is a valuable tool that empowers developers to
build modern and visually stunning websites.
fl
fl
fl
Media queries are CSS rules that allow developers to apply styles based on characteristics of the device,
such as its screen width, height, or resolution. They play a crucial role in the implementation of responsive
web design, providing a way to tailor the presentation of content to different devices and viewport sizes.
Syntax of Media Queries
The syntax of a media query is straightforward, typically consisting of a media type and one or more
expressions that check conditions such as width, height, or orientation.
It consists of:
• A media type tells the browser what kind of media this code is for (e.g., print, or screen). The
possible types of media you can specify are:
◦ all
◦ print
◦ screen
◦ speech
• A media expression, a rule, or a test that must be passed for the contained CSS to be applied.
• A set of CSS rules that will be applied if the test passes and the media type is correct.
Example:
@media screen and (max-width: 768px) {
/* Styles for screens with a maximum width of 768 pixels */
body {
font-size: 16px;
}
}
In this example:
• @media indicates the start of a media query.
• screen is the media type, specifying that the styles apply to devices with screens.
• (max-width: 768px) is the expression, applying styles only when the viewport width is 768 pixels or
less.
Use Cases of Media Queries
1. Responsive layouts: One of the primary use cases of media queries is creating responsive layouts. By
adjusting the layout, font sizes, and spacing based on the device's screen size, websites can provide an
optimal viewing experience for users.
@media screen and (max-width: 600px) {
/* Adjust styles for smaller screens */
.container {
padding: 10px;
}
.menu {
display: none;
}
}
2. Image optimization: Media queries can be used to load different images or image sizes based on the
user's device. This is particularly useful for improving page loading times and reducing bandwidth usage on
mobile devices.
@media screen and (max-width: 480px) {
/* Load smaller images for smaller screens */
.header {
background-image: url('small-header-image.jpg');
}
}
3. Print styles: Media queries allow developers to de ne styles speci cally for printed documents,
ensuring that the content is well-formatted when users decide to print a webpage.
@media print {
fi
fi
/* Styles for printed documents */
.navigation, .sidebar {
display: none;
}
}
4. Mobile- rst approach: A common practice in responsive web design is adopting a mobile- rst
approach. This involves designing and developing the mobile version of a website rst, then using media
queries to enhance the layout for larger screens. This approach ensures that the core content and
functionality are optimized for mobile devices.
/* Styles for mobile devices (default) */
body {
font-size: 14px;
}
/* Media query for larger screens */
@media screen and (min-width: 768px) {
body {
font-size: 16px;
}
}
Conclusion
Media queries are indispensable tools for web developers seeking to create adaptive and user-friendly
websites. As users access the web from an ever-expanding array of devices, the importance of responsive
design cannot be overstated. Media queries empower developers to tailor their designs to various screen
sizes and characteristics, providing a consistent and enjoyable experience for users across the digital
landscape. As technology continues to advance, the role of media queries will remain pivotal in shaping the
future of web design, ensuring that websites are not only visually appealing but also accessible to users
regardless of the device they choose.
fi
fi
fi
Cascading Style Sheets (CSS) is a rule-based language that empowers web designers to de ne styles for
speci c elements on a webpage.
CSS Rules: CSS rules consist of selectors and declarations, specifying how particular elements or groups of
elements should be styled on a webpage.
Components of a CSS Rule:
• Selector: Identi es the HTML element to be styled (e.g., paragraph).
• Declaration Block: Enclosed in curly braces {}, contains one or more property-value pairs.

CSS Declarations:
Declarations within a rule consist of property and value pairs, de ning speci c stylistic features.
Property: Human-readable identi er indicating the stylistic feature to be modi ed (e.g., color).
Value: Speci es how to style the property (e.g., blue). Depending on the property, values may include size
units, font names, or functions.
Property and value are separated by a colon (:).
CSS properties and values are case-insensitive.
CSS Declaration Blocks:
Declaration blocks are enclosed within curly braces and consist of one or more CSS declarations.
Multiple CSS rules are written sequentially in a stylesheet.
Examples:
p{
color: blue;
width: 200px;
border: 1px solid black;
}
h1 {
color: red;
text-align: center;
}
There are three different ways to apply styles to a webpage. They are external stylesheet, internal styles, and
inline styles.
1. External Stylesheet:
An external stylesheet involves writing CSS rules in a separate le with a .css extension. These rules are
linked to an HTML document using the <link> element in the <head> section.
Key points:
• <link> element speci es the stylesheet using the rel attribute.
• The location of the stylesheet is de ned by the href attribute, pointing to the CSS le.
• External stylesheets facilitate a clear separation of structure and styling, promoting reusability across
multiple pages.
2. Internal Stylesheet:
Internal stylesheets house CSS rules within an HTML document, enclosed in a <style> element within the
<head> section. These rules exclusively apply to the speci c HTML page.
Key points:
• Suitable for situations where modifying the original CSS le is restricted.
• Inef ciencies arise when maintaining websites with multiple pages due to each page having its
internal stylesheet.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
3. Inline Styles:
Inline styles are CSS declarations applied to a speci c HTML element within a style attribute. These styles
only affect the element they are applied to and cannot be referenced elsewhere in the document.
Example:
<h1 style="color:blue; border:1px solid black;">Hello World!</h1>
Key points:
• Least ef cient for maintenance, as changes may require multiple edits within a single page.
• Mixing presentational code with HTML content makes it harder to read and understand.
• Use cases include content management systems limiting HTML body edits.
Browser Rendering Process:
Understanding how browsers render HTML content and apply styles involves a multi-step process.
1. Loading HTML Content:
• Browser loads HTML content.
• Converts HTML into a Document Object Model (DOM) in the computer's memory.
2. Creating DOM:
• DOM has a hierarchical structure resembling a tree.
• Nodes represent elements, attributes, and text, de ning relationships in the DOM.
3. Applying CSS Rules:
• Browser parses associated CSS and creates a CSS Object Model (CSSOM).
• Combines DOM and CSSOM to form a render tree, determining the visual display.
4. Rendering on Screen:
• The render tree is used to render the visual display of the page on the screen.

Conclusion:

With a comprehensive understanding of the components of a CSS rule, the three CSS application methods,
and the browser rendering process, we are well-equipped to create stylish and well-structured HTML web
pages.

The Signi cance of Selectors:


CSS selectors act as a link between the structure of an HTML document and its visual representation. They
specify which elements on a webpage should follow certain styling rules by de ning the scope of styles. The
strength of CSS lies in its capability to select elements with a high degree of precision, providing designers
with greater exibility and control over the visual design.
Types of CSS Selectors:
1. Universal Selector (*):
The universal selector targets all elements on a webpage. While it can be useful for applying global styles,
its broad scope should be used judiciously to avoid unintended consequences.
Example:
*{
margin: 0;
padding: 0;
}
2. Simple/Type Selector:
Type selectors are used to target speci c HTML elements, allowing for uniform application of styles across
all instances of the element.
fi
fi
fl
fi
fi
fi
fi
Example:
h1 {
font-size: 24px;
}
3. Class Selector (.class):
Class selectors are a powerful tool that allows for the styling of multiple HTML elements with a speci c
class attribute. By using class selectors, web developers can ensure consistent and uniform styling for all
elements belonging to a particular class.
Example:
.button {
background-color:red;
color:yellow;
}
4. ID Selector (#id):
ID selectors target a unique HTML element with a speci c ID attribute. They should be unique on a page
and are useful for applying styles to a single, speci c element.
Example:
#header {
border-bottom: 1px solid black;
}
5. Attribute Selector ([attribute=value]):
Attribute selectors target elements based on the presence or value of their attributes. This provides a exible
way to style elements with speci c attributes.
Example:
input[type="text"] {
border: 1px solid #ddd;
}
Attribute selectors can do much more than just check for the presence of an attribute and its value.
[attr]: This selector will select all elements with the attribute attr, whatever its value.
[attr=val]: This selector will select all elements with the attribute attr, but only if its value is val.
[attr~=val]: This selector will select all elements with the attribute attr, but only if the value val is one of a
space-separated list of values contained in attr's value.
[attr^=val]: This selector will select all elements with the attribute attr for which the value starts with val.
[attr$=val]: This selector will select all elements with the attribute attr for which the value ends with val.
[attr*=val]: This selector will select all elements with the attribute attr for which the value contains the string
val.
6. Pseudo-Class Selector
Pseudo-classes target elements based on their state or position.
Example:
a:hover {
color: blue; /* Change color on hover */
}
7. Pseudo-Element Selector
The CSS pseudo-element module de nes abstract elements that are not directly present in the document tree.
These abstract elements, called pseudo-elements, represent portions of the render tree that can be selected
and styled.
Pseudo-elements are pre xed with a double colon (::).
p:: rst-line {
font-weight: bold;
/* Style the rst line of paragraphs */
}
Combinators
fi
fi
fi
fi
fi
fi
fi
fl
fi
It is also possible to combine these selectors to select the elements depending on their location and
relationship with other elements. The combination of these selectors allows for precise targeting of elements,
enabling the implementation of complex and responsive layouts. The different types of combinators possible
are listed below.
1. Descendant Combinator:
The descendant combinator (represented by a single space) selects elements based on their relationship to an
ancestor element. Elements matching the second selector are chosen if they have an ancestor matching the
rst selector.
Example:
article p {
/* Styles applied to <p> inside an article element*/
}
2. Child Combinator:
The child combinator (>) selects elements that are direct children of the rst selector. Descendant elements
further down the hierarchy do not match.
Example:
article > p {
/* Styles applied to <p> elements that are direct children of <article> */
}
3. Next-Sibling Combinator:
The next-sibling combinator (+) selects elements that are the next sibling of the rst selector. Useful for
styling elements immediately following another element.
Example:
p + img {
/* Styles applied to <img> elements immediately preceded by a <p> */
}
4. Subsequent-Sibling Combinator:
The subsequent-sibling combinator (~) selects elements that are siblings of the rst selector, even if they are
not directly adjacent.
Example:
p ~ img {
/* Styles applied to <img> elements that come after <p> elements */
}
CSS combinators are essential tools for crafting precise and effective styles in web design. Whether
selecting descendants, children, or siblings, understanding these combinators empowers designers to create
dynamic and responsive layouts.

The CSS Cascade is a vital aspect of CSS that determines which CSS declarations take precedence over
others. It is essentially an algorithm that web browsers use to resolve competing CSS declarations.
Every CSS rule or declaration enters the CSS Cascade, which then decides whether it will become the nal
style or not.
The following are the order and steps that are followed to resolve con icts and select the nal style.
Importance: The rst factor that is looked at is the importance. There are four basic types of rules, and they
are listed below in the other of their importance.
1. transition: Rules that apply to an active transition take the utmost importance.
2. !important: When we add !important to the end of our declaration, it becomes an important rule.
3. animation: Rules that apply to an active animation.
4. normal: This level represents all the other rules.
Origin:
The second factor to be looked at in the cascade algorithm is the Origin.
fi
fi
fl
fi
fi
fi
fi
fi
There are three types of origin for CSS declarations: user-agent stylesheets, author stylesheets, and user
stylesheets. User-agent stylesheets are the default styles applied by browsers to any document. Author
stylesheets are the most common type of stylesheet created by web developers, who de ne the styles for the
document using one or more linked or imported stylesheets, <style> blocks, and inline styles de ned with
the style attribute. In addition, users can choose to override styles using a custom user stylesheet to tailor
their experience. These user styles can be con gured directly or added via browser extensions, depending on
the user agent.
The precedence of the various origins is, in descending order, is as follows.
• Transition declarations [css-transitions-1]
• Important user agent declarations
• Important user declarations
• Important author declarations
• Animation declarations [css-animations-1]
• Normal author declarations
• Normal user declarations
• Normal user agent declarations
Declarations from origins earlier in this list win over declarations from later origins.
Speci city:
The third factor that is looked at is Speci city. If two styles from the same origin precedence, con ict, then
Speci city is considered.
"Speci city" refers to a calculation that determines the most speci c CSS selector, by assigning weights or
scores to each selector type. Each selector is worth a certain number of points which adds up to give the nal
speci city score.
A universal selector (*) has no speci city and gets 0 points.
An element (type) or pseudo-element selector gets 1 point of speci city.
A class, pseudo-class, or attribute selector gets 10 points of speci city.
An ID selector gets 100 points of speci city.
CSS applied directly to the style attribute of the HTML element, gets a speci city score of 1,000 points.
Example:
div #myid
{
color:red;
}
div is an element selector, so gets 1 point
#myid is an id selector, so gets 100 points
So the speci city of this selector div #myid is 0101
The rule with the higher speci city is applied. When two rules have the same speci city, the next factor to
be looked is the source order.
Source order
The last factor to be looked at is the position of the CSS rule or the source order.
Source order only matters when the speci city weight of the rules is the same.
The CSS rules from all sources, such as external, internal, and imported, are all ordered as they appear in the
source code. The last declaration in document order wins.
The output of the cascade is a sorted list of declared values for each property on each element.
The Cascade algorithm resolved only style properties that con ict, but the other style properties are merged.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
fi
fi
fi
fi
fi
fl
fi
When designing web pages, the browser's rendering engine employs the CSS basic box model as a
fundamental framework. The browser's rendering engine visualizes each HTML element as a rectangular
box. This model represents each HTML element as a rectangular box, dictating its size, position, and various
properties such as color, background, and border. The box model standardizes layout design by governing
box size, position, and properties.
The CSS Box Model has four key components—content area, padding area, border area, and margin area—
which collectively de ne the structure of these rectangular boxes.

Components of the CSS Box Model:


1. Content Area: The innermost area where the actual content (text, images, etc.) of the element
resides. Bounded by the content edge, this area contains the "real" content of the element (text,
images, videos). Dimensions are de ned by content width and content height. Size can be explicitly
de ned using properties such as width, min-width, max-width, height, min-height, and max-height.
2. Padding Area: A transparent area surrounding the content, creating space between the content and
the element's border. Padding thickness is determined by padding-top, padding-right, padding-
bottom, and padding-left properties, as well as shorthand padding properties.
3. Border Area: A visible or invisible boundary surrounding the padding, demarcating the edges of the
element.
4. Margin Area: The outermost layer, providing space between the element's border and adjacent
elements, in uencing layout spacing. It is an empty area separating the element from its neighbors.
Size is determined by margin-top, margin-right, margin-bottom, margin-left, and shorthand margin
properties. Margin collapsing occurs when margins are shared between boxes.
Calculating Width and Height in CSS:
Understanding how width and height are calculated in CSS involves considering the entire box model:
The content width and height refer to the actual width and height of the content area, respectively. It is
de ned by properties such as width and height in CSS. Padding and border are added to the total width and
height of the element. Margin creates space outside the element and is not included in the speci ed width
and height. Margin affects the overall spacing and layout but does not impact the element's intrinsic size.
The total width of an element is the sum of its content width, padding, and border. The total height includes
the content height, padding, and border.
For example:
Total element width = de ned width + left padding + right padding + left border + right border
Total element height = de ned height + top padding + bottom padding + top border + bottom border.
.box1 {
width: 300px;
height: 300px;
border: 1px solid black;
color: blue;
}
• Total <div> width = 300px + 10px + 10px + 1px + 1px = 322px.
• Total <div> height = 300px + 10px + 10px + 1px + 1px = 322px.
Understanding Box Sizing
fi
fi
fl
fi
fi
fi
fi
fi
The box-sizing property allows developers to control the dimensions of an element.
Two primary values are the content-box (default) and the border-box.
Content-Box: In the content-box model, the speci ed width and height apply only to the content area,
excluding padding and border. The total space the element occupies is the sum of its content, padding, and
border.
Border-Box: The border-box model includes padding and border within the speci ed width and height,
simplifying layout calculations. This ensures that the speci ed dimensions encompass the content, padding,
and border.
Calculating Width and Height in CSS in border-box
Total element width = de ned width
Total element height = de ned height
.box1 {
width: 300px;
height: 300px;
border: 1px solid black;
color: blue;
}
Total <div> width = 278px + 10px + 10px + 1px + 1px = 300px.
Total <div> height = 278px + 10px + 10px + 1px + 1px = 300px.
The content box shrinks to accommodate padding and border and retains the total width of 300px.
Conclusion:
In conclusion, the CSS Box Model is the cornerstone of web layout design, providing a standardized and
systematic approach to element representation. A thorough understanding of its components—content,
padding, border, and margin areas—empowers web developers to create precisely positioned layouts.
fi
fi
fi
fi
fi
Introduction to HTML:
HTML, an acronym for HyperText Markup Language, serves as the standard markup language for crafting
web pages. HTML de nes the structure of a web page through the use of markups. Understanding HTML is
foundational to web development.
HTML structures content and links, creates forms, and integrates multimedia in web pages.
Basic Structure of an HTML Page:
The HTML document starts with <!DOCTYPE html> to specify the document type. The entire document is
enclosed within <html> tags, with two main sections: <head> and <body>.
The <head> section of a web page contains metadata about the document, such as the title of the page and
linked stylesheets. On the other hand, the <body> section includes the actual content of the web page,
including text, images, links, and various other elements.
HTML elements are the fundamental building blocks of the language and consist of a start tag, content, and
an end tag. For example, a paragraph is represented by <p>This is a paragraph.</p>
Basic HTML Code:
Choosing the right text editor is essential to code faster and with ease. We use Visual Studio Code for this
course. It is a lightweight source code editor that can be conveniently installed on Windows, macOS, or
Linux, making it accessible to everyone.
The following code snippet shows an example of a basic HTML page:

Previewing HTML Code:


To preview HTML code, save the le with a .html extension and open it in a web browser. Popular browsers
like Google Chrome, Mozilla Firefox, Microsoft Edge, and Safari are commonly used. The browser renders
the HTML code, displaying the web page as it would appear online.
Debugging with Developer Tools:
Debugging is an essential part of the coding process. Use browser developer tools to inspect elements and
x errors for proper rendering and functionality.
Most browsers offer built-in developer tools accessible by right-clicking on a web page and selecting
"Inspect."
Use the "Elements" tab to inspect and modify HTML elements. Developer tools can be helpful to have a
thorough understanding of a website’s structure and layout.

Using Text Editor


fi
fi
fi
Visual Studio (VS) Code has built-in support for HTML programming, including syntax highlighting,
intelligent completions with IntelliSense, and customizable formatting. These features make coding more
straightforward, even for beginners.

Quotations:
Blockquotes (<blockquote>): Use this element to mark up a block of content quoted from an external
source. When quoting a block of content from an external source, whether it is a paragraph, multiple
paragraphs, or a list, the <blockquote> element can be used. This element signals that the content is a
quotation, and for transparency, a URL pointing to the source should be included within the cite attribute.
However, note that browsers and screen readers often do not display the content of the cite attribute. If you
want users to access the source, consider providing it in the text via a link or another suitable method.
Example:

<blockquote cite="https://www.example.com/inspirational-quote">
"The only way to do great work is to love what you do."
<p>— Steve Jobs</p>
</blockquote>

Abbreviations:
The <abbr> element is commonly used to mark up abbreviations or acronyms. For clarity, include the full
expansion of the term in plain text on its rst use, alongside the <abbr> element.
If adding the full expansion alongside the abbreviation seems impractical, especially for shorter terms, you
can use the title attribute to provide the full expansion.
Example:

<abbr title="HyperText Markup Language">HTML</abbr>

Contact Information:
Address (<address>): The <address> element is designed for marking up contact details. It can wrap around
simple contact information or more complex structures. It can enclose contact details like name, address,
phone number, and email within this element.
Example:

<address>
<p>John Doe</p>
<p>123 Main Street</p>
<p>Anytown, CA 12345</p>
<p>Phone: <a href="tel:555-123-4567">555-123-4567</a></p>
<p>Email: <a href="mailto:johndoe@example.com">johndoe@example.com</
a></p>
</address>

Superscript and Subscript


When dealing with dates, chemical formulas, or mathematical equations, the <sup> and <sub> elements play
a crucial role in rendering superscript and subscript, respectively.
Superscript (<sup>): Use this for text that appears slightly above the normal line, like exponents or
footnotes.
Subscript (<sub>): Employ this for text that appears slightly below the normal line, often used for chemical
formulas or mathematical expressions.
Example:
fi
<p>Water is composed of H<sub>2</sub>O molecules.</p>
<p>Einstein's famous equation is E = mc<sup>2</sup>.</p>

Computer Code Markup


HTML provides several elements for marking up computer code.
<code>: Mark up generic pieces of computer code.
<pre>: Retains whitespace, particularly useful for code blocks.
<var>: Speci cally for marking up variable names.
<kbd>: For marking up keyboard input.
<samp>: For marking up the output of a computer program.
Example:

<pre>
<code>
function greet(name) {
console.log("Hello, " + name + "!");
}
</code>
</pre>

Date and Time Representation


The <time> element in HTML is a versatile and semantic tag designed speci cally for representing time-
related information on the Web. Introduced in HTML5, it provides a standardized way to mark up dates,
times, and durations. The datetime attribute is crucial for providing a machine-readable version of the time
content. It speci es the time in a standardized format, allowing computers to process it accurately.
Example:

<time datetime="2024-01-03T18:50:00+05:30">6:50 PM IST</time>

HTML Entity References


HTML entities are text strings starting with an ampersand (&) and ending with a semicolon (;). They are
used to display reserved characters and invisible characters. You can also use HTML entities as substitutes
for hard-to-type characters.

Introduction to Semantics
In HTML, semantic elements are specially designed to provide clear meaning and purpose to both the
developer and the browser, ensuring that the purpose and content of the HTML document are conveyed with
utmost clarity and precision.
Semantic versus Non-Semantic Elements
Semantic elements, such as “<h1>,” “<table>,” and “< gure>,” clearly de ne their content and contribute to
a better understanding of the document’s structure. In contrast, non-semantic elements like “<div>” and
“<span>” convey no inherent meaning about their content.
Semantic Elements in HTML5
The HTML5 version introduced several new semantic elements that offer meaningful ways to structure a
web page:
1. <article>: De nes an independent, self-contained content block suitable for items like forum posts,
blog posts, or newspaper articles.
fi
fi
fi
fi
fi
fi
2. <aside>: Speci es content that is tangentially related to the surrounding content, often used for
sidebars.
3. <details> and <summary>: De ne additional details that the user can choose to view or hide, with a
visible heading provided by <summary>.
4. < gcaption> and < gure>: Group images and their captions together for better structure and
presentation.
5. <footer>: Speci es a footer for a document or section, commonly containing information like the
author, copyright details, or contact information.
6. <header>: Speci es a header for a document or section, often used to contain introductory content.
7. <main>: Speci es the main content of a document, emphasizing the primary content.
8. <mark>: De nes marked or highlighted text within the document.
9. <nav>: De nes a set of navigation links intended for large blocks of navigation.
10. <section>: De nes a thematic grouping of content, typically with a heading, providing a structured
way to organize content.

Importance of Semantic HTML5 Elements


HTML5 introduced semantic elements like “<header>,” “<footer>,” “<nav>,” “<section>,” and “<article>,”
which provide a standardized way to identify and style page elements, improving clarity and structure in
web documents.
Beyond readability, there are two key reasons to use semantic HTML tags:
Accessibility: Screen readers rely on semantic tags to interpret and present content accurately to users with
vision impairments, enhancing their comprehension and navigation.
SEO: Search engines use semantic tags to understand the meaning and structure of your content, making it
easier for them to rank your pages for relevant keywords in search results.
Developers can signi cantly contribute to the creation of the Semantic Web by utilizing semantic elements
in their web pages. Semantic elements allow data to be easily shared and reused across various applications,
enterprises, and communities. The use of clear and meaningful tags not only improves the user experience
but also helps search engines accurately identify and index web page content.
In short, semantic HTML bene ts both users and search engines, making it crucial for building inclusive and
discoverable web pages.

Accessibility, in the context of technology and the Web, refers to the practice of making information and
services usable for everyone, regardless of their abilities, disabilities, or circumstances. It is about removing
barriers and creating inclusive experiences for all users. The Web Content Accessibility Guidelines (WCAG)
are a set of guidelines that aim to make digital content more accessible to people with disabilities.
These guidelines are divided into four key principles that serve as a roadmap for creating accessible content:
1. Perceivable: This principle focuses on making sure that users can perceive the content in some way.
For instance, the content should be presented in a way that can be seen, heard, or felt, depending on
the user’s abilities.
2. Operable: This principle focuses on giving users control over UI elements, such as buttons, links,
and forms. A user should be able to interact with these elements using various methods, such as a
mouse, keyboard, and voice command.
3. Understandable: This principle focuses on making sure that the content is easy to understand. It
should be presented in a clear and organized way, with simple and concise language that conveys the
intended message.
4. Robust: This principle focuses on developing content using well-established web standards that can
work across different browsers and devices, both now and in the future.
By following these standards, the content can be made accessible to a wider audience, including people with
disabilities.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
A signi cant amount of web content can become accessible if we use the appropriate HyperText Markup
Language elements for their intended purpose at all times.
fi
Protocols help the Internet to function properly. A protocol is simply a standard for enabling the following
between two entities on the network:
• Connection
• Communication
• Data transfer
HyperText Transfer Protocol (HTTP)
HTTP is the underlying protocol of the World Wide Web. Developed by Tim Berners-Lee and his team
between 1989 and 1991, HTTP has gone through many changes that have helped maintain its simplicity
while shaping its exibility. HTTP is a protocol for fetching resources such as HTML documents. It is the
foundation of any data exchange on the Web, and it is a client-server protocol, which means requests are
initiated by the recipient, usually the web browser.
HTTP messages are how data is exchanged between a server and a client. There are two types of messages:
requests sent by the client to trigger an action on the server, and responses, the answer from the server.
In client-server protocols like HTTP, sessions consist of three phases:
• The client establishes a TCP connection (or the appropriate connection if the transport layer is not
TCP).
• The client sends its request and waits for the answer.
• The server processes the request, sending back its answer, providing a status code and appropriate
data.
HyperText Transfer Protocol Secure (HTTPS)
HTTPS is an encrypted version of the HTTP protocol. It uses Transport Layer Security (TLS) to encrypt all
communication between a client and a server. This secure connection allows clients to safely exchange
sensitive data with a server, such as when performing banking activities or online shopping.

HTTPS transmits its data securely by using an encrypted connection. Basically, it uses a public key, which is
then decrypted on the recipient side. The public key is deployed on the server and included in what you
know as a Secure Sockets Layer (SSL) certi cate. The certi cates are cryptographically signed by a
certi cate authority.
Features of HTTP
• Connectionless protocol: The connection between a client and a server exists only for the current
request and response time.
• Stateless: HTTP is a stateless protocol as both the client and server know each other only during the
current request.
The general form of an HTTP request is as follows:
• Request line: It consists of at least three items—a method that tells the server what it should do with
the resource, a path that identi es the resource on the server, and an HTTP version number, showing
the HTTP speci cation to which the client has tried to comply.
• Header elds: They are written on a message to provide the recipient with information about the
sender, the message, and the way in which the sender wants to communicate with the recipient.
• Blank line: To separate the header and the body
• Message body: Actual or encoded message
fi
fi
fi
fl
fi
fi
fi
HTTP Methods:
• GET: The purpose of this method is to retrieve data from the server
• POST: This method sends data to the server for processing
• HEAD: It returns metadata about a resource on the server
• PUT: It is used to completely replace a resource identi ed with a given URL
• DELETE: It removes the resource from the server
• TRACE: It is used for troubleshooting and debugging
• OPTIONS: It returns a listing of which HTTP methods are supported and allowed by the server
HTTP headers let the client and the server pass additional information with an HTTP request or response. An
HTTP header consists of its case-insensitive name followed by a colon (:), then by its value.
Example:
GET /home.html HTTP/1.1
Host: developer.mozilla.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/
20100101 Firefox/50.0
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, de ate, br
Referer: https://developer.mozilla.org/testpage.html
Connection: keep-alive
Upgrade-Insecure-Requests: 1
The general form of an HTTP response is:
• Status line: The HTTP version number, showing the HTTP speci cation to which the server has tried
to make the message comply, status code, which is a three-digit number indicating the result of the
request, and reason phrase, which is human-readable text that summarizes the meaning of the status
code.
• Response header elds: It contains information that a client can use to nd out more about the
response and the server that sent it.
• Blank line: It separates the header from the body
• Response body: It contains either the resource requested by the client or some information about the
status of the action requested by the client.
fi
fl
fi
fi
fi
HTTP Response Codes
Listed below are a few of the response codes:
100 Continue: This interim response indicates that the client should continue the request or ignore the
response if the request is already nished.
200 OK: The request succeeded.
302 Found: This response code means that the URI of the requested resource has been changed temporarily.
304 Not Modi ed: This is used for caching purposes.
401 Unauthorized: Semantically, this response means “unauthenticated.”
408 Request Timeout: This response is sent on an idle connection by some servers, even without any
previous request by the client.
502 Bad Gateway: This error response means that the server, while working as a gateway to get a response
needed to handle the request, got an invalid response.
HTTP response headers provide additional information about the server’s response to an HTTP request
Example:
200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Date: Mon, 18 Jul 2016 16:06:00 GMT
Etag: "c561c68d0ba92bbeb8b0f612a9199f722e3a621a"
Keep-Alive: timeout=5, max=997
Last-Modi ed: Mon, 18 Jul 2016 02:36:04 GMT
Server: Apache
Set-Cookie: mykey=myvalue; expires=Mon, 17-Jul-2017 16:06:00 GMT; Max-
Age=31449600; Path=/; secure
Transfer-Encoding: chunked
Vary: Cookie, Accept-Encoding
File Transfer Protocol (FTP)
FTP is an insecure protocol for transferring les from one host to another over the Internet. It is used for the
transfer of les from one host to another over a TCP-based network, such as the Internet. For many years, it
was the standard way of transferring les, but as it is inherently insecure, it is no longer supported by many
hosting accounts.
SSL
SSL is used for securing an internet connection by encrypting data sent between a website and a browser. It
prevents hackers from seeing or stealing any information transferred, including personal or nancial data.
Transport Layer Security (TLS)
fi
fi
fi
fi
fi
fi
fi
TLS is an updated, more secure version of SSL. It is the most widely used protocol for implementing
cryptography on the Web. TLS uses a combination of cryptographic processes to provide secure
communication over a network. TLS uses public-key cryptography to provide authentication and secret-key
cryptography with hash functions to provide privacy and data integrity.
Web Applications
Web applications are delivered on the World Wide Web to users with an active network connection.
WEB 1.0 is the WWW. It is a system of interlinked, hypertext pages or documents accessed via
INTERNET. It is the read-only web.
WEB 2.0 is the social web. It makes use of new and latest technologies to make the user experience more
interactive, useful, and interconnecting. It is associated with blogs, wikis, podcasts, etc.
WEB 3.0: It is a Semantic Web. It supports 3D portals, multi-user virtual environments, integrated games,
and all media ows in and out of virtual web worlds. Web 3.0 organizes all the information
Tools Used in Web Programming:
Web programs and scripts are divided into two categories:
• Client side: HTML and XML are client-side languages
• Server side: PHP and Ruby are server-side languages
JavaScript is often a client-side language but can be used for both
HTML
HTML is the standard markup language for web pages. It describes the structure of a web page. It consists of
a series of elements and these elements tell the browser how to display the content. Each element is de ned
by a start tag, some content, and an end tag. A web browser reads the HTML documents and displays them
correctly.
Example:

XML
XML stands for eXtensible Markup Language. Unlike other programming languages, XML cannot perform
computing operations by itself. XML’s primary function is to create formats for data that are used to encode
information for documentation, database records, transactions, and many other types of data. It was designed
to be self-descriptive, human- and machine-readable. XML users create their own markup language set of
tags and attributes.
Example:

JavaScript
JavaScript, often abbreviated as JS, is a programming language and core technology of the World Wide Web,
alongside HTML and CSS. JavaScript engines were originally used only in web browsers but are now core
components of some servers and a variety of applications. The most popular runtime system for this usage is
fl
fi
Node.js. JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting
object-oriented, imperative, and declarative styles.
Primary uses:
• Validate form data
• Build Ajax-enabled HTML documents
• Create dynamic HTML documents
PHP
PHP is a general-purpose scripting language geared toward web development. PHP is a server scripting
language and a powerful tool for making dynamic and interactive web pages. PHP code is embedded in
HTML documents. The code is interpreted on the server before the HTML document is delivered to the
requesting client.
Example:
Form - HTML. ——>

Table - HTML

Form style - CSS


/* Set maximum width for the form container */
.form-style {
max-width: 450px;
}

/* Center the elements with class 'center' by adding left margin */


.center {
margin-left: 100px;
}

/* Styling for labels in the form */


label {
display: block;
margin-bottom: 10px;
}

/* Styling for label spans inside the form */


label>span {
float: left;
width: 100px;
color: darkgreen;
font-weight: bold;
font-size: 13px;
}
/* Styling for fieldsets in the form */
fieldset {
border-radius: 10px;
margin: 0px 0px 10px 0px;
border: 1px solid green;
padding: 20px;
background: rgb(171, 243, 171);
}

/* Styling for legend inside fieldsets */


fieldset legend {
color: darkgreen;
border: 1px solid green;
border-radius: 5px 5px 5px 5px;
background: white;
font-weight: bold;
font-size: 12px;
}

/* Styling for text, email inputs, and selects */


input[type=text],
input[type=email],
select {
border-radius: 3px;
border: 1px solid green;
outline: none;
color: black;
padding: 5px 8px 5px 8px;
background: lightgrey;
width: 50%;
}

/* Styling for focused text input */


input[type=text]:focus {
border: 2px dashed black;
color: red;
background-color: yellow;
}

/* Styling for submit and reset buttons */


input[type=submit],
input[type=reset] {
background: rgb(9, 71, 9);
border: 1px solid black;
padding: 5px 15px 5px 15px;
color: white;
border-radius: 3px;
}

/* Styling for reset button on hover */


input[type=reset]:hover {
background-color: red;
}

/* Styling for required field indicator */


.required {
color: red;
font-weight: normal;
}
Forms - HTML

Flexstyle - solution

/* Global */
* {
margin: 0;
padding: 0;
font-family: Arial, Helvetica;
}
/* Header
Adds background color , padding and boxshadow to header
*/
header {
background-color: goldenrod;
padding: 20px 50px;
box-shadow: 0 1px 8px #ddd;
}
/*Style the heading element */
h1{
color:darkblue;
margin-left: 10px;
}
/*Navigation Element
Nav is the Flex container, The List items inside the nav element are the flex items*/
nav{
display: flex;
justify-content:flex-end;
align-items: center;
padding: 20px 50px;
}

/* By default the list items are displayed vertically.


Change the display property to display :inline-block
*/
nav li{
list-style: none;
display: inline-block;
padding: 10px;
}

/*reset the default browser styling of the anchor elements*/


nav a {
text-decoration: none;
color: #1f1e1e;
transition: all 0.3s ease 0s;
}

/*Highlight the nav item selected when the mouse is hover */


nav a:hover {
color: black;
font-size: larger;
background-color:lightseagreen;
}

You might also like