0% found this document useful (0 votes)
4 views

PHP

PHP, or PHP: Hypertext Preprocessor, is a popular open-source scripting language primarily used for web development, allowing for server-side execution and easy integration with databases. Key features include its cross-platform compatibility, ease of learning, and extensive library support. The document also outlines how to run PHP programs locally using XAMPP and provides an overview of PHP data types and methods for retrieving data from a MySQL database.

Uploaded by

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

PHP

PHP, or PHP: Hypertext Preprocessor, is a popular open-source scripting language primarily used for web development, allowing for server-side execution and easy integration with databases. Key features include its cross-platform compatibility, ease of learning, and extensive library support. The document also outlines how to run PHP programs locally using XAMPP and provides an overview of PHP data types and methods for retrieving data from a MySQL database.

Uploaded by

Jahiiid Hasan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

What is PHP?

PHP, which stands for PHP: Hypertext Preprocessor, is a widely-used open-source scripting language
designed primarily for web development1. It was created by Rasmus Lerdorf in 1993 and released in
19953. PHP is known for its ability to be embedded into HTML, making it a powerful tool for creating
dynamic web pages2.

Key Features of PHP

1. Server-Side Execution: PHP code is executed on the server, and the result is sent to the client's
browser as plain HTML1. This means that the client does not see the PHP code, only the output.

2. Open Source: PHP is free to download and use, making it accessible to a wide range of
developers1.

3. Cross-Platform: PHP runs on various platforms, including Windows, Linux, Unix, and macOS1.

4. Database Support: PHP supports a wide range of databases, including MySQL, PostgreSQL,
Oracle, and more1.

5. Ease of Learning: PHP is easy to learn for beginners and offers advanced features for
professional programmers2.

How to run PHP programs ? XAMPP is a Web development tool, created by Apache, that makes it easy
to run PHP (Personal Home Pages) scripts on your computer locally. Installation of XAMPP Server on
windows is easy as compared to manual installation of a web server and PHP required a lot of in-depth
configuration knowledge. XAMPP package installs MySQL, FileZilla, Mercury, Perl, and Tomcat along with
Web Server and PHP, with these applications you can test the full website on your desktop. You don’t
need to upload it every time on an online Web server.

Step 1: First of all, open the Apache Friends website and download XAMPP for Windows, and install it.

Step 2: Start the XAMPP Program Control Panel. Click on the “Start” button next to the “Apache” to start
your Apache Web Server. Also, start “MySQL” if your PHP programs depend on a MySQL database to run.

How to run PHP programs ?

Step 3: Place your PHP files in the “htdocs” folder located under the “XAMPP” folder on your drive (i.e.
C/D/E etc). The initial path is “your_drive_letter:\xampp\htdocs” for your Web server. Make sure that
your PHP files are saved as a “.php” file extension.

Example: The “demo.php” file is saved in the htdocs folder.

PHP<!DOCTYPE html>
<html>

<body>

<h1>Hello GFG </h1>

<?php

echo "Hello geeksforgeeks";

?>

</body>

</html>

Step 4: Open up any web browser and enter “localhost/filename”. This will open the list of all the files
and folders stored under the “htdocs” folder on your computer. Click on the link to a PHP file and open it
to run a program.

Example: The file “demo.php” file is placed inside the “htdocs” folder. If you want to run it, open any
web browser and enter “localhost/demo.php” and press enter. Your program will run.

Syntax: php have special Syntax to write a code, as shown in below

<?php
//write your code here
?>

demo.php

PHP

<!DOCTYPE html>

<html>

<body>

<h1>Hello GFG </h1>


<?php

echo "Inside gfgdemo FOLDER Hello geeksforgeeks";

?>

</body>

</html>

Step 5: You can create any folder to test PHP files under the “htdocs” folder. If you create a specific
folder then you need to use the address as “localhost/foldername” to open them in your browser.

Example: The “demo.php” file is placed inside the “gfgdemo” folder. Enter
“localhost/gfgdemo/demo.php” in your browser and press enter, your program will be run.

PHP case sensitivity

PHP is case sensitive language, in that variables and functions, tags are case sensitive but classes are not
case sensitive. Below the example of case sensitivity of php.

Example 1: echo.php

PHP

<!DOCTYPE>

<html>

<body>

<?php

echo "Hello world using echo </br>";

ECHO "Hello world using ECHO </br>";

EcHo "Hello world using EcHo </br>";

?>

</body>
</html>

In above code we write three different types of echo methods, see the output in the image.

Output:

How to run PHP programs?

Example 2: color.php

PHP

<html>

<body>

<?php

$color = "black";

echo "My car is ". $ColoR ."</br>";

echo "My dog is ". $color ."</br>";

echo "My Phone is ". $COLOR ."</br>";

?>

</body>

</html>

In the above example, the variable name is case sensitive, so it gives error.

Output:

My car is

My dog is black

My Phone is

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 Open Source


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.

PHP is Cross-Platform Compatible


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.

Server-Side Scripting in PHP


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 Supports Easy Integration with Databases


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 Library Support


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.

Efficient Memory and Session Management in PHP


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 Has Active Community and Support


Since PHP is an open-source platform, it has a vibrant community of
developers who actively contribute to its development, share knowledge,
provide support, and create third-party tools and frameworks.

Due to this active community support, PHP remains up-to-date and


developers can easily seek help from other community members in case
they get any errors or exceptions while writing PHP codes.

What are the different types of PHP variables?

Data Types

Here is a list of all the available data types and examples when creating variables in PHP:

• bool: boolean values, returning either true or false.

• int: integer numbers containing no decimals.

• float: floating-point numbers containing decimals.

• string: strings of text containing alphanumeric characters.

• array: nodes of data assigned with indexes, or positions within the contained array.

• object: data containing key/value pairs.

• null: no value assigned

PHP is not strict with data types. A variable assigned as a string could later be recreated as a numeric
value or vice versa.

PHP Data Types

Summary: in this tutorial, you will learn about PHP data types including scalar types, compound types,
and special types.

Introduction to PHP data types

A type specifies the amount of memory that allocates to a value associated with it. A type also
determines the operations that you can perform on it.

PHP has ten primitive types including four scala types, four compound types, and two special types:
Scalar types

• bool

• int

• float

• string

Compound types

• array

• object

• callable

• iterable

Special types

• resource

• null

Scalar types

A variable is a scalar when it holds a single value of the type integer, float, string, or boolean.

Integer

Integers are whole numbers defined in the set {…-3,-2-,-1,0,1,2,3…}. The size of the integer depends on
the platform where PHP runs.

The constant PHP_INT_SIZE specifies the size of the integer on a specific platform. PHP uses the int
keyword to denote the integer type.

The following example illustrates some integers:

<?php

$count = 0;

$max = 1000;

$page_size = 10;Code language: HTML, XML (xml)

Float

Floats are floating-point numbers, which are also known as floats, doubles, or real numbers.
PHP uses the IEEE 754 double format to represent floats. Like other programming languages, floats have
limited precision.

PHP uses the float keyword to represent the floating-point numbers. The following example illustrates
the floating-point numbers in PHP:

<?php

$price = 10.25;

$tax = 0.08;Code language: HTML, XML (xml)

Boolean

Boolean represents a truth value that can be either true or false. PHP uses the bool keyword to
represent the Boolean type.

The bool type has two values true and false. Since keywords are case-insensitive, you can
use true, True, TRUE, false, False, and False to indicate boolean values.

The following example shows how to assign Boolean values to variables:

<?php

$is_admin = true;

$is_user_logged_in = false;Code language: HTML, XML (xml)

When you use the values of other types in the boolean context, such as if-else and switch-
case statements, PHP converts them to the boolean values.

PHP treats the following values as false:

• The false keyword.

• The integer 0 and -0 (zero).

• The floats 0.0 and -0.0 (zero).

• The empty string ("", '') and the string “0”.

• The empty array (array() or []).

• The null.

• The SimpleXML objects created from attributeless empty elements.

The values that are not one of these falsy values above are true.

String
A string is a sequence of characters surrounded by single quotes (‘) or double quotes (“). For example:

<?php

$str = 'PHP scalar type';

$message = "PHP data types";Code language: HTML, XML (xml)

Compound types

Compound data includes the values that contain more than one value. PHP has two compound types
including array and object.

Array

An array is an ordered map that associates keys with values. For example, you can define a list of items in
a shopping cart like this:

<?php

$carts = [ 'laptop', 'mouse', 'keyboard' ];Code language: HTML, XML (xml)

The $carts array contains three string values. It maps the index 0, 1, and 2 to the values 'laptop', 'mouse',
and 'keyboard'. The $carts is called an indexed array because it uses numeric indexes as keys.

To access a value in an array, you use the square brackets:

<?php

echo $carts[0]; // 'laptop'

echo $carts[1]; // 'mouse'

echo $carts[2]; // 'keyboard'Code language: HTML, XML (xml)

Besides numeric indexes, you can use strings as keys for the array elements. These arrays are known
as associative arrays. For example:

<?php

$prices = [

'laptop' => 1000,

'mouse' => 50,

'keyboard' => 120


];Code language: HTML, XML (xml)

To access an element in an associative array, you specify the key in the square brackets. For example:

<?php

echo $prices['laptop']; // 1000

echo $prices['mouse']; // 50

echo $prices['keyboard']; // 120Code language: HTML, XML (xml)

Object

An object is an instance of a class. It’s a central concept in object-oriented programming.

An object has properties. For example, a person object may have the first name, last name, and age
properties.

An object also has behaviors, which are known as methods. For example, a person object can have a
method called getFullName() that returns the full name.

To learn more about objects, check out the object tutorial.

Special types

PHP has two special types: null and resource

Null

The null type has one value called null that represents a variable with no value.

Resource

The resource type holds a reference to an external resource, e.g. a filehandle or a database connection.

Summary

• PHP has four scalar types, four compound types, and two special types.

• Scale types: integer, float, string, and boolean.

• Compound types: array and object.

• Special types: null and resource.

• ………………………………….

4.Explain the pro How to retrieve data from


MySQL database using PHP ?
•• •
There are steps to understand for retrieving the data from the MySQL database.
Approach:
• Create the database, then create the table for data.
• Enter the rows in the table. You have to connect to the database.
Now we understand each and every step as shown below.
Example 1: In this. we use PHPMyAdmin for the database handling. Start the
server in the XAMPP as shown in the below image

XAMPP PANEL

After that create the database in the PHPMyAdmin. Open the below URL.
http://localhost/phpmyadmin/index.php
Creating the database:

creating the database in MySQL PHPMyAdmin

Create the table: Execute the SQL query in the “gfg” database.
CREATE TABLE student
(
name varchar(20),
branch varchar(20),
roll_no INT
);
Enter the data in the table.
INSERT INTO `student` ( `name`, `branch`, `roll_no`)
VALUES ( 'Rohan', 'CSE', '1' );
After the data is inserted, the table will look like this.

After entering the data in the table

PHP Code: Run the PHP script as shown below to fetch the data from the
database.
• PHP
<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "gfg";
// connect the database with the server

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

// if error occurs

if ($conn -> connect_errno)

echo "Failed to connect to MySQL: " . $conn -> connect_error;

exit();

$sql = "select * from student";

$result = ($conn->query($sql));

//declare array to store the data of database

$row = [];

if ($result->num_rows > 0)

// fetch all data from db into array

$row = $result->fetch_all(MYSQLI_ASSOC);

?>

<!DOCTYPE html>

<html>

<style>

td,th {

border: 1px solid black;


padding: 10px;

margin: 5px;

text-align: center;

</style>

<body>

<table>

<thead>

<tr>

<th>Name</th>

<th>Branch</th>

<th>Roll Number</th>

</tr>

</thead>

<tbody>

<?php

if(!empty($row))

foreach($row as $rows)

?>

<tr>

<td><?php echo $rows['name']; ?></td>

<td><?php echo $rows['branch']; ?></td>

<td><?php echo $rows['roll_no']; ?></td>


</tr>

<?php } ?>

</tbody>

</table>

</body>

</html>

<?php

mysqli_close($conn);

?>

procedure of retrieving data using PHP.

3.Briefly explain a simple PHP form validation example.

HTML Form (index.php)

php

Copy code

<!DOCTYPE html>

<html>

<head>

<title>Simple PHP Form Validation</title>

</head>

<body>

<h2>PHP Form Validation Example</h2>

<form method="post" action="index.php">

Username: <input type="text" name="username">

<span style="color: red;"><?php echo $usernameErr ?? ''; ?></span><br><br>

Email: <input type="text" name="email">

<span style="color: red;"><?php echo $emailErr ?? ''; ?></span><br><br>


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

</form>

</body>

</html>

PHP Validation Logic (index.php)

php

Copy code

<?php

$usernameErr = $emailErr = "";

$username = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Check if username is empty

if (empty($_POST["username"])) {

$usernameErr = "Username is required";

} else {

$username = test_input($_POST["username"]);

// Check if email is valid

if (empty($_POST["email"])) {

$emailErr = "Email is required";

} elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {

$emailErr = "Invalid email format";

} else {

$email = test_input($_POST["email"]);

}
// Sanitize input

function test_input($data) {

return html specialchars(stripslashes(trim($data)));

?>

Explanation

1. HTML Form: We create a simple form with fields for the username and email, plus span tags for
error messages.

2. Validation: When the form is submitted (POST request), PHP checks:

o If the username field is empty.

o If the email field is empty or if the email format is invalid.

3. Sanitization: test_input() function sanitizes the input by trimming whitespace, removing


backslashes, and converting HTML characters to prevent injection attacks.

You might also like