0% found this document useful (0 votes)
2 views31 pages

php_notes

PHP is an open-source, server-side scripting language widely used for web development, allowing dynamic content generation and database interaction. Created by Rasmus Lerdorf in 1994, PHP has evolved through various versions, with the latest being PHP 8.2.8 released in 2023, offering features like object-oriented programming, a rich standard library, and strong community support. Despite its advantages, PHP has limitations in customization and security, making it less suitable for certain advanced applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views31 pages

php_notes

PHP is an open-source, server-side scripting language widely used for web development, allowing dynamic content generation and database interaction. Created by Rasmus Lerdorf in 1994, PHP has evolved through various versions, with the latest being PHP 8.2.8 released in 2023, offering features like object-oriented programming, a rich standard library, and strong community support. Despite its advantages, PHP has limitations in customization and security, making it less suitable for certain advanced applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

What is PHP?

PHP is an open-source, interpreted, and object-oriented scripting language that can be executed at the
server-side. PHP is well suited for web development. Therefore, it is used to develop web applications (an
application that executes on the server and generates the dynamic page.).

PHP stands for a recursive acronym PHP: Hypertext Preprocessor. PHP is the world’s most popular server-
side programming language. PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995.
Its latest version PHP 8.2.8, released on July 4th, 2023.

PHP is a server-side scripting language that is embedded in HTML. PHP is a cross-platform language, capable
of running on all major operating system platforms and with most of the web server programs such as
Apache, IIS, lighttpd and nginx.

Features Of PHP

1. Server-Side Scripting: PHP runs on the web server, allowing for dynamic content generation and
interaction with databases and other resources. This keeps sensitive logic and data processing on the server-
side, improving security and performance.

2. Open Source and Free: PHP is an open-source language, freely available for anyone to use and modify.
This fosters a large community of developers contributing to its ongoing development and vast amount of
available resources.

3. Ease of Use: PHP has a relatively simple syntax, making it easier to learn compared to some other
programming languages. This allows developers to get started quickly and build basic web applications with
minimal effort.

4. Object-Oriented Programming (OOP): While not mandatory, PHP supports object-oriented programming
principles. This allows for better code organization, reusability, and maintainability when building complex
applications.

5. Rich Standard Library: PHP comes with a large collection of built-in functions for common tasks like
database interaction, string manipulation, user input validation, and more. This reduces the need for
developers to write repetitive code

6. Database Integration: PHP seamlessly integrates with various popular databases like MySQL, PostgreSQL,
and Oracle. This allows websites to store and retrieve information dynamically, making them more
interactive and data-driven.

1
7. Security Features: While security ultimately depends on the developer's practices, PHP offers features
like input validation and user authentication mechanisms to help prevent common web security
vulnerabilities.

8. Flexibility and Scalability: PHP can be used for a wide range of projects, from simple web pages to
complex e-commerce applications and content management systems (CMS). It can also scale well to handle
increasing website traffic and user demands.

History of PHP

1. PHP/FI(Forms Interpreter) (1994-1997):

* Created by Rasmus Lerdorf for his personal website.

* Tracked visitors and displayed basic dynamic content.

* The humble beginnings of a future powerhouse.

2. PHP 2.0 (1997):

* A short-lived stepping stone with only one official release.

* Introduced basic database support and user-defined functions.

* Marked the transition from simple tools to a structured language.

3. PHP 3.0 (1998):

* A major turning point with features like extensibility, object-oriented programming, and consistent syntax.

* Significant performance and stability improvements compared to earlier versions.

* Laid the foundation for modern PHP functionalities.

4. PHP 4.0 (2000):

* Powered by the new Zend Engine for increased performance and modularity.

* Expanded capabilities with enhanced web server support, HTTP sessions, and secure user input handling.

* Solidified PHP as a powerful and versatile web development language.

5. PHP 5.0 (2004):

* Introduced a completely new object model with Zend Engine 2.0.

* Improved object-oriented programming capabilities, error handling, and core libraries.

2
* Marked a significant step forward in PHP's maturity and functionality.

6. Cancelled Project (PHP 6.0):

* Attempted major changes like Unicode support but encountered technical issues.

* Development efforts shifted to focus on the next big thing - PHP 7.

7. PHP 7.0 (2015):

* Delivered a significant performance boost, making PHP faster and more efficient.

* Introduced modern features like strict typing declarations, anonymous functions, and the null coalescing
operator.

* A major leap forward in both performance and embracing modern language features.

8. PHP 8.0 (2020):

* Continued performance optimizations and language improvements.

* Introduced Just-in-Time (JIT) compilation for even faster execution, union types, and match expressions.

* Solidified PHP's position as a high-performance language for modern web development.

Advantages of PHP

1. Open-source and Free-to-use

PHP is an open-source language, which means it is free to use by developers. It is also one of the oldest
scripting languages that are used by many popular brands. It does not require any fee to use frameworks,
libraries, and databases.

2. Easy to Learn and Use

PHP has a vast set of tutorials, resources, and other insights that anyone can use to learn this language
effortlessly. At the same time, the Graphical User Interface (GUI) made this language easy to use.

3. Platform Independent

PHP language can be easily downloaded and is compatible with various platforms and operating systems.
Being the interpreted language, it executes the code itself, making it platform-independent.

4. Community Support

Even though it is an easy-to-use language, anyone with knowledge of C programming can learn and use it.
However, there will be times when you need help from experts in this field. In that case, you can ask your
queries on forums and various other platforms that largely contribute to the advancement of PHP.

3
5. Scalability

If you want to develop a website, you must be looking for ways to enhance your business. Therefore, in the
long run, you will add new features and functionalities to your web application. With the help of this scripting
language, you can complete this task. Not only can you focus on faster loading websites but integrate with
other technologies to enhance the performance.

Disadvantages of PHP

1. Limited Customization

You can create an intuitive website and web application using PHP, and it allows customization and
integration to some extent. However, if your project demands the incorporation of technologies like machine
learning, AR/VR, big data, etc., you might need to find another language to use.

2. Not the Best in Terms of Security

Being an open-source language, the ASCII text file is open for anyone to see. Hence, general people can see
the logic and even bugs in your code, making it easier for them to manipulate it. Hence, your website
becomes vulnerable to XSS and SQL injection attacks. Also, there is no default security mechanism in PHP,
leading to security concerns.

4. Less Versatility

With PHP, you get less opportunity to make modifications to the website. Therefore, you might not be able
to keep up with the required creative challenge of a website. Also, as compared to other languages, PHP is
less effective and slower to work with.

5. Less Debugging Options

The simple syntax makes PHP a perfect solution for building a dynamic website. However, with restrained
debugging opportunities, it does not handle errors well. Since the debugging tools do not identify errors
properly, debugging is a difficult task as compared to other programming languages. Hence, developers and
business owners consider it to be more prone to security concerns.

What is server-side website programming?

“Server-side scripting is a programming technique for creating code that may run software on the server
side. In other words, server-side scripting is any scripting method that may operate on a web server. At the
server end, actions such as website customization, dynamic changes in website content, response creation
to user requests, database access, and many more are carried out.Server-side scripting creates a
communication channel between a server and a client.”

4
The server-side is made up of three parts: the database, the server, the APIs, and the backend web software
written in the server-side scripting language. When a browser requests a page with server-side scripting, the
web server evaluates the script before delivering the page to the browser. In this case, script processing may
entail collecting information from a database, performing simple computations, or selecting the relevant
material to be shown on the client end. The output is provided to the web browser when the script is
processed. The web server hides the scripts from the end user until the content is delivered, making the data
and source code safer.

Static sites

The diagram below shows a basic web server architecture for a static site (a static site is one that returns the
same hard-coded content from the server whenever a particular resource is requested). When a user wants
to navigate to a page, the browser sends an HTTP "GET" request specifying its URL.

The server retrieves the requested document from its file system and returns an HTTP response containing
the document and a success status (usually 200 OK). If the file cannot be retrieved for some reason, an error
status is returned (see client error responses and server error responses).

Dynamic sites

A dynamic website is one where some of the response content is generated dynamically, only when needed.
On dynamic website HTML pages are normally created by inserting data from a database into placeholders
in HTML templates (this is a much more efficient way of storing large amounts of content than using static
websites).A dynamic site can return different data for a URL based on information provided by the user or
stored preferences and can perform other operations as part of returning a response (e.g. sending
notifications).

Most of the code to support a dynamic website must run on the server. Creating this code is known as
"server-side programming" (or sometimes "back-end scripting").

5
The diagram below shows a simple architecture for a dynamic website. As in the previous diagram, browsers
send HTTP requests to the server, then the server processes the requests and returns appropriate HTTP
responses.

Requests for static resources are handled in the same way as for static sites (static resources are any files
that don't change — typically: CSS, JavaScript, Images, pre-created PDF files, etc.).

Requests for dynamic resources are instead forwarded (2) to server-side code (shown in the diagram as a
Web Application). For "dynamic requests" the server interprets the request, reads required information from
the database (3), combines the retrieved data with HTML templates (4), and sends back a response
containing the generated HTML (5,6).

Are server-side and client-side programming the same?

They run inside different operating system environments.

Code running in the browser is known as client-side code and is primarily concerned with improving the
appearance and behaviour of a rendered web page. This includes selecting and styling UI components,
creating layouts, navigation, form validation, etc. By contrast, server-side website programming mostly
involves choosing which content is returned to the browser in response to requests. The server-side code
handles tasks like validating submitted data and requests, using databases to store and retrieve data and
sending the correct data to the client as required.

Server-side code can be written in any number of programming languages — examples of popular server-
side web languages include PHP, Python, Ruby, C#, and JavaScript (NodeJS). The server-side code has full
access to the server operating system and the developer can choose what programming language (and
specific version) they wish to use.

6
Developers typically write their code using web frameworks. Web frameworks are collections of functions,
objects, rules and other code constructs designed to solve common problems, speed up development, and
simplify the different types of tasks faced in a particular domain.

Again, while both client and server-side code use frameworks, the domains are very different, and hence so
are the frameworks. Client-side web frameworks simplify layout and presentation tasks while server-side
web frameworks provide a lot of "common" web server functionality that you might otherwise have to
implement yourself (e.g. support for sessions, support for users and authentication, easy database access,
templating libraries, etc.).

What can you do on the server-side?

Server-side programming is very useful because it allows us to efficiently deliver information tailored for
individual users and thereby create a much better user experience.

1. Companies like Amazon use server-side programming to construct search results for products, make
targeted product suggestions based on client preferences and previous buying habits, simplify purchases,
etc.
2. Banks use server-side programming to store account information and allow only authorized users to view
and make transactions. Other services like Facebook, Twitter, Instagram, and Wikipedia use server-side
programming to highlight, share, and control access to interesting content.

Some of the common uses and benefits of server-side programming are listed below.

Efficient storage and delivery of information

Server-side programming allows us to instead store the information in a database and dynamically construct
and return HTML and other types of files (e.g. PDFs, images, etc.). It is also possible to return data (JSON,
XML, etc.) for rendering by appropriate client-side web frameworks (this reduces the processing burden on
the server and the amount of data that needs to be sent).

The server is not limited to sending information from databases, and might alternatively return the result of
software tools, or data from communications services. The content can even be targeted for the type of
client device that is receiving it.

Customized user experience

Servers can store and use information about clients to provide a convenient and tailored user experience.
For example, many sites store credit cards so that details don't have to be entered again. Sites like Google
Maps can use saved or current locations for providing routing information, and search or travel history to
highlight local businesses in search results.

7
A deeper analysis of user habits can be used to anticipate their interests and further customize responses
and notifications, for example providing a list of previously visited or popular locations you may want to look
at on a map.

Controlled access to content

Server-side programming allows sites to restrict access to authorized users and serve only the information
that a user is permitted to see.Real-world examples include social-networking sites which allow users to
determine who can see the content they post to the site, and whose content appears in their feed.

Store session/state information

Server-side programming allows developers to make use of sessions — basically, a mechanism that allows a
server to store information associated with the current user of a site and send different responses based on
that information.

This allows, for example, a site to know that a user has previously logged in and display links to their emails
or order history, or perhaps save the state of a simple game so that the user can go to a site again and carry
on where they left

To Install And Configure PHP On A Windows System Using XAMPP (Which Includes Apache, Mysql, PHP,
And Perl), Follow These Steps:

1. Download XAMPP

- Visit the official XAMPP website at https://www.apachefriends.org/index.html.

- Download the latest version of XAMPP for Windows.

2.Install XAMPP

- Run the downloaded installer.

- Follow the installation wizard instructions.

- Choose the components you want to install, including Apache, MySQL, PHP, and other optional
components.

3. Start Apache and MySQL

- After installation, launch the XAMPP Control Panel.

- Start the Apache and MySQL services by clicking the "Start" button next to their names.

8
4. Testing Apache

- Open a web browser and enter `http://localhost` in the address bar.

- If Apache is running properly, you should see the XAMPP dashboard or a page indicating that Apache is
installed and running.

5. Configure PHP

- Locate the `php.ini` configuration file inside the XAMPP installation directory (usually
`C:\xampp\php\php.ini`).

- Make any necessary configuration changes in the `php.ini` file. Common configurations include settings
for error reporting, timezone, and file upload limits.

6. Testing PHP

- Create a new PHP file (e.g., `test.php`) in the `htdocs` directory within the XAMPP installation directory
(usually `C:\xampp\htdocs`).

- Open `test.php` in a text editor and add the following PHP code:

```php

<?php

phpinfo();

?>

```

- Save the file and then open a web browser.

- Enter `http://localhost/test.php` in the address bar.

- If PHP is configured correctly, you should see a page displaying PHP configuration information.

XAMPP provides a convenient way to set up a local development environment with PHP on Windows. It
includes all the necessary components for web development, allowing you to start building and testing PHP-
based applications quickly and easily.it.

9
Embedding PHP in HTML: Powering Dynamic Webpages

One of the core strengths of PHP is its ability to seamlessly integrate with HTML, the language that forms the
static structure and content of webpages. This combination allows you to create dynamic webpages that
adapt and respond based on various factors. Here's a breakdown of embedding PHP in HTML and why it's
beneficial:

Benefits of Embedding PHP

1) Mixing Code: You can embed PHP code directly within your HTML files. To distinguish it from regular
HTML, PHP code is enclosed within special tags: `<?php ?>`.
2) Server-Side Execution: When a user requests a webpage containing PHP code, the web server doesn't
send the raw HTML straight to the browser. Instead, it first executes the PHP code on the server. Keeps
sensitive logic and data processing on the server, improving security. User passwords or credit card
information never reach the user's browser.
3) Dynamic Content Generation: The executed PHP code can perform various actions like fetching data
from databases, handling user input, or performing calculations. It then generates the final HTML content
based on these actions. Lets you create webpages that change based on user input, database
information, or other factors, making them more interactive and engaging. Imagine a login page that
personalizes greetings based on the username.
4) Data Integration: Allows you to connect to databases and display information relevant to each user or
request. Think about an e-commerce website showing product details based on user searches.
5) Conditional Logic: Enables you to show or hide content based on certain conditions, personalizing the
user experience. For example, displaying a "Welcome Back" message for logged-in users.

Let's see how embedding PHP can personalize a simple greeting:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Current Date and Time</title>

</head>

10
<body>

<h1>Current Date and Time</h1>

<p>The current date and time is: <?php echo date('Y-m-d H:i:s'); ?></p>

</body>

</html>

Explanation of the PHP code section:

PHP Opening Tag: The <?php tag denotes the beginning of a PHP code block.

date() Function: The date() function is called with the format 'Y-m-d H:i:s' to retrieve the current date and
time in the specified format (Year-Month-Day Hour:Minute:Second).

Variable Assignment: The result of the date() function call is stored in the variable $currentDateTime.

Output: The echo statement outputs the current date and time along with the text "The current date and
time is: ".

When this PHP code is executed, it will dynamically generate the current date and time and output it as part
of the text "The current date and time is: " followed by the formatted date and time string.

11
HTML and Whitespaces
Whitespace is any string of text composed only of spaces, tabs or line breaks (to be precise, CRLF sequences,
carriage returns or line feeds). These characters allow you to format your code in a way that will make it
easily readable by yourself and other people. In fact, much of our source code is full of these whitespace
characters, and we only tend to get rid of it in a production build step to reduce code download sizes.
HTML largely ignores whitespace?
In the case of HTML, whitespace is largely ignored — whitespace in between words is treated as a single
character, and whitespace at the start and end of elements and outside elements is ignored. Take the
following minimal example:

<h1> Hello World!


</h1>
This source code contains a couple of line break bunch of space characters before, after, and inside
the <h1> element, but the browser doesn't seem to care at all and just shows the words "Hello World!" as if
these characters didn't exist at all

What happens to whitespace?


They don't just disappear, however. Any whitespace characters that are outside of HTML elements in the
original document are represented in the DOM. This is needed internally so that the editor can preserve
formatting of documents. This means that: There will be some text nodes that contain only whitespace, and
Some text nodes will have whitespace at the beginning or end.

Take the following document, for example:


<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>My Document</title>
</head>

12
<body>
<h1>Header</h1>
<p>Paragraph</p>
</body>
</html>

The DOM tree for this looks like so:

Whitespace and Line Breaks and PHP


In general, whitespace doesn’t matter in a PHP program. You can spread a statement across any number of
lines, or lump a bunch of statements together on a single line. For example, this statement:
raisePrices($inventory, $inflation, $costOfLiving, $greed);
could just as well be written with more whitespace:
raisePrices (
$inventory ,
$inflation ,
$costOfLiving ,
$greed
);
or with less whitespace:

13
raisePrices($inventory,$inflation,$costOfLiving,$greed);
You can take advantage of this flexible formatting to make your code more readable (by lining up
assignments, indenting, etc.). Some lazy programmers take advantage of this freeform formatting and create
completely unreadable code—this is not recommended.

Writing Comments In Php


In PHP, you can add comments to your code to provide explanations, documentation, or reminders for
yourself or other developers who might work with the code. PHP supports two types of comments: single-
line comments and multi-line comments.
1) Single line Comments:
In PHP, single-line comments are used to annotate code or provide explanations on a single line. These
comments are ignored by the PHP interpreter and do not affect the execution of the code. Single-line
comments begin with two forward slashes (`//`) or (#) and extend to the end of the line. Here's an
explanation of single line commenting in PHP:
<?php
// This is a single-line comment
#This is another single-line comment
echo "Hello, World!";
?>
In the example above:
This is a single-line comment`: This comment begins with `//` and ‘#’extends to the end of the line. It provides
a brief explanation of the following code or annotates it.
Single-line comments are useful for documenting code, adding reminders, or temporarily disabling code
without removing it entirely. They help improve code readability and maintainability by providing insights
into the purpose and functionality of different parts of the codebase. Additionally, single-line comments are
often used for quick annotations or explanations that don't require extensive formatting or documentation.
2) Multi line Comments:
In PHP, multi-line comments are used to add explanations, documentation, or comments that span multiple
lines in your code. They are also commonly used to temporarily disable blocks of code without deleting them.
Multi-line comments in PHP begin with `/*` and end with `*/`. Here's how you can use multi-line comments
in PHP:
<?php

14
/*
This is a multi-line comment in PHP.
It can span multiple lines and is ignored by the PHP interpreter.
Multi-line comments are useful for providing detailed explanations or
commenting out large blocks of code temporarily.
*/
echo "Hello, World!";
?>

In the above example:


The `/*` symbol marks the beginning of the multi-line comment. Everything between `/*` and `*/`, including
line breaks and any text or code within, is considered a comment and ignored by the PHP interpreter.The
comment ends with the `*/` symbol.
Multi-line comments are particularly useful when you need to provide extensive documentation for
functions, classes, or sections of code, or when you want to temporarily disable large blocks of code for
debugging or testing purposes. They help improve code readability, facilitate collaboration among
developers, and make it easier to understand the purpose and functionality of different parts of your
codebase.
SENDING DATA TO THE WEB
PHP provides two methods through which a client (browser) can send information to the server. These
methods are given below, and discussed in detail:
1. GET method
2. POST method
Get and Post methods are the HTTP request methods used inside the <form> tag to send form data to the
server.HTTP protocol enables the communication between the client and the server where a browser can
be the client, and an application running on a computer system that hosts your website can be the server.
GET method
The GET method is used to submit the HTML form data. This data is collected by the predefined $_GET
variable for processing.
The information sent from an HTML form using the GET method is visible to everyone in the browser's
address bar, which means that all the variable names and their values will be displayed in the URL. Therefore,
the get method is not secured to send sensitive information.
For Example
1. localhost/gettest.php?username=Harry&bloodgroup=AB+
The bold part in the above URL is the variables name and italic part contains the values for their
corresponding variable.
Example

15
The below code will display an HTML form containing two input fields and a submit button. In this HTML
form, we used the method = "get" to submit the form data.
1. <html>
2. <body>
3. <form action = "gettest.php" method = "GET">
4. Username: <input type = "text" name = "username" /> <br>
5. Blood Group: <input type = "text" name = "bloodgroup" /> <br>
6. <input type = "submit" />
7. </form>
8. </body>
9. </html>

Create php file, which will accept the data sent by HTML form.
1. <html>
2. <body>
3. Welcome <?php echo $_GET["username"]; ?> </br>
4. Your blood group is: <?php echo $_GET["bloodgroup"]; ?>
5. </body>
6. </html>
When the user will click on Submit button after filling the form, the URL sent to the server could look
something like this:
localhost/gettest.php?username=Harry&bloodgroup=AB-
The output will look like the below output:

Welcome Harry
Your blood group is: AB-

Advantages of GET method (method = "get")


o You can bookmark the page with the specific query string because the data sent by the GET method
is displayed in URL.
o GET requests can be cached.

16
o GET requests are always remained in the browser history.
Disadvantages of GET Method
o The GET method should not be used while sending any sensitive information.
o A limited amount of data can be sent using method = "get". This limit should not exceed 2048
characters.
o For security reasons, never use the GET method to send highly sensitive information like username
and password, because it shows them in the URL.
o The GET method cannot be used to send binary data (such as images or word documents) to the
server.
POST method
Similar to the GET method, the POST method is also used to submit the HTML form data. But the data
submitted by this method is collected by the predefined superglobal variable $_POST instead of $_GET.
Unlike the GET method, it does not have a limit on the amount of information to be sent. The information
sent from an HTML form using the POST method is not visible to anyone.
For Example
1. localhost/posttest.php
Note that the "post" method is more secure than the "get" method because the data sent using the POST
method is not visible to user.
With the help of an example, let's understand how the POST method works-
Example
The below code will display an HTML form containing two input fields and a submit button. In this HTML
form, we used the method = "post" to submit the form data.
file: test2.html
1. <html>
2. <body>
3. <form action = "posttest.php" method = "post">
4. Username: <input type = "text" name = "username" /> <br>
5. Blood Group: <input type = "text" name = "bloodgroup" /> <br>
6. <input type = "submit" />
7. </form>
8. </body>
9. </html>

17
Now create posttest.php file to accept the data sent by HTML form.
file: posttest.php
1. <html>
2. <body>
3. Welcome <?php echo $_POST["username"]; ?> </br>
4. Your blood group is: <?php echo $_POST["bloodgroup"]; ?>
5. </body>
6. </html>
When the user will click on Submit button after filling the form, the URL sent to the server could look
something like this:
localhost/posttest.php
The output will look like the below output:

Welcome Harry
Your blood group is: O+

Advantages of POST method (method = "post")


o The POST method is useful for sending any sensitive information because the information sent using
the POST method is not visible to anyone.
o There is no limitation on size of data to be sent using the POST Method. You can send a large amount
of information using this method.
o Binary and ASCII data can also be sent using the POST method.
o Data security depends on the HTTP protocol because the information sent using the POST method
goes through the HTTP header. By using secure HTTP, you can ensure that your data is safe.
Disadvantages of POST Method
o POST requests do not cache.
o POST requests never remain in the browser history.
o It is not possible to bookmark the page because the variables are not displayed in URL.

18
$_REQUEST variable
The $_REQUEST variable is a superglobal variable, which can hold the content of both $_GET and $_POST
variable. In other words, the PHP $_REQUEST variable is used to collect the form data sent by either GET or
POST methods. It can also collect the data for $_COOKIE variable because it is not a method-specific variable.
You can access this data with the $_REQUEST keyword followed by variable name

$_REQUEST['firstname']

Using $_REQUEST on $_POST Requests


POST request are usually data submitted from an HTML form.
Here is an example of how a HTML form could look like:

<html>
<body>
<form method="post" action="demo_request.php">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>

When a user clicks the submit button, the form data is sent to a PHP file specified in the action attribute of
the <form> tag.In the action file we can use the $_REQUEST variable to collect the value of the input field.
PHP file

$name = $_REQUEST['fname'];
echo $name;

19
In the example below we have put the HTML form and PHP code in the same PHP file.We have also added
some extra lines for security.

<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>

Using $_REQUEST on $_GET Requests


GET request can be form submissions as in the example above, with the method attribute of the HTML
<form> element set to GET.GET requests can also be data from a query string (information added after a URL
address).Here is an example of how an HTML hyperlink, with a query string could look like:

<html>
<body>
<a href="demo_phpfile.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body>
</html>
When a user clicks the link, the query string data is sent to demo_phpfile.php.
In the PHP file we can use the $_REQUEST variable to collect the value of the query string.
Example
The PHP file demo_phpfile.php:

20
<html>
<body>
<?php
echo "Study " . $_REQUEST['subject'] . " at " . $_REQUEST['web'];
?>
</body>
</html>

What are PHP Keywords?


PHP keywords are predefined, reserved words in PHP that are used to perform specific functions. These
keywords are reserved by PHP and cannot be used as variable names, function names, or class names. PHP
keywords are case-insensitive, meaning that they can be written in either upper or lower case letters.
List of PHP Keywords

abstract and array as break callable


case catch class clone const continue
declare default die do echo else
elseif empty enddeclare endfor endforeach endif
endswitch endwhile extends final finally for
foreach function global goto if implements
include include_once instanceof insteadof interface
isset list namespace new or print
private protected public require require_once return
static switch throw trait try unset
use var while xor yield __halt_compiler
Copy

Usage of PHP Keywords


Keywords are used in PHP to define certain statements, constructs, and functions. For example,
the if keyword is used to define a conditional statement, the while keyword is used to define a loop, and
the function keyword is used to define a function.
Here is an example of using some of the PHP keywords:

21
<?php
$x = 7;
// Define a conditional statement
if ($x == 5) {
echo "x is equal to 5.";
}
// Define a function
function add($a, $b)
{
return $a + $b;
} ?>
Data Types
PHP provides eight types of values, or data types. Four are scalar (single-value) types: integers, floating-point
numbers, strings, and Booleans. Two are compound (collection) types: arrays and objects. The remaining
two are special types: resource and NULL. Numbers
1)Integers: integers are whole numbers, such as 1, 12, and 256. The range of acceptable values varies
according to the details of your platform but typically extends from −2,147,483,648 to +2,147,483,647.
Integer literals can be written in decimal, octal, or hexadecimal. Decimal values are represented by a
sequence of digits, without leading zeros. The sequence may begin with a plus (+) or minus (−) sign. If there
is no sign, positive is assumed. Examples of decimal integers include the following:
1998,−641,+33
Octal numbers consist of a leading 0 and a sequence of digits from 0 to 7. Like decimal numbers, octal
numbers can be prefixed with a plus or minus. Here aresome example octal values and their equivalent
decimal values:
0755 // decimal 493
+010 // decimal 8
Hexadecimal values begin with 0x, followed by a sequence of digits (0–9) or letters (A–F). The letters can be
upper-or lowercase but are usually written in capitals. Like decimal and octal values, you can include a sign
in hexadecimal numbers:
0xFF // decimal 255
0x10 // decimal 16
-0xDAD1 // decimal −56017
Binary numbers begin with 0b, followed by a sequence of digits (0 and 1). Like other values, you can include
a sign in binary numbers:
0b01100000 // decimal 1
0b00000010 // decimal 2

22
Use the is_int() function (or its is_integer() alias) to test whether a value is
an integer:
if (is_int($x)) {
// $x is an integer
}
2) Floating-Point Numbers
Floating-point numbers (often referred to as real numbers) represent numeric values with decimal digits.
Like integers, their limits depend on your machine’s details Usually, this allows numbers between 1.7E−308
and 1.7E+308 with 15 digits of accuracyPHP recognizes floating-point numbers written in two different
formats. There’s the one we all use every day:
3.14,0.017,-7.1
but PHP also recognizes numbers in scientific notation:
0.314E1 // 0.314*10^1, or 3.14
17.0E-3 // 17.0*10^(-3), or 0.017
Floating-point values are only approximate representations of numbers. For example, on many systems 3.5
is represented as 3.4999999999. This means you must take care to avoid writing code that assumes floating-
point numbers are represented completely accurately, such as directly comparing two floating-point values
using ==. The normal approach is to compare to several decimal places:
if (intval($a * 1000) == intval($b * 1000)) {
// numbers equal to three decimal places
}
Use the is_float() function (or its is_real() alias) to test whether a value is a floating-point number:
if (is_float($x)) {
// $x is a floating-point number
}
3)Strings: PHP includes core-level support for creating and manipulating strings. A string is a sequence of
characters of arbitrary length. String literals are delimited by either single or double quotes:
'big dog'
"fat hog"
Variables are expanded (interpolated) within double quotes, while within single quotes they are not:
$name = "Guido";
echo "Hi, $name\n";
echo 'Hi, $name';
Hi, Guido
Hi, $name

23
Double quotes also support a variety of string escapes, as listed. Escape sequence Character represented
\" Double quotes
\n Newline
\r Carriage return
\t Tab
\\ Backslash
\$ Dollar sign
\{ Left brace
\} Right brace
\[ Left bracket
\] Right bracket
To test whether two strings are equal, use the == (double equals) comparison
operator:
if ($a == $b) {
echo "a and b are equal"
}
Use the is_string() function to test whether a value is a string:
if (is_string($x)) {
// $x is a string
}
4) Booleans
A Boolean value represents a “truth value”—it says whether something is true or not. Like most
programming languages, PHP defines some values as true and others as false. Truth and falseness determine
the outcome of conditional code
In PHP, the following values all evaluate to false:
The keyword false
The integer 0
The floating-point value 0.0
The empty string ("") and the string "0"
An array with zero elements
An object with no values or functions
The NULL value
PHP provides true and false keywords for clarity:

24
$x = 5; // $x has a true value
$x = true; // clearer way to write it
$y = ""; // $y has a false value
$y = false; // clearer way to write it
Use the is_bool() function to test whether a value is a Boolean:
if (is_bool($x)) {
// $x is a Boolean
}

5)Arrays
In PHP, an array is a data structure that can hold multiple values under a single variable name. Arrays are
incredibly versatile and commonly used for storing and manipulating collections of data. PHP supports
several types of arrays, including indexed arrays, associative arrays, and multidimensional arrays.
1. Indexed Arrays:
An indexed array is a simple list of values, where each value is assigned a numeric index starting from zero.
You can create an indexed array using the `array()` function or using shorthand square bracket syntax (`[]`)
since PHP 5.4.Elements of an indexed array are accessed using numeric indices.
// Creating an indexed array
$colors = array("Red", "Green", "Blue");
// Accessing elements of an indexed array
echo $colors[0]; // Output: Red
echo $colors[1]; // Output: Green
echo $colors[2]; // Output: Blue

2. Associative Arrays:
An associative array is a collection of key-value pairs, where each key is associated with a value. You can
create an associative array using the `array()` function with key-value pairs or using shorthand square bracket
syntax (`[]`) .Elements of an associative array are accessed using their keys.
// Creating an associative array
$person = array("name" => "John", "age" => 30, "city" => "New York");
// Accessing elements of an associative array
echo $person["name"]; // Output: John
echo $person["age"]; // Output: 30

25
echo $person["city"]; // Output: New York
3. Multidimensional Arrays:
A multidimensional array is an array that contains one or more arrays as its elements. You can create
multidimensional arrays by nesting arrays inside arrays.Elements of multidimensional arrays are accessed
using multiple indices corresponding to each level of nesting.
// Creating a multidimensional array
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
// Accessing elements of a multidimensional array
echo $matrix[0][0]; // Output: 1
echo $matrix[1][1]; // Output: 5
echo $matrix[2][2]; // Output: 9
```
6)Objects
PHP also supports object-oriented programming (OOP). OOP promotes clean modular design, simplifies
debugging and maintenance, and assists with code reuse. Classes are the building blocks of object-oriented
design. A class is a definition of a structure that contains properties (variables) and methods (functions).
Classes are defined with the class keyword:

class Person{
public $name = '';
function name ($newname = NULL){
if (!is_null($newname)) {
$this->name = $newname;
}
return $this->name;
}
}

Once a class is defined, any number of objects can be made from it with the new keyword, and the object’s
properties and methods can be accessed with the -> construct:

$ed = new Person;


$ed->name('Edison');

26
echo "Hello, {$ed->name}\n";
$tc = new Person;
$tc->name('Mister');
echo "Look out Above {$tc->name}\n";

Hello, Edison
Look out Above Mister
Use the is_object() function to test whether a value is an object:
if (is_object($x)) {
// $x is an object
}
7)Resources
Many modules provide several functions for dealing with the outside world. For example, every database
extension has at least a function to connect to the database, a function to send a query to the database, and
a function to close the connection to the database. Because you can have multiple database connections
open at once, the connect function gives you something by which to identify that unique connection when
you call the query and close functions: a resource (or a “handle”).
Each active resource has a unique identifier. Each identifier is a numerical index into an internal PHP lookup
table that holds information about all the active resources. PHP maintains information about each resource
in this table, including the number of references to (or uses of) the resource throughout the code. When the
last reference to a resource value goes away, the extension that created the resource is called to free any
memory, close any connection, etc., for that resource:
$res = database_connect(); // fictitious database connect function
database_query($res);
$res = "boo";
// database connection automatically closed because $res is redefined
The benefit of this automatic cleanup is best seen within functions, when the resource is assigned to a
local variable. When the function ends, the variable’s value is reclaimed by PHP:
function search() {
$res = database_connect();
database_query($res);
}
Use the is_resource() function to test whether a value is a resource:
if (is_resource($x)) {
// $x is a resource
}

27
8)NULL
There’s only one value of the NULL data type. That value is available through the case-insensitive keyword
NULL. The NULL value represents a variable that has no value (similar to Perl’s undef or Python’s None):
$aleph = "beta";
$aleph = null; // variable's value is gone
$aleph = Null; // same
Use the is_null() function to test whether a value is NULL—for instance, to see whether a variable has a
value:
if (is_null($x)) {
// $x is NULL
}
Variables
In PHP, variables are used to store and manipulate data. Variables in PHP are represented by a dollar sign ($)
followed by the variable name. They can store various types of data, including strings, numbers, arrays,
objects, and more.
$name
A variable may hold a value of any type. There is no compile-time or runtime type checking on variables. You
can replace a variable’s value with another of a different type:
$what = "Fred";
$what = 35;
There is no explicit syntax for declaring variables in PHP. The first time the value of a variable is set, the
variable is created. In other words, setting a value to a variable also functions as a declaration. For example,
this is a valid complete PHP program:
$day = 60 * 60 * 24;
echo "There are {$day} seconds in a day.\n";
There are 86400 seconds in a day.
A variable whose value has not been set behaves like the NULL value:
if ($uninitializedVariable === NULL) {
echo "Yes!";
}
Yes!

28
Variable Scope
In PHP, variable scope refers to the visibility and accessibility of variables within different parts of a script.
PHP variables can have either global scope or local scope, and the scope determines where the variable can
be accessed and modified. Understanding variable scope is crucial for writing well-organized and
maintainable code. Here's an overview of variable scope in PHP:
1. Local Scope:
- Variables declared inside a function have local scope and are only accessible within that function.
- Local variables are created when the function is called and destroyed when the function execution
completes.
- Local variables can have the same name as global variables without causing conflicts because they exist
in different scopes.

Example:
```php
$globalVar = "I am a global variable";
function myFunction() {
$localVar = "I am a local variable";
echo $localVar; // Output: I am a local variable
}
echo $globalVar; // Output: I am a global variable
echo $localVar; // This will throw an error because $localVar is not defined in the global scope
?>
globalVar is declared and initialized outside of any function, making it a global variable.It holds the value "I
am a global variable". myFunction() is defined as a function. Inside this function, we have: Declaration and
initialization of a local variable $localVar with the value "I am a local variable".
When myFunction() is called, it executes the code inside its block. The function echoes the value of the local
variable $localVar, which is "I am a local variable".After the function definition, the script echoes the value
of the global variable $globalVar. This results in the output: "I am a global variable".
Finally, the script tries to echo the value of the local variable $localVar outside the function.However, since
$localVar is defined only within the scope of the function, it is not accessible outside.This attempt to access
$localVar outside its scope causes a PHP error, typically something like "Undefined variable: localVar".
$globalVar is accessible both inside and outside the function because it's declared in the global scope. On
the other hand, $localVar is only accessible within the myFunction() function and not in the global scope,
resulting in an error when attempting to access it outside the function.

29
2.Global Scope:
- Variables declared outside of any function or class have global scope.
- Global variables can be accessed from anywhere in the script, including inside functions, classes, and
included files.
- To access a global variable from within a function, you need to use the `global` keyword or the `$GLOBALS`
array.
EXAMPLE
<?php
$globalVar = "I am a global variable";
function myFunction() {
global $globalVar;
echo $globalVar; // Output: I am a global variable
}
echo $globalVar; // Output: I am a global variable
?>
the global variable $globalVar is declared and initialized outside any function, making it accessible from both
the global scope and any functions in the script. Inside the myFunction() function, we explicitly declare
$globalVar as a global variable using the global keyword, allowing us to access its value within the function.
The script then outputs the value of $globalVar both inside and outside the function, resulting in the same
value being displayed twice.

3. Static Local Variables: PHP allows you to declare static local variables inside functions using the `static`
keyword.Static variables retain their value between function calls and are not destroyed when the function
execution completes.
<?php
function counter() {
static $count = 0;
$count++;
echo $count . "<br>";
}
counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3
?>

30
The counter() function is defined. Inside this function A static variable $count is declared and initialized with
the value 0. Static variables retain their value between function calls.The value of $count is then incremented
by 1.The current value of $count is echoed followed by a line break (<br>).
The counter() function is called three times consecutively:
The first function call initializes the static variable $count with 0, increments it to 1, and outputs it as "1".
The second function call increments the static variable $count from 1 to 2 and outputs it as "2".
The third function call increments the static variable $count from 2 to 3 and outputs it as "3".
The counter() function demonstrates the use of a static variable ($count) to maintain state between function
calls. The static variable retains its value across multiple function invocations, allowing us to track and
increment a counter each time the function is called.

31

You might also like