1. Introduction to PHP
PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed for web development. It is embedded within HTML and is particularly suited for creating dynamic and interactive web pages. PHP is known for its ease of use, flexibility, and ability to integrate with various databases like MySQL, PostgreSQL, and SQLite.
PHP scripts are executed on the server, and the output is sent to the client's browser as plain HTML. This makes PHP an essential tool for developing web applications, content management systems, e-commerce platforms, and more.
2. PHP Syntax and Basics
PHP scripts are enclosed within special tags <?php ... ?>
, which allow the PHP code to be mixed with HTML.
2.1 Example: Basic PHP Script
<?php
echo "Hello, World!";
?>
In this example, the PHP script outputs "Hello, World!" to the browser. The echo
statement is used to display text in PHP.
2.2 Variables and Data Types
PHP variables start with a dollar sign ($
) and can store various data types such as strings, integers, floats, arrays, and objects.
2.2.1 Example: Using Variables
<?php
$greeting = "Hello, World!";
$age = 25;
$is_student = true;
echo $greeting; // Outputs: Hello, World!
?>
In this example, the $greeting
variable stores a string, $age
stores an integer, and $is_student
stores a boolean value.
3. Control Structures
PHP supports various control structures, such as conditionals and loops, which allow developers to control the flow of the program based on specific conditions.
3.1 Conditional Statements
PHP provides if
, else
, elseif
, and switch
statements to perform different actions based on different conditions.
3.1.1 Example: Using If-Else
<?php
$number = 10;
if ($number > 0) {
echo "The number is positive.";
} elseif ($number < 0) {
echo "The number is negative.";
} else {
echo "The number is zero.";
}
?>
In this example, the script checks whether a number is positive, negative, or zero and outputs the appropriate message.
3.2 Loops
PHP supports loops like for
, while
, do-while
, and foreach
for iterating over a block of code multiple times.
3.2.1 Example: For Loop
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i <br>";
}
?>
This example uses a for
loop to print numbers from 1 to 5.
4. Functions in PHP
Functions in PHP are blocks of code that perform specific tasks and can be reused throughout a script. PHP has a large number of built-in functions, but you can also define your own custom functions.
4.1 Defining and Using Functions
To define a function, use the function
keyword followed by the function name, parentheses, and a block of code.
4.1.1 Example: Custom Function
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice"); // Outputs: Hello, Alice!
?>
In this example, the greet
function takes a name as an argument and returns a greeting message.
4.2 Built-In Functions
PHP includes many built-in functions for tasks such as string manipulation, array handling, and file operations.
4.2.1 Example: Using Built-In Functions
<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = array_sum($numbers);
echo "Sum: $sum"; // Outputs: Sum: 15
?>
Here, the array_sum
function calculates the sum of all elements in the $numbers
array.
5. Working with Forms in PHP
PHP is often used to process form data submitted via HTML forms. The data can be sent to a PHP script using the GET
or POST
method.
5.1 Handling Form Data
When a form is submitted, PHP automatically creates arrays $_GET
and $_POST
to store the form data depending on the submission method.
5.1.1 Example: Processing a Form
<!-- HTML Form -->
<form method="POST" action="process.php">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
<!-- PHP Script (process.php) -->
<?php
$name = $_POST['name'];
$age = $_POST['age'];
echo "Name: $name <br>";
echo "Age: $age";
?>
In this example, a simple form collects a user's name and age. When the form is submitted, the data is sent to the process.php
script, where it is processed and displayed.
6. PHP and Databases
PHP is commonly used with databases to create dynamic web applications. MySQL is one of the most popular databases used with PHP, but PHP can connect to various other databases as well.
6.1 Connecting to a Database
PHP provides several ways to connect to a MySQL database, including the mysqli
extension and the more modern PDO (PHP Data Objects)
extension.
6.1.1 Example: Connecting to MySQL with MySQLi
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test_db";
// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
This example demonstrates how to establish a connection to a MySQL database using the MySQLi extension.
6.2 Querying a Database
Once connected, you can run SQL queries to interact with the database, such as selecting, inserting, updating, or deleting records.
6.2.1 Example: Running a SQL Query
<?php
$sql = "SELECT id, name, age FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This example retrieves data from a users
table and displays the results. The connection is closed after the query is executed.
7. Error Handling in PHP
PHP provides several ways to handle errors, allowing you to manage what happens when something goes wrong in your script. Proper error handling ensures that your application can gracefully recover from errors or provide meaningful messages to the user.
7.1 Error Handling Functions
PHP provides built-in functions like error_reporting()
, set_error_handler()
, and try-catch
blocks to handle errors.
7.1.1 Example: Basic Error Handling
<?php
function customError($errno, $errstr) {
echo "Error: [$errno] $errstr <br>";
}
// Set custom error handler
set_error_handler("customError");
// Trigger an error
echo($test);
?>
This example sets a custom error handler function customError()
and triggers an error by trying to echo an undefined variable $test
.
7.2 Exception Handling
PHP also supports exception handling using try-catch
blocks, allowing you to catch and handle exceptions gracefully.
7.2.1 Example: Using Try-Catch for Exception Handling
<?php
try {
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
throw new Exception("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
This example uses a try-catch
block to catch any exceptions that occur when trying to connect to the database and handle them appropriately.
8. PHP Security Best Practices
Securing your PHP applications is crucial to protect them from common web vulnerabilities such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF). Following best practices can help mitigate these risks.
8.1 Input Validation and Sanitization
Always validate and sanitize user input to prevent malicious data from being processed by your application.
8.1.1 Example: Sanitizing User Input
<?php
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$age = filter_input(INPUT_POST, 'age', FILTER_SANITIZE_NUMBER_INT);
echo "Name: $name <br>";
echo "Age: $age";
?>
In this example, user input is sanitized before being used, reducing the risk of malicious data causing harm.
8.2 Using Prepared Statements
Use prepared statements for database queries to prevent SQL injection attacks.
8.2.1 Example: Prepared Statement in MySQLi
<?php
$stmt = $conn->prepare("INSERT INTO users (name, age) VALUES (?, ?)");
$stmt->bind_param("si", $name, $age);
$name = "John";
$age = 30;
$stmt->execute();
echo "New record created successfully";
$stmt->close();
$conn->close();
?>
This example demonstrates the use of a prepared statement in MySQLi, which binds parameters and executes a secure SQL query.