PHP UNIT - 1 Print
PHP UNIT - 1 Print
UNIT-I
Introduction to PHP -Basic Knowledge of websites -Introduction of Dynamic Website -
Scope of PHP -XAMPP and WAMP Installation- PHP Programming Basics -Syntax of
PHP
Web - Basic Concepts
What is Internet?
The Internet is essentially a global network of computing resources. You can think
of the Internet as a physical collection of routers and circuits as a set of shared resources.
Some common definitions given in the past include −
A network of networks based on the TCP/IP communications protocol.
A community of people who use and develop those networks.
Internet-Based Services
Some of the basic services available to Internet users are −
Email − A fast, easy, and inexpensive way to communicate with other Internet
users around the world.
Telnet − Allows a user to log into a remote computer as though it were a local
system.
FTP − Allows a user to transfer virtually every kind of file that can be stored on a
computer from one Internet-connected computer to another.
UseNet news − A distributed bulletin board that offers a combination news and
discussion service on thousands of topics.
World Wide Web (WWW) − A hypertext interface to Internet information
resources.
What is WWW?
WWW stands for World Wide Web. A technical definition of the World Wide
Web is − All the resources and users on the Internet that are using the Hypertext Transfer
Protocol (HTTP).
A broader definition comes from the organization that Web inventor Tim Berners-Lee
helped found, the World Wide Web Consortium (W3C): The World Wide Web is the
universe of network-accessible information, an embodiment of human knowledge.
In simple terms, The World Wide Web is a way of exchanging information between
computers on the Internet, tying them together into a vast collection of interactive
multimedia resources.
What is HTTP?
HTTP stands for Hypertext Transfer Protocol. This is the protocol being used to
transfer hypertext documents that makes the World Wide Web possible.
A standard web address such as Yahoo.com is called a URL and here the
prefix http indicates its protocol
What is URL?
URL stands for Uniform Resource Locator, and is used to specify addresses on the
World Wide Web. A URL is the fundamental network identification for any resource
connected to the web (e.g., hypertext pages, images, and sound files).
What is Web Server?
A Web Server is a computer that hosts websites and makes them accessible over the
Internet. When you type a website address (like tutorialspoint.com) into your browser, it
sends a request to the web server that holds the site, and the server sends back the
requested web pages.
Each web server has a unique IP address (e.g., 68.178.157.132), which helps to identify
it on the Internet. When you register a domain name (like tutorialspoint.com), you link it
to the server's IP address.
When you type a website address in your browser, it requests the page from the web
server, and you can then "browse" or "surf" the website.
Use of PHP
PHP is a server-side scripting language, which is used to design the dynamic web
applications with MySQL database.
o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and
many more.
o Using PHP language, you can control the user to access some pages of your
website.
o As PHP is easy to install and set up, this is the main reason why PHP is the best
language to learn.
o PHP can handle the forms, such as - collect the data from users using forms, save
it into the database, and return useful information to the user. For example -
Registration form.
PHP Features
PHP is very popular language because of its simplicity and open source. There are
some important features of PHP given below:
Performance:
PHP script is executed much faster than those scripts which are written in other
languages such as JSP and ASP. PHP uses its own memory, so the server workload and
loading time is automatically reduced, which results in faster processing speed and better
performance.
Open Source:
PHP source code and software are freely available on the web. You can develop
all the versions of PHP according to your requirement without paying any cost. All its
components are free to download and use.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with
it. PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A
PHP application developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or
warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken
automatically at the time of execution based on the type of data it contains on its value.
Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape,
Microsoft IIS, etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of
security to prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do
the same work in a few lines of code. It has maximum control over the websites like you
can make changes easily whenever you want.
A Helpful PHP Community:
It has a large community of developers who regularly updates documentation,
tutorials, online help, and FAQs. Learning PHP from the communities is one of the
significant benefits.
Common uses of PHP
PHP performs system functions, i.e. from files on a system it can create, open,
read, write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, through email
you can send data, return data to the user.
You add, delete, modify elements within your database through PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Advantages of PHP
3. Platform Independence:
5. Database Connectivity:
Fast execution: PHP is known for its speed and efficiency, allowing for quick
loading times and a better user experience.
Scalability: PHP applications can be easily scaled to handle increasing traffic and
data volumes.
Disadvantages
Applications of PHP
PHP performs system functions, i.e. from files on a system it can create, open,
read, write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, through email
you can send data, return data to the user.
You add, delete, modify elements within your database through PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Web Pages: Individual units within a website, each with its own URL.
Domain Name: The website's address (e.g., example.com).
Web Server: The computer that stores and delivers website files.
Web Browser: Software used to view websites (e.g., Chrome, Firefox, Safari).
HTML (HyperText Markup Language): The standard markup language for
creating the structure and content of web pages.
CSS (Cascading Style Sheets): Used 1 to control the presentation and visual style
of web pages.
JavaScript: A programming language that adds interactivity and dynamic features
to websites.
How Websites Work:
1. Request: You type a website's URL into your web browser.
2. Lookup: Your browser contacts a Domain Name System (DNS) server to
translate the domain name into an IP address (a unique identifier for the server).
3. Connection: Your browser establishes a connection to the web server.
4. Retrieval: The server sends the requested web page files (HTML, CSS, images,
etc.) to your browser.
5. Display: Your browser interprets the code and displays the web page on your
screen.
Types of Websites:
Static Websites: Have fixed content that doesn't change frequently.
Dynamic Websites: Content changes based on user interactions or database
updates.
E-commerce Websites: Allow users to buy products or services online.
Social Media Websites: Platforms for social interaction and content sharing.
Blog Websites: Online journals or diaries with regularly updated content.
Basic Website Development:
Choose a domain name and web hosting.
Plan your website's structure and content.
Create web pages using HTML, CSS, and JavaScript (or use website builders).
Upload your website files to your web server.
Test and launch your website.
Difference between Static Website and Dynamic Website:
As the name suggests, Its webpages do As the name suggests, the webpages keep changing
not change in terms of design, content, as per users' requirements such as Facebook profile
etc. The information or content remains pages and an E-commerce site. So, the content does
the same. not remain the same.
It mainly uses HTML and CSS and does It requires server-side scripting, application server,
not require server-side scripting, and database to create and send dynamic webpages
application server, and database. to the client.
It has a limited number of pages. It may contain thousands of pages in the database.
Its hosting cost is low, as HTML files Its hosting cost is higher as dynamic pages need
need less space on the server. more space on the server.
It loads quickly as it involves the use of It takes more time to load due to the more
mark-up languages to create a webpage. processing time.
It lacks the Content management It makes use of the Content Management Feature.
feature.
The content of the webpage cannot be The webpage content can be changed during
changed during runtime. runtime.
It does not require interaction with a Interaction with the database occurs.
database.
It is more secure or fewer chances of it It is less secure and may get hacked easily as it uses
getting hacked as it doesn't use plugins. many plugins and content sources.
It is more reliable, e.g., whenever the It is less reliable, as it may go down for hours if the
server is down, it is redirected to other server breaks down.
nearby nodes.
Web Development
PHP is widely used in web development nowadays. PHP can develop dynamic
websites easily. But you must have the basic the knowledge of following technologies for
web development as well.
o HTML
o CSS
o JavaScript
o Ajax
o XML and JSON
o jQuery
Prerequisite
Before learning PHP, you must have the basic knowledge of HTML,
CSS, and JavaScript. So, learn these technologies for better implementation of PHP.
HTML - HTML is used to design static webpage.
CSS - CSS helps to make the webpage content more effective and attractive.
JavaScript - JavaScript is used to design an interactive website.
Real-life application:
Here is a list of application where we use dynamic website in real world.
Facebook
Twitter
LinkedIn
Online booking website.
Social media
PHP Variables Scope
In PHP, the scope of a variable refers to the context within which the variable is
accessible or can be used. Understanding variable scope is crucial for managing variables
in your code, as it helps ensure they are accessible only when needed, and prevents
accidental modification or conflicts.
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
Global
local
static
GLOBAL SCOPE:
A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:
PHP The global Keyword:
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;
function myTest()
{
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; // This modifies the global
variable $y
}
myTest(); // Call the function to modify $y
echo $y; // Output the new value of $y
?>
</body>
</html>
Output
LOCAL SCOPE:
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
Example
<!DOCTYPE html>
<html>
<body>
<?php
function myTest()
{
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
Ouput
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are
deleted. However, sometimes we want a local variable NOT to be deleted. We
need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
</body>
</html>
Output:
0
1
2
What is XAMPP?
XAMPP is an abbreviation where X stands for Cross-Platform, A stands for
Apache, M stands for MYSQL, and the Ps stand for PHP and Perl, respectively.
It is an open-source package of web solutions that includes Apache distribution for
many servers and command-line executables along with modules such as Apache
server, MariaDB, PHP, and Perl.
XAMPP helps a local host or server to test its website and clients via computers
and laptops before releasing it to the main server.
Advantages of XAMPP:
It is free and easy to use and easily available for Windows, Linux and Mac OS .
It is a beginners friendly solution package for full stack web development.
It is a open source software package which gives a easy installation experience.
It is very simple and lightweight to create set up for development, testing and
deployment.
It is a time-saver and provides several ways for managing configuration changes.
It handles many administrative tasks like checking the status and security.
Components of XAMPP
As defined earlier, XAMPP is used to symbolize the classification of solutions for
different technologies.
It provides a base for testing of projects based on different technologies through a
personal server.
XAMPP is an abbreviated form of each alphabet representing each of its major
components. This collection of software contains a web server named Apache, a database
management system named MariaDB and scripting/ programming languages such
as PHP and Perl.
X denotes Cross-platform, which means that it can work on different platforms
such as Windows, Linux, and macOS.
Many other components are also part of this collection of software and are explained
below.
1. Cross-Platform:
o Works on Windows, Linux, and macOS.
2. Apache:
o Cross-platform web server that delivers web content.
3. MariaDB:
o Relational database management system (replacing MySQL) for data
storage, retrieval, and manipulation.
4. PHP:
o Server-side scripting language for creating dynamic websites and
applications.
5. Perl:
o High-level programming language for web development, system
administration, and networking.
6. phpMyAdmin:
o Tool for managing MariaDB databases via a web interface.
7. OpenSSL:
o Open-source implementation of SSL/TLS protocols for secure
communication.
8. XAMPP Control Panel:
o Panel to manage and control all XAMPP components.
9. Webalizer:
o Web analytics tool for tracking user activity and usage logs.
10. Mercury:
11. Tomcat:
12. Filezilla:
1. .EXE:
o Executable file for easy installation on Windows systems.
2. .7z:
o Compressed archive format (7zip) for storing and encrypting files,
requiring decompression software.
3. .ZIP:
o Compressed file format using lossless compression for easier file storage,
but trickier to install than .EXE files.
During the installation process, select the required components like MySQL,
FileZilla ftp server, PHP, phpMyAdmin or leave the default options and click
the Next button.
Uncheck the Learn more about bitnami option and click Next button.
Choose the root directory path to set up the htdocs folder for our applications. For
example ‘C:\xampp’.
Click the Allow access button to allow the XAMPP modules from the Windows
firewall.
After the installation process, click the Finish button of the XAMPP Setup wizard.
Now the XAMPP icon is clearly visible on the right side of start menu. Show or
Hide can be set by using the control panel by clicking on the icon.
To start Apache and MySql, just click on the Start button on the control panel.
If Apache doesn’t start, it’s probably because another program is using port 80
(like Skype or IIS).
Fix: Stop the other program or change Apache’s port:
o Open XAMPP Control Panel.
o Click Config next to Apache and choose httpd.conf.
o Find Listen 80 and change it to Listen 8080.
o Change ServerName localhost:80 to ServerName localhost:8080.
o Save and restart Apache.
Create a file named index.php in the htdocs folder (found in the XAMPP
directory).
Add this code:
<?php
echo "PHP is working!";
?>
4. Organizing Projects
Create a folder for each new project in the htdocs folder (e.g., sample).
Inside it, create a helloWorld.php file:
php
<?php
echo "Hello, World from sample!";
?>
Note: In XAMPP, the configuration files of Apache, MySQL, PHP are located
in C:\Program Files\xampp. For any configuration file changes, you need to restart
Apache and MySQL.
WAMP stands for Windows, Apache, MySQL, and PHP. It is a software stack
used to develop web applications on a local Windows machine. WAMP includes
the following components:
1. Apache:
o Apache is the web server that serves the content (HTML, PHP files) to
users’ browsers.
o It listens for incoming requests on a specific port (usually port 80) and
sends back the requested resources.
2. MySQL:
o MySQL is a database management system that stores and manages data.
o It’s used for storing information like user data, website content, etc.
3. PHP:
o PHP is a scripting language used to create dynamic web pages. It processes
code on the server and sends the result (often HTML) to the user's browser.
4. phpMyAdmin:
o A web-based tool used for managing MySQL databases. It allows you to
create, modify, and manage databases, tables, and records from your
browser.
WAMP Features:
Choose location
After selecting your folder, you get extra options to choose. The options include whether
you want to add a desktop and quick launch icon. Once selected, you will be asked to
confirm your choices before installing.
Confirmation
The installation process will take a while but it should get done in a few minutes.
The installation
Congratulations! You have successfully installed a WAMP server. Launch the
application or launch it through the quick launch menu if you want.
Note: The latest version is WAMP server 3. I installed WAMP server 2 because my
device isn’t compatible with the newest one.
Active status
Go to your selected browser (the one you chose during the installation), and
type http://localhost. If it works, you have completed the installation correctly but if it
doesn’t check the port could help.
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:
Example
A simple .php file with both HTML code and PHP code:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Output:
1. Basic Syntax
2. Variables
Arithmetic: +, -, *, /, % (modulo)
Assignment: =, +=, -=, *=, /=
Comparison: == (equal), != (not equal), >, <, >=, <=
Logical: && (and), || (or), ! (not)
4. Control Flow
} else {
switch: Evaluate an expression and execute different code blocks based on its
value.
for loop: Execute a block of code a specified number of times.
while loop: Execute a block of code as long as a condition is true.
foreach loop: Iterate over elements in an array.
5. Functions
Defining a function:
function greet($name) {
6. Arrays
7. Output
HTML embedding: PHP code can be embedded within HTML files using special
tags (<?php ... ?>).
Form handling: PHP can process data submitted through HTML forms.
Working with files: PHP can read and write files on the server.
Database interaction: PHP can connect to databases (like MySQL) to retrieve
and store data.
Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$name = "IWC";
?>
</body>
</html>
Output
Syntax of PHP
Case-Sensitivity:
o PHP is case-sensitive for variables and keywords.
$myVariable is different from $myvariable.
Semicolons:
o Most statements in PHP must end with a semicolon (;).
Comments:
o Single-line comments:
// This is a single-line comment
o Multi-line comments:
/* This is a multi-line comment */
Whitespace:
o PHP generally ignores extra spaces, tabs, and newlines within code b locks.
Example:
<?php
/* This is a
multi-line comment */
?>
Output