What are Variables in PHP?
Variables in PHP are used to store data, which can be of various types
(numbers, strings, arrays, etc.). They act as containers that hold values you
want to use and manipulate within your code. Each variable in PHP starts
with a $ symbol, followed by a name that can contain letters, numbers, and
underscores. PHP is a loosely typed language, meaning you don’t need to
declare the data type of a variable explicitly—PHP will automatically
determine it based on the value you assign.
Rules for Naming Variables
Variable names must start with a letter or an underscore ( _) but
cannot start with a number.
Variable names are case-sensitive, meaning $name and $Name are
considered different variables.
Avoid using spaces or special characters in variable names.
Examples of Declaring Variables
php
<?php
$name = "John"; // A string
$age = 25; // An integer
$isStudent = true; // A boolean
$salary = 35000.75; // A float
?>
In the above example:
$name stores a string, "John".
$age stores an integer, 25.
$isStudent stores a boolean value, true.
$salary stores a floating-point number, 35000.75.
Basic Operators in PHP
Operators allow you to perform operations on variables and values. Here’s
an overview of essential PHP operators:
Arithmetic Operators: Used for basic math operations.
php
<?php
$sum = 10 + 5; // Addition
$difference = 10 - 5; // Subtraction
$product = 10 * 5; // Multiplication
$quotient = 10 / 5; // Division
$remainder = 10 % 3; // Modulus
?>
Assignment Operators: Assign values to variables.
php
<?php
$x = 5; // Simple assignment
$x += 3; // Equivalent to $x = $x + 3
$x -= 2; // Equivalent to $x = $x - 2
?>
Comparison Operators: Compare two values and
return true or false.
php
<?php
$isEqual = (10 == 10); // true
$isNotEqual = (10 != 5); // true
$isGreater = (10 > 5); // true
$isLess = (10 < 15); // true
?>
Logical Operators: Used for combining multiple conditions,
particularly in control structures.
php
<?php
$a = true;
$b = false;
$andResult = $a && $b; // AND operator (returns false)
$orResult = $a || $b; // OR operator (returns true)
?>
Using these operators with variables allows for various operations in PHP,
from simple calculations to complex conditions and expressions.
Practical Example Using Variables, Data Types, and Constants
Here’s a practical example demonstrating how to combine variables, data
types, and constants to create a basic calculator.
php
<?php
define("SALES_TAX", 0.05); // Constant for sales tax
$itemName = "Wireless Mouse"; // String
$itemPrice = 25.00; // Float
$quantity = 2; // Integer
$subtotal = $itemPrice * $quantity; // Calculate subtotal
$totalTax = $subtotal * SALES_TAX; // Calculate tax
$totalPrice = $subtotal + $totalTax; // Total price
echo "Item: $itemName <br>";
echo "Price per item: $$itemPrice <br>";
echo "Quantity: $quantity <br>";
echo "Subtotal: $$subtotal <br>";
echo "Sales Tax: $$totalTax <br>";
echo "Total Price: $$totalPrice";
?>
In this example:
The code calculates the total cost of purchasing items, including
sales tax.
The constant SALES_TAX is used to ensure consistency in tax
calculations.
Variables store item details, and basic operators calculate totals.
Taking User Input (Using HTML + PHP)
You can take input using an HTML form and process it using PHP.
HTML + PHP Example (user inputs two numbers and gets their sum):
<!-- save this as index.php and run on localhost or server -->
<!DOCTYPE html>
<html>
<head>
<title>Simple PHP Calculator</title>
</head>
<body>
<h2>PHP Calculator</h2>
<form method="post">
Enter first number: <input type="number" name="num1" required><br><br>
Enter second number: <input type="number" name="num2" required><br><br>
<input type="submit" name="submit" value="Calculate Sum">
</form>
<?php
if (isset($_POST['submit'])) {
// Taking input
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
// Processing
$sum = $num1 + $num2;
// Output
echo "<h3>Result: $num1 + $num2 = $sum</h3>";
}
?>
</body>
</html>
📤 4. Output in PHP
Use echo or print to display output.
<?php
$name = "Alice";
echo "Welcome, $name!";
?>
PHP Arrays
What are Arrays in PHP?
An array in PHP is a special variable that can hold multiple values at once.
Instead of storing individual values in separate variables, you can use an
array to store a collection of data. Arrays are particularly useful for grouping
related items, such as a list of names, product prices, or other data sets,
and making them easier to manage.
Types of Arrays in PHP
PHP supports three main types of arrays:
Indexed Arrays: Arrays with numeric indexes, where each element
is automatically assigned an index starting from 0.
Associative Arrays: Arrays with named keys, where each element is
associated with a key-value pair.
Multidimensional Arrays: Arrays containing one or more arrays as
elements, allowing you to store complex data structures.
Indexed Arrays
An indexed array uses numeric indexes to access elements. PHP assigns
each element a numeric index automatically, starting from 0 for the first
element, 1 for the second, and so on.
Creating an Indexed Array
php
<?php
// Using the array() function
$fruits = array("Apple", "Banana", "Cherry");
// Using the shorthand syntax (PHP 5.4+)
$colors = ["Red", "Green", "Blue"];
?>
In this example:
$fruits is an indexed array created using the array() function.
$colors is another indexed array, created with shorthand syntax.
Accessing Array Elements
To access elements in an indexed array, use the index number within
square brackets [].
php
<?php
echo $fruits[0]; // Outputs: Apple
echo $colors[2]; // Outputs: Blue
?>
Associative Arrays
An associative array uses named keys instead of numeric indexes,
allowing you to access elements based on a descriptive key.
Creating an Associative Array
php
<?php
$person = array(
"name" => "Alice",
"age" => 25,
"city" => "New York"
);
// Using shorthand syntax
$car = [
"make" => "Toyota",
"model" => "Corolla",
"year" => 2020
];
?>
In this example:
$person and $car are associative arrays with descriptive keys such
as "name" and "make".
Accessing Elements in an Associative Array
Use the key name within square brackets to access elements in an
associative array.
php
<?php
echo $person["name"]; // Outputs: Alice
echo $car["model"]; // Outputs: Corolla
?>
Multidimensional Arrays
A multidimensional array is an array that contains one or more arrays as
its elements, creating a more complex data structure. Multidimensional
arrays are often used for representing tables or grids of data.
Creating a Multidimensional Array
php
<?php
$students = array(
array("Alice", "Biology", 85),
array("Bob", "Mathematics", 90),
array("Charlie", "Physics", 78)
);
?>
In this example:
$students is a multidimensional array where each element is an
array containing a student’s name, subject, and score.
Accessing Elements in a Multidimensional Array
To access elements in a multidimensional array, specify each index in
sequence.
php
<?php
echo $students[1][0]; // Outputs: Bob
echo $students[2][1]; // Outputs: Physics
?>
Common Array Functions in PHP
PHP provides a wide range of functions for manipulating arrays. Here are
some of the most commonly used ones:
count(): Returns the number of elements in an array.
php
<?php
echo count($fruits); // Outputs: 3
?>
array_push(): Adds one or more elements to the end of an array.
php
<?php
array_push($fruits, "Orange");
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] =>
Orange )
?>
array_pop(): Removes the last element from an array.
php
<?php
array_pop($colors);
print_r($colors); // Outputs: Array ( [0] => Red [1] => Green )
?>
array_merge(): Merges two or more arrays into a single array.
php
<?php
$array1 = ["A", "B"];
$array2 = ["C", "D"];
$mergedArray = array_merge($array1, $array2);
print_r($mergedArray); // Outputs: Array ( [0] => A [1] => B [2] => C [3] => D )
?>
in_array(): Checks if a value exists in an array.
php
<?php
if (in_array("Banana", $fruits)) {
echo "Banana is in the list.";
}
?>
array_keys(): Returns all the keys of an associative array.
php
<?php
print_r(array_keys($person)); // Outputs: Array ( [0] => name [1] => age [2] => city
)
?>
array_values(): Returns all the values of an associative array.
php
<?php
print_r(array_values($person)); // Outputs: Array ( [0] => Alice [1] => 25 [2] =>
New York )
?>
Practical Example: Using Arrays to Store Product Data
Let’s create a small script to manage a list of products with their prices,
quantities, and calculate the total cost.
php
<?php
$products = [
["name" => "Laptop", "price" => 999.99, "quantity" => 2],
["name" => "Mouse", "price" => 25.50, "quantity" => 5],
["name" => "Keyboard", "price" => 45.00, "quantity" => 3]
];
$totalCost = 0;
echo "Product List: <br>";
foreach ($products as $product) {
$cost = $product["price"] * $product["quantity"];
echo $product["name"] . " - Price: $" . $product["price"] . ", Quantity: " .
$product["quantity"] . ", Cost: $" . $cost . "<br>";
$totalCost += $cost;
}
echo "Total Cost: $" . $totalCost;
?>
In this example:
$products is a multidimensional array, where each element is an
associative array representing a product’s name, price, and quantity.
The foreach loop iterates through each product, calculates the total
cost for each product, and adds it to $totalCost.
The final output displays each product's details and the total cost of
all products.
Best Practices for Using Arrays in PHP
Use Descriptive Keys in Associative Arrays: Descriptive keys
make arrays easier to understand and maintain.
Use Functions to Simplify Array Manipulation: PHP’s built-in array
functions help streamline array operations, making code more
efficient.
Avoid Hard-Coding Indexes: For multidimensional arrays, consider
using descriptive indexes in associative arrays to improve readability.
Check Array Existence: Always verify that an array key exists
(using isset() or array_key_exists()) before accessing it,
especially when working with user-provided data.
Sessions and Cookies in PHP
What are Sessions and Cookies?
Sessions and cookies are two methods used to store data about a user as
they navigate through a website. They allow you to maintain information
across different pages, enhancing user interaction.
Sessions: Store data on the server and are used to track information
about a user during a single visit (or session) to the site. Sessions
are ideal for storing sensitive data, such as login information,
because the data is stored securely on the server.
Cookies: Store data on the user's browser and persist across
sessions (even after the browser is closed, depending on the
expiration time). Cookies are useful for remembering user
preferences or login credentials between visits.
Using Sessions in PHP
Sessions are server-side, meaning the data is stored on the server. Each
user has a unique session ID stored in a cookie on their browser, which
PHP uses to associate them with their session data on the server.
Starting a Session
To use sessions in PHP, you must start a session at the beginning of your
script using session_start(). It’s typically placed at the top of the script
before any HTML output.
php
<?php
// Start the session
session_start();
?>
Setting and Retrieving Session Variables
Session variables are set using the $_SESSION superglobal array. These
variables remain accessible across all pages of the website as long as the
session is active.
Example: Setting and Retrieving Session Variables
php
<?php
session_start();
// Setting session variables
$_SESSION["username"] = "JohnDoe";
$_SESSION["role"] = "Admin";
echo "Session variables are set.<br>";
?>
To retrieve session variables, you access them using the $_SESSION array:
php
<?php
session_start();
echo "Username: " . $_SESSION["username"] . "<br>";
echo "Role: " . $_SESSION["role"];
?>
In this example:
$_SESSION["username"] and $_SESSION["role"] store the
username and role information, which can be retrieved on any page
after starting the session.
Checking if a Session Variable is Set
It’s often necessary to check if a session variable is set, especially for
pages that require user authentication.
php
<?php
session_start();
if (isset($_SESSION["username"])) {
echo "Welcome, " . $_SESSION["username"];
} else {
echo "You are not logged in.";
}
?>
Destroying a Session
To log a user out or clear session data, use session_unset() to remove
session variables and session_destroy() to end the session.
php
<?php
session_start();
// Remove all session variables
session_unset();
// Destroy the session
session_destroy();
echo "Session destroyed. You are logged out.";
?>
Using Cookies in PHP
Cookies store data on the client side, specifically in the user's browser.
They’re commonly used for features like “Remember Me” functionality,
where user credentials or preferences are saved between visits.
Setting Cookies
To set a cookie in PHP, use the setcookie() function, which requires the
name, value, and expiration time of the cookie. By default, cookies are only
available during the browser session unless an expiration time is set.
Syntax of setcookie()
php
setcookie(name, value, expire, path, domain, secure, httponly);
name: The name of the cookie.
value: The value of the cookie.
expire: The expiration time (in seconds since the Unix Epoch).
Use time() + seconds for future expiration.
path: The path where the cookie is available (default is the current
directory).
domain: The domain that the cookie is available to.
secure: If TRUE, the cookie is only set over HTTPS connections.
httponly: If TRUE, the cookie is only accessible through HTTP (not
JavaScript), enhancing security.
Example: Setting a Cookie
php
<?php
$cookie_name = "user";
$cookie_value = "JohnDoe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // Expires in 30
days
echo "Cookie has been set.";
?>
In this example:
The cookie user is set with the value "JohnDoe".
The cookie expires in 30 days (86400 seconds per day multiplied by
30).
Retrieving Cookies
Cookies can be accessed using the $_COOKIE superglobal array.
php
<?php
if (isset($_COOKIE["user"])) {
echo "User: " . $_COOKIE["user"];
} else {
echo "User cookie is not set.";
}
?>
In this example:
$_COOKIE["user"] retrieves the value of the user cookie if it’s set.
Deleting Cookies
To delete a cookie, set its expiration date to a time in the past.
php
<?php
setcookie("user", "", time() - 3600, "/"); // Expire 1 hour ago
echo "Cookie 'user' has been deleted.";
?>
In this example:
The user cookie is set to expire one hour in the past, effectively
deleting it.
Practical Example: Using Sessions and Cookies for Login
Management
Let’s create a simple login system using sessions and cookies.
HTML Login Form
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="login_process.php" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="checkbox" id="remember" name="remember">
<label for="remember">Remember Me</label><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
PHP Script for Login Processing (login_process.php)
php
<?php
session_start();
// Hardcoded credentials for demonstration
$correct_username = "JohnDoe";
$correct_password = "password123";
$username = $_POST["username"];
$password = $_POST["password"];
if ($username === $correct_username && $password === $correct_password) {
$_SESSION["username"] = $username;
// If "Remember Me" is checked, set a cookie
if (isset($_POST["remember"])) {
setcookie("username", $username, time() + (86400 * 30), "/"); // Expires
in 30 days
}
echo "Login successful! Welcome, " . $_SESSION["username"];
} else {
echo "Invalid credentials. Please try again.";
}
?>
In this example:
The login credentials are hardcoded (in practice, they would come
from a database).
If the credentials match, a session is started, and a username session
variable is set.
If the "Remember Me" checkbox is selected, a cookie is set to
remember the user’s username for 30 days.
Logout Script (logout.php)
php
<?php
session_start();
// Unset session variables and destroy session
session_unset();
session_destroy();
// Delete the "username" cookie if it exists
if (isset($_COOKIE["username"])) {
setcookie("username", "", time() - 3600, "/");
}
echo "You have been logged out.";
?>
In this example:
session_unset() and session_destroy() end the session, logging
out the user.
The username cookie is deleted by setting its expiration time in the
past.
Best Practices for Using Sessions and Cookies
Secure Sensitive Data: Store sensitive data (like login information)
in sessions rather than cookies.
Use HTTPS for Cookies: When handling secure information, set
cookies to be transmitted only over HTTPS.
Set Expiration Times: Always define expiration times for cookies to
avoid lingering data on user devices.
Implement Session Expiration: Regularly expire sessions (e.g.,
after 30 minutes of inactivity) to enhance security.