php notes
php notes
2. Introduction to PHP
What is PHP?
o PHP: A server-side scripting language designed primarily for web development
but also used as a general-purpose programming language.
o Originally created by Rasmus Lerdorf in 1993 and evolved over time into a
powerful language.
History of PHP:
o PHP/FI (Personal Home Page/Forms Interpreter): The original version created in
1995.
o PHP 3: Released in 1997, marked a significant upgrade and adoption in web
development.
o PHP 4: Introduced in 2000, included improved performance and support for web
applications.
o PHP 5: Released in 2004, added object-oriented programming features and
improved MySQL integration.
o PHP 7: Launched in 2015, significantly improved performance and introduced
new features like scalar type declarations and return type declarations.
o PHP 8: The latest major release, which includes Just-In-Time compilation, union
types, attributes, and improvements in error handling.
Advantages of PHP:
o Open Source: Free to use and widely supported by a large community of
developers.
o Cross-Platform: Runs on various operating systems (Windows, Linux, macOS).
o Database Support: Seamless integration with popular databases like MySQL,
PostgreSQL, and SQLite.
o Ease of Learning: Simple syntax and extensive documentation make it accessible
to beginners.
o Robust Community: A large community contributes to a wealth of libraries,
frameworks (e.g., Laravel, Symfony), and resources.
Disadvantages of PHP:
o Security Issues: Historically criticized for security vulnerabilities; requires
developers to follow best practices.
o Inconsistent Function Naming: Some function names can be non-intuitive or
inconsistent, leading to confusion.
o Performance: While improvements have been made, PHP may not be as
performant as some compiled languages for certain tasks.
PHP vs. Other Server-Side Technologies:
o Ease of Use: PHP is often easier to set up and get started with compared to
frameworks like ASP.NET or Java.
o Community Support: PHP has extensive community support and resources,
making it easier to find solutions to problems.
o Performance: PHP may lag behind more modern languages/frameworks in
performance, but its speed and efficiency are sufficient for most web applications.
o Flexibility: PHP allows both procedural and object-oriented programming styles,
making it versatile for developers.
1. PHP Syntax
Basic Syntax:
o PHP code is embedded in HTML using the PHP tags <?php and ?>. Anything
outside of these tags is treated as HTML.
o Example:
<?php
echo "Hello, World!";
?>
Comments: Comments in PHP are used for documentation and to make the code more
readable. PHP supports both single-line and multi-line comments:
o Single-line comments:
o Multi-line comments:
/* This is a
multi-line comment */
Variables:
o Variables in PHP start with the $ symbol followed by the variable name. They are
case-sensitive.
o Variable names must start with a letter or an underscore, followed by any
combination of letters, numbers, or underscores.
o Example:
$name = "John";
$age = 30;
Output:
o PHP provides two primary ways to output data: echo and print.
o Echo: A language construct used to output one or more strings.
2. Data Types
Overview: PHP is a loosely typed language, meaning you do not need to declare a
variable's data type.
Types of Data:
o String: A sequence of characters enclosed in quotes.
$age = 25;
$price = 19.99;
$is_active = true;
$value = NULL;
String Manipulation:
o Concatenation: Joining two strings using the . operator.
$first_name = "John";
$last_name = "Doe";
$full_name = $first_name . " " . $last_name; // John Doe
4. Constants
Definition: Constants are similar to variables, but their values cannot be changed once
defined.
Defining Constants: Use the define() function to create a constant.
define("SITE_NAME", "MyWebsite");
5. Operators
Types of Operators:
o Arithmetic Operators: Used for performing basic mathematical operations.
+ (addition), - (subtraction), * (multiplication), / (division), % (modulus).
o Assignment Operators: Used to assign values to variables.
= (assignment), +=, -=, *=, /=, %= for compound assignment.
o Comparison Operators: Used to compare values.
== (equal), === (identical), != (not equal), !== (not identical), <, >, <=, >=.
o Logical Operators: Used to combine conditional statements.
&& (and), || (or), ! (not).
6. Control Structures
Conditional Statements:
o If-Else Statement:
Loops:
o While Loop: Executes as long as a condition is true.
o Do-While Loop: Executes at least once and then repeats while a condition is true.
do {
echo $count;
$count++;
} while ($count < 5);
7. Functions
Definition: A function is a block of code that can be reused and executed when called.
Creating a Function:
function greet($name) {
return "Hello, " . $name;
}
echo greet("John"); // Outputs: Hello, John
1. PHP Arrays
Introduction to Arrays:
o Definition: An array is a special variable in PHP that can hold multiple values in
a single variable. Arrays are useful for storing a collection of data, such as lists of
items, settings, or records.
o Types of Arrays: PHP supports three main types of arrays:
Indexed Arrays: Arrays with numeric indices, where each element is
accessed using its index number.
Associative Arrays: Arrays where each element is identified by a unique
key (string), allowing for easier access to elements based on names rather
than numbers.
Multidimensional Arrays: Arrays that contain one or more arrays within
them. This structure is useful for representing more complex data, such as
tables.
Types of Arrays:
o Indexed Arrays:
Defined using numeric indices. Example:
Accessing elements:
o Associative Arrays:
Defined using key-value pairs. Example:
$ages = array("Alice" => 25, "Bob" => 30, "Charlie" => 35);
// or using short array syntax
$ages = ["Alice" => 25, "Bob" => 30, "Charlie" => 35];
Accessing elements:
o Multidimensional Arrays:
Arrays containing other arrays. Example:
$students = array(
array("John", 20, "Computer Science"),
array("Jane", 22, "Mathematics"),
array("Mike", 21, "Physics")
);
Accessing elements:
Sorting Arrays:
o PHP provides several functions to sort arrays:
sort(): Sorts indexed arrays in ascending order.
2. PHP Superglobals
Introduction to Superglobals:
o Superglobals are built-in variables in PHP that are always accessible, regardless
of scope. They are used to access information about variables, forms, session data,
server environment, and more. This makes them useful for various programming
scenarios.
Common Superglobals:
o $GLOBALS:
An associative array containing all global variables. Useful for accessing
global variables from any function or method.
$x = 10;
function test() {
echo $GLOBALS['x']; // Output: 10
}
test();
o $_SERVER:
An associative array containing information about headers, paths, and
script locations. Useful for obtaining server-related data.
echo $_SERVER['HTTP_USER_AGENT']; // Outputs the user's
browser information
o $_REQUEST:
An associative array containing data from both $_GET and $_POST
requests, as well as $_COOKIE data. Used to collect data submitted via
forms.
o $_GET:
An associative array used to collect data sent in the URL query string. It is
typically used for form submissions with method="get".
// URL: example.com/page.php?name=John&age=25
$name = $_GET['name']; // Output: John
o $_POST:
An associative array used to collect data sent through HTTP POST
method. It is used for forms that require data submission without exposing
it in the URL.
// In a form submission
$name = $_POST['name']; // Output: Data submitted via POST
o $_FILES:
An associative array used to handle file uploads. Contains information
about files uploaded via forms.
o $_SESSION:
An associative array used to store session variables. Data stored in this
array is available across multiple pages during the user's session.
o $_COOKIE:
An associative array used to access cookie values. Cookies are small
pieces of data stored on the client-side.
Introduction:
o Regular expressions (regex) are sequences of characters that form search patterns.
They are used for string matching and manipulation.
Common Functions:
o preg_match(): Checks if a pattern matches a string.
$pattern = "/abc/";
$string = "abcdef";
if (preg_match($pattern, $string)) {
echo "Match found!";
}
$string = "one,two,three";
$array = preg_split("/,/", $string);
// $array contains ["one", "two", "three"]
html
<form action="process.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit">
</form>
o The action attribute specifies the PHP file that will process the data, while the
method attribute defines how data is sent (GET or POST).
Handling Form Data in PHP:
o PHP retrieves form data using the $_GET or $_POST superglobals, depending on
the method used.
o Example of processing form data in process.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
}
?>
html
<form action="register.php" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<label for="confirm_password">Confirm Password:</label>
<input type="password" id="confirm_password"
name="confirm_password" required>
<input type="submit" value="Register">
</form>
html
<form action="feedback.php" method="POST">
<label for="feedback">Feedback:</label>
<textarea id="feedback" name="feedback" rows="4"
required></textarea>
<input type="submit" value="Submit Feedback">
</form>
Appending to a File:
Deleting a File:
Image Upload:
o PHP can handle file uploads, including images, through forms. Here’s a simple
upload form:
html
<form action="upload.php" method="POST" enctype="multipart/form-
data">
<label for="file">Choose an image to upload:</label>
<input type="file" name="file" id="file" accept="image/*"
required>
<input type="submit" value="Upload Image">
</form>
Session Management:
o Sessions in PHP allow you to store user data across multiple pages. This is crucial
for features like user login and shopping carts.
o Starting a Session:
o Ending a Session:
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
Cookies:
o Cookies are small files stored on the client’s computer and are used to remember
information about the user.
o Setting a Cookie:
o Accessing Cookies:
if(isset($_COOKIE['user'])) {
echo "Welcome back, " . $_COOKIE['user'];
}
o Deleting a Cookie:
Exception Handling:
o PHP supports exception handling, allowing developers to manage errors
gracefully.
o Try-Catch Blocks:
try {
// Code that may throw an exception
throw new Exception("An error occurred.");
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
}
Introduction to OOP:
o Object-Oriented Programming (OOP) is a programming paradigm that uses
"objects" to design software. OOP allows for code reusability, modularity, and
better organization of code.
o Key concepts include classes, objects, inheritance, encapsulation, and
polymorphism.
Classes and Objects:
o Class: A blueprint for creating objects. It defines properties (attributes) and
methods (functions) that the created objects can use.
o Object: An instance of a class. It represents a specific implementation of the
class.
o Syntax Example:
class Car {
public $color;
public $model;
class Example {
public function __construct() {
echo "Object created!";
}
Namespaces:
o Namespaces are a way to group related classes, functions, and constants to avoid
naming conflicts. They allow better organization and can be autoloaded.
o Syntax Example:
namespace Animals;
class Cat {
public function meow() {
return "Meow!";
}
}
Iterables:
o In PHP, an iterable is any variable that can be looped over with foreach. This
includes arrays and objects that implement the Traversable interface.
Introduction to MySQL:
o MySQL is an open-source relational database management system. It uses
Structured Query Language (SQL) for database interactions and is commonly
used with PHP to manage data.
Connecting to a Database:
o Use the mysqli or PDO (PHP Data Objects) extensions to connect to a MySQL
database.
o Syntax Example (Using mysqli):
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create
$sql = "INSERT INTO users (name, email) VALUES ('John Doe',
'john@example.com')";
mysqli_query($conn, $sql);
// Read
$result = mysqli_query($conn, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
echo $row['name'];
}
// Update
$sql = "UPDATE users SET email='john.doe@example.com' WHERE
name='John Doe'";
mysqli_query($conn, $sql);
// Delete
$sql = "DELETE FROM users WHERE name='John Doe'";
mysqli_query($conn, $sql);
Prepared Statements:
o Prepared statements are a way to execute SQL queries safely, helping to prevent
SQL injection attacks.
o Syntax Example:
Introduction to APIs:
o APIs allow different software applications to communicate with each other. They
define a set of rules for how requests and responses are structured.
Creating an API with PHP:
o You can create RESTful APIs in PHP that can respond to HTTP requests (GET,
POST, PUT, DELETE) and return data in formats like JSON or XML.
o Syntax Example:
header('Content-Type: application/json');
$response = array("message" => "Hello, World!");
echo json_encode($response);
Using APIs:
o To use external APIs, you can use PHP’s curl functions to send requests and
handle responses.
o Syntax Example:
$url = "https://api.example.com/data";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
4. PHP Frameworks
Introduction to PHPUnit:
o PHPUnit is a popular testing framework for PHP that allows developers to write
unit tests for their code, ensuring functionality and reliability.
Writing Tests:
o Tests are typically written in separate files and organized in a way that
corresponds to the application structure.
o Syntax Example:
use PHPUnit\Framework\TestCase;
Running Tests:
o PHPUnit can be executed from the command line to run all tests in a specified
directory.
o Use the command:
Bash----------------
phpunit tests/