What is PHP
What is PHP
PHP is an open-source general purpose scripting language, widely used for website development.
It is developed by Rasmus Lerdorf. PHP stands for a recursive acronym PHP: Hypertext
Preprocessor.
PHP is the world’s most popular server-side programming language. Its latest version PHP
8.3.13, released on October 24th, 2024.
A large number of reusable classes and libraries are available on PEAR and Composer. PEAR
(PHP Extension and Application Repository) is a distribution system for reusable PHP libraries
or classes. Composer is a dependency management tool in PHP.
PHP one of the most preferred languages for creating interactive websites and web applications.
PHP scripts can be easily embedded into HTML.
A number of PHP based web frameworks have been developed to speed-up the web application
development. The examples are WordPress, Laravel, Symfony etc.
Some of the most notable advantages of using PHP are listed below −
PHP is a multi-paradigm language that supports imperative, functional, object-oriented,
and procedural programming methodologies.
PHP is a server-side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
PHP is integrated with a number of popular databases
including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module
on the Unix side. The MySQL server, once started, executes even very complex queries with
huge result sets in record-setting time.
PHP supports a number of protocols such as POP3, IMAP, and LDAP. PHP supports
distributed object architectures (COM and CORBA), which makes n-tier development possible.
PHP is forgiving: PHP language tries to be as forgiving as possible.
PHP has a familiar C-like syntax.
Features of PHP
Over the years, PHP has incorporated numerous features. It is being consistently upgraded with
new features and code revisions. In this chapter, let's highlight some of the key features of PHP:
PHP is Simple and Easy to Learn
The syntax of PHP compared to that of C, Java, and Perl, which makes it rather simple for
developers to comprehend, particularly for those who are already familiar with other
programming languages. Web apps can be developed quickly because of its generous pre-
defined functions.
PHP is free and open-source, meaning we can download it for free, and anyone can use it,
modify it, and distribute. This encourages a sizable and vibrant developer community that uses
forums, tutorials, and documentation to support and contribute to its development.
Numerous operating systems including Windows, Linux, macOS, and UNIX; and different
databases like MongoDB, PostgreSQL, MySQL are compatible with PHP.
PHP-based apps can operate on several environments without requiring any modifications due to
this cross-platform inter-operability.
PHP is mainly used for server-side scripting, which runs scripts on the web server and then
forwards the HTML they process to the web browser on the client. It helps the developers in
Form Submission and Session Management with users across multiple requests.
PHP offers strong database interaction support for various DBMS. It offers numerous built-in
functions to achieve the database connection.
PHP also includes database abstraction layer which integrates the communication between the
application and the database. This makes it simple for developers to design database-driven web
applications.
PHP provides extensive libraries for various functionalities like image processing, encryption,
PDF generation, parsing XML and JSON, handling sessions and cookies, and much more.
Security Features in PHP
PHP provides a plethora of built-in functions for data encryption. Developers can also leverage
third-party applications for security.
PHP employs security algorithms like Sha1 and MD5 to encrypt strings. Additionally, functions
like filter_var and strip_tags contribute in maintaining a secure environment for the users. PHP
also supports secure communication protocols like HTTPS.
PHP is a reliable language due to its efficient memory management and session management. It
avoids unnecessary memory allocation.
PHP code runs in its own memory space which makes it faster compared to other scripting
languages making it more efficient. In PHP, the database connections are also fast.
PHP - Syntax
The syntax rules of PHP are very similar to C Language. PHP is a server side scripting language.
A PHP code is stored as a text file with ".php" extension. A ".php" file is essentially a web page
with one or more blocks of PHP code interspersed in the HTML script. However, it must be
opened in a browser with a HTTP protocol URL. In other words, if you double-click on the PHP
file icon, it will be opened locally with the file protocol. For example, if you open the
"index.php" file in the document root folder of your Apache server, it may just show the text of
the PHP code. However, if you launch the Apache server and open the
URL http://localhost/index.php, it displays the Apache home page.
A ".php" file may contain HTML, CSS and JavaScript code blocks along with the PHP code.
Hence, the PHP parser must differentiate between the PHP code from the other elements. When
a ".php" file is opened in the web browser, the HTML engine renders the HTML/CSS/JavaScript
part and escapes out of the HTML block as soon as the statements included in PHP tags are
encountered. The PHP parser interpreter processes this block and returns the response to the
browser.
A statement in PHP is any expression that is followed by a semicolon (;). Any sequence of valid
PHP statements that is enclosed by the PHP tags is a valid PHP program.
Here is a typical statement in PHP, which in this case assigns a string of characters to a variable
called "$greeting" −
A physical line in the text editor doesn’t have any significance in a PHP code. There may be
multiple semicolon-terminated statements in a single line. On the other hand, a PHP statement
may spill over more than one line if required.
The smallest building blocks of PHP are the indivisible tokens such as numbers (3.14159),
strings ("two"), variables ($two), constants (TRUE), and the special words that make up the
syntax of PHP itself like "if", "else", "while", "for", and so forth.
Although statements cannot be combined like expressions, you can always put a sequence of
statements anywhere a statement can go, by enclosing them in a set of curly braces.
if (3 == 2 + 1)
print("Good - I haven't totally lost my mind.");
if (3 == 2 + 1) {
print("Good - I haven't totally");
print("lost my mind.");
}
PHP is a case sensitive language. The names of various PHP identifiers such as variable,
function, class, etc., are case sensitive. As a result, the variable "$age" is not the same as "$Age".
Similarly, a function called "myfunction()" is different from another function called
"MyFunction()".
PHP provides robust database connectivity features, supporting a wide range of DBMSs,
including MySQL, PostgreSQL, SQLite, Oracle, and more. This flexibility allows developers
to work with their preferred database system seamlessly.
To establish a database connection in PHP, developers typically provide connection details, such
as the server address, username, password, and database name. Once the connection is
established, PHP applications can execute SQL queries and retrieve the results, enabling efficient
data manipulation and retrieval.
Database connectivity in PHP facilitates the creation of dynamic and data-driven web
applications. It allows developers to store user information, manage content, implement user
authentication, and handle complex data relationships. With PHP's database connectivity,
applications can seamlessly integrate and leverage the power of relational databases.
It is important to note that database connectivity in PHP also involves considerations for
security, such as protecting against SQL injection attacks by properly sanitizing and validating
user input, implementing prepared statements or parameterized queries, and applying appropriate
access controls to safeguard sensitive data.
PHP's database connectivity capabilities provide developers with the necessary tools to create
robust and interactive web applications that effectively store, retrieve, and manipulate
data from various relational databases.
What is MySQL?
MySQL is a popular and widely used open-source relational database management system
(DBMS) that is commonly integrated with PHP. It is a key component in web development,
allowing developers to efficiently store, manage, and retrieve structured data.
In the context of PHP, MySQL serves as the database backend where PHP applications can store
and retrieve data. PHP provides built-in functions and extensions that facilitate seamless
interaction with MySQL databases. These functions enable developers to establish database
connections, execute SQL queries, and handle the results.
MySQL supports essential features of a relational database, including tables, rows, and columns,
allowing developers to define the structure of their data. It provides a robust query language,
SQL (Structured Query Language), which is used to manipulate and retrieve data from the
database.
With MySQL, PHP applications can perform various database operations, such as inserting new
records, updating existing data, deleting data, and executing complex queries involving joins and
aggregations. MySQL's performance, scalability, and reliability make it a preferred choice for
small to large-scale web applications.
Additionally, MySQL offers features like transactions, indexes, and data integrity constraints to
ensure data consistency and reliability. It also provides administrative tools and utilities for
database management, backup, and performance optimization. MySQL plays a significant role in
PHP web development, providing a reliable and efficient backend database solution. Its
integration with PHP enables developers to build robust and scalable applications that effectively
handle data storage and retrieval requirements.
There are 3 types of methods in PHP to connect MySQL database through the backend:
1. MySQL
2. MySQLi
3. PDO
mysql() is now obsolete because of security issues like SQL injection etc, but the other two are
being actively used.
1. MySQLi
MySQLi is an API that serves as a connector function, linking the backend of PHP applications
to MySQL databases. It is an improvement over its predecessor, offering enhanced safety, speed,
and a more extensive set of functions and extensions.MySQLi was introduced with PHP 5.0.0,
and its drivers were installed in version 5.3.0. The API was designed to support MySQL versions
4.1.13 and newer.
2. PDO
The PHP Data Objects (PDO) extension is a Database Abstraction Layer that serves as an
interface for the backend to interact with MySQL databases. It allows for changes to be made to
the database without altering the PHP code and provides the flexibility to work with multiple
databases. One of the significant advantages of using PDO is that it keeps your code simple and
portable.
After installing XAMPP, you must add a password to your account for added security. To do
this, navigate to the User Account section and locate the username shown in the image below.
From there, you can set a password for your account.
To set a password for your XAMPP account, click on the Edit Privileges button and navigate to
the Change Admin Password section. Enter your password and click Save to update your
account. Be sure to remember this password, as you’ll need it to connect to your database.
Note: While it is not strictly necessary to change the password for accessing databases on
your localhost, it is considered good practice to do so. For this reason, we have chosen to use a
password for added security.
1. Create Database
Now return to the homepage of PHPMyAdmin. Click the New button to create a new database.
In the new window, enter a name for your database. For this tutorial, we’ll name it “practice”.
Next, select utf8_general_ci as the collation, as this will handle all the queries and data covered
in this tutorial series. Finally, click on Create to create your new database.
Currently, the newly created database is empty because it contains no tables. In the upcoming
series, we’ll learn how to create tables and insert data into them. Let’s focus on connecting the
database to localhost using PHP.
First, navigate to the XAMPP installation folder and open the htdocs subfolder (usually located
at C:\xampp). Inside htdocs, create a new folder named “practice” where we’ll store our web
files. We must create a folder in htdocs because XAMPP uses the folders within htdocs to
execute and run PHP sites.
Note: If you’re using WAMP instead of XAMPP, make sure to create the practice folder
within the C:\wamp\www directory.
3. Create Database Connection File in PHP
Create a new file named db_connection.php and save it as a PHP file. We need a separate file
for the database connection because it allows us to reuse the same connection code across
multiple files. If several files need to interact with the database, you can simply include
the db_connection.php file instead of writing the connection code multiple times.
1. <?php
2. function OpenCon()
3. {
4. $dbhost = "localhost";
5. $dbuser = "root";
6. $dbpass = "1234";
7. $db = "example";
8. $conn = new mysqli($dbhost, $dbuser, $dbpass,$dbname) or die("Connect failed: %s\n".
$conn -> error);
9. return $conn;
10. }
11. function CloseCon($conn)
12. {
13. $conn -> close();
14. }
15. ?>
Let’s take a closer look at the variables used in our db_connection.php file and their purpose:
1. $dbhost: This variable specifies the host where your RAID server is running. It’s usually
set to localhost.
2. $dbuser: This variable specifies the username for accessing the database. For example, it
could be set to root.
3. $dbpass: This variable specifies the database password. It should be the same password
you use to access PHPMyAdmin.
4. $dbname: This variable specifies the database name you want to connect to. In this
tutorial, we created a database with a specific name, so you should use that name here.
To use the database connection in your code, simply include the connection.php file at the top
of your script using PHP’s include function (e.g., include ‘connection.php’). This allows you to
call and use the connection functions throughout your code.
If you need to change the connection details, you only have to update them in one place, and the
changes will automatically apply to all other files that include the connection.php file.
To connect to your database, create a new PHP file named index.php and add the following code
to it:
1. <?php
2. include 'db_connection.php';
3. $conn = OpenCon();
4. echo "Connected Successfully";
5. CloseCon($conn);
6. ?>
To view the index page, open your web browser and navigate to localhost/practice/index.php.
You should see the following screen:
Great job! You’ve successfully connected your database to your localhost. If you’re unable to
see the expected screen, double-check the contents of your db_connection.php file to ensure
everything is set up correctly.
XAMPP TUTORIAL
XAMPP is one of the widely used cross-platform web servers, which helps developers to create
and test their programs on a local webserver. It was developed by the Apache Friends, and its
native source code can be revised or modified by the audience. It consists of Apache HTTP
Server, MariaDB, and interpreter for the different programming languages like PHP and Perl.
It is available in 11 languages and supported by different platforms such as the IA-32 package of
Windows & x64 package of macOS and Linux.
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. It is a platform that furnishes a suitable environment to test
and verify the working of projects based on Apache, Perl, MySQL database, and PHP through
the system of the host itself. Among these technologies, Perl is a programming language used for
web development, PHP is a backend scripting language, and MariaDB is the most vividly used
database developed by MySQL. The detailed description of these components is given below.
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.