PHP Programming
PHP Programming
Websites today are typically divided into two major categories based on how they
interact with users:
• Static Websites:
o These are the simplest form of websites where every user is shown the
same content. The content is fixed and does not change unless
manually edited by the website administrator.
o Static websites typically consist of HTML for structure, CSS for
styling, and sometimes JavaScript for small dynamic elements (e.g.,
sliders or form validation).
o Example: A personal portfolio website with your bio, project images,
and contact information displayed as static HTML content.
• Dynamic Websites:
o These websites offer interaction and generate different content
depending on user actions or preferences. For instance, e-commerce
websites will show different products based on user location, search
history, or preferences.
o The key feature of dynamic websites is the use of server-side
scripting languages (like PHP) to generate content on-the-fly. This is
typically combined with databases (like MySQL) to store and
retrieve content.
o Example: An online store showing products that can be sorted, added
to a cart, and purchased by a user. Content, such as product listings, is
often fetched from a database.
PHP is one of the most widely-used server-side scripting languages. It runs on the
server and generates HTML dynamically, which is then sent to the user's browser.
Below are a few more important aspects of PHP:
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Output data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
In this example:
The scope of PHP is vast and covers almost every aspect of web development.
Some of the primary areas where PHP is widely used include:
Web Applications:
REST APIs:
• PHP can be used to build RESTful APIs, which allow different applications
to communicate over HTTP. This is useful for applications that need to
exchange data with other platforms (e.g., mobile apps, third-party services).
Command-Line Scripts:
• Although it's most commonly used in web development, PHP can also be
used for command-line scripting. This is useful for tasks like sending
automated emails, processing data, or cleaning up databases.
1. User Interaction: A user visits a website and requests a specific page (e.g.,
a product listing).
2. Server-Side Processing: The web server processes the request, often
running PHP scripts to handle the logic. For example, PHP can query a
MySQL database to retrieve product information.
3. Database Interaction: PHP might execute a SQL query like SELECT * FROM
products WHERE category='electronics' to retrieve products from the
database.
4. HTML Generation: PHP then generates HTML code based on the retrieved
data. This HTML is returned to the user's browser.
5. Client-Side Rendering: Once the browser receives the HTML, it renders
the page for the user to view.
These software packages provide all the necessary components to set up a local
server environment:
With XAMPP or WAMP, developers can build, test, and debug PHP applications
without needing a live server, making it easier to develop websites and applications
in a local, safe environment.
PHP Syntax
• PHP code is written between <?php and ?> tags. These tags tell the web
server to execute the enclosed code.
Example:
<?php
echo "Hello, World!";
?>
You can easily embed PHP code inside an HTML document. The PHP code is
executed on the server and generates HTML that is sent to the browser.
Example:
<!DOCTYPE html>
<html>
<head>
<title>PHP in HTML</title>
</head>
<body>
<h1><?php echo "Welcome to my website!"; ?></h1>
<p>This paragraph is part of the HTML content.</p>
</body>
</html>
In this example, PHP is used to generate the content inside the <h1> tag, but the
rest of the page is static HTML.
Embedding HTML in PHP
You can also include HTML in PHP code. This is useful for generating dynamic
content, where you may have HTML structure but also need PHP to insert dynamic
data.
Example:
<?php
$name = "John";
echo "<h1>Hello, $name!</h1>";
echo "<p>This is a paragraph of text.</p>";
?>
Here, PHP inserts a dynamic value into the HTML content, making the webpage
dynamic.
In PHP, variables are used to store data, such as numbers, strings, or arrays. PHP
variables always start with the dollar sign ($) symbol followed by the variable
name.
Defining Variables:
• Variables in PHP are loosely typed, meaning you do not have to specify a
data type when you declare them. PHP will automatically infer the type
based on the assigned value.
Example:
$age = 25; // Integer variable
$name = "Alice"; // String variable
$isActive = true; // Boolean variable
Variable Types:
PHP supports several types of variables, including:
PHP has several built-in data types that you can use in your code. These types
help define the kind of data stored in variables.
Example:
$emptyVar = NULL;
4. Using Operators in PHP
PHP provides a wide range of operators that allow you to manipulate data and
variables. Operators are used to perform operations on variables and values.
Types of Operators:
Example:
$x = 10;
$y = 5;
$sum = $x + $y; // $sum = 15
Example:
if ($x == $y) {
echo "x is equal to y";
}
Example:
if ($x > 5 && $y < 10) {
echo "Both conditions are true";
}
Example:
$x = 10;
$x += 5; // $x becomes 15
5. String Operators: Used to concatenate strings.
o . (dot) is used to concatenate strings.
Example:
$greeting = "Hello";
$name = "World";
echo $greeting . " " . $name; // Outputs "Hello World"
If Statement
The if() statement allows you to test a condition and execute a block of code if
the condition is true.
Example:
if ($x > 5) {
echo "x is greater than 5";
}
Else If Statement
The else if() statement allows you to check additional conditions if the previous
if() or else if() conditions were not true.
Example:
if ($x > 10) {
echo "x is greater than 10";
} else if ($x > 5) {
echo "x is greater than 5 but less than or equal to 10";
} else {
echo "x is 5 or less";
}
Else Statement
The else statement provides an alternative block of code that is executed when
none of the previous conditions are true.
Example:
if ($x > 10) {
echo "x is greater than 10";
} else {
echo "x is 10 or less";
}
Nested If Statements
You can nest if statements inside other if statements to handle more complex
logic.
Example:
if ($x > 0) {
if ($x > 5) {
echo "x is greater than 5";
} else {
echo "x is greater than 0 but less than or equal to 5";
}
}
1. Switch() Statements in PHP
Example:
$day = 2;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
default:
echo "Invalid day";
}
Output: Tuesday
The while() loop repeatedly executes a block of code as long as the specified
condition is true.
Example:
$count = 1;
while ($count <= 5) {
echo "Count is: $count<br>";
$count++; // Increment the counter
}
Output:
csharp
Copy code
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
The for() loop is used when you know in advance how many times you want to
execute a statement or a block of statements.
• initialization: This is executed before the loop starts (typically used to set
the loop counter).
• condition: The loop will run as long as this condition evaluates to true.
• increment: After each iteration, this expression is executed (usually used to
update the loop counter).
Example:
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: $i<br>";
}
Output:
makefile
Copy code
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
4. PHP Functions
PHP allows you to define functions that can be reused throughout your code.
Functions are blocks of code that can accept parameters and return values. They
help modularize code and reduce repetition.
PHP has many built-in functions for tasks like working with strings, arrays, dates,
etc. For example:
An array in PHP is a variable that can hold multiple values. There are two types of
arrays in PHP: indexed arrays (numerically indexed) and associative arrays
(indexed by keys).
Indexed Array:
echo $colors[0]; // Outputs: Red
Associative Array:
echo $person["name"]; // Outputs: John
You can modify array elements after they are created by directly assigning new
values to specific indices or keys.
To add elements to an array, use functions like array_push() for indexed arrays or
simply assign values for associative arrays.
Indexed Array:
array_push($colors, "Purple"); // Adds "Purple" at the end of the
array
print_r($colors); // Outputs: Array ( [0] => Red [1] => Green [2] =>
Blue [3] => Purple )
Associative Array:
$person["location"] = "New York"; // Adds a new key-value pair to the
array
print_r($person); // Outputs: Array ( [name] => John [age] => 31
[gender] => male [location] => New York )
1. Processing Arrays with Loops
When dealing with arrays, you'll often need to iterate over the elements to process
or display the data. PHP provides several ways to loop through arrays, but the most
common loops used for this purpose are for(), foreach(), and while().
The foreach() loop is specifically designed for iterating over arrays, making it the
most convenient way to process array elements. It automatically handles both
indexed and associative arrays.
• This loops through each element of the $colors array and assigns the value of each
element to $color on each iteration.
• This loops through each element of the associative array $person, providing both the
key and the value.
Example Output:
name: John
age: 30
gender: male
The for() loop is useful for indexed arrays when you know the number of
elements or want to work with the indices directly.
php
Copy code
$colors = array("Red", "Green", "Blue");
for ($i = 0; $i < count($colors); $i++) {
echo $colors[$i] . "<br>";
}
• The count() function gives the number of elements in the array, and the loop
continues until it reaches the last element.
You can also use the while() loop to iterate through arrays. However, you'll need a
separate counter or pointer to keep track of the array index.
$colors = array("Red", "Green", "Blue");
$i = 0;
while ($i < count($colors)) {
echo $colors[$i] . "<br>";
$i++;
}
When creating web forms, it's common to group related options together in a
dropdown or checkbox list. You can use arrays to process and manage multiple
form selections. For example, you may need to process multiple checkbox values
that are selected by the user.
Consider a form where the user selects multiple hobbies using checkboxes.
<form action="process.php" method="post">
<label><input type="checkbox" name="hobbies[]" value="Reading">
Reading</label><br>
<label><input type="checkbox" name="hobbies[]" value="Cooking">
Cooking</label><br>
<label><input type="checkbox" name="hobbies[]" value="Traveling">
Traveling</label><br>
<input type="submit" value="Submit">
</form>
• The name="hobbies[]" attribute ensures that the selected checkbox values are
grouped into an array.
In the PHP script process.php, you can retrieve the array of selected hobbies:
if (isset($_POST['hobbies'])) {
$hobbies = $_POST['hobbies']; // This will be an array
foreach ($hobbies as $hobby) {
echo $hobby . "<br>";
}
} else {
echo "No hobbies selected.";
}
• If the user selects "Reading" and "Traveling", the $hobbies array will contain the
values ["Reading", "Traveling"].
8. array_search() - Searches for a value in an array and returns the key of the
first occurrence.
$fruits = array("Apple", "Banana", "Orange");
$key = array_search("Banana", $fruits);
echo $key; // Outputs: 1 (index of "Banana")
Let's say we want to process a list of products selected in a form and display the
total value of selected products.
$form_values = array("apple" => 1.99, "banana" => 0.99, "orange" =>
1.49);
$selected_products = array("apple", "orange");
$total_price = 0;
foreach ($selected_products as $product) {
if (array_key_exists($product, $form_values)) {
$total_price += $form_values[$product];
}
}
• Here, $form_values is an associative array containing product names and their prices.
• We loop through the selected products and check if the product exists in the array, then
sum up the total price.
1. Reading Data from a File
PHP provides several functions for reading data from files. The most commonly
used functions for this task are:
The fopen() function opens a file for reading or writing. To read a file, you first
need to open it in the appropriate mode, and then use fread() to read the content.
if ($file) {
$content = fread($file, filesize("example.txt")); // Read the
entire content of the file
echo $content; // Display the content
fclose($file); // Close the file
} else {
echo "Could not open the file.";
}
?>
• fopen("example.txt", "r"): Opens the file example.txt in read mode. If the file
exists and can be opened, it returns a file pointer.
• fread($file, filesize("example.txt")): Reads the entire file content. The
second parameter, filesize(), specifies how many bytes to read. We use
filesize() to ensure we read the entire file.
• fclose($file): Closes the file after reading.
If you want to read a file line by line, you can use fgets(). This function reads a
single line at a time, which can be useful when processing large files.
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line . "<br>"; // Print each line
}
fclose($file); // Close the file
} else {
echo "Could not open the file.";
}
?>
• fgets($file): Reads one line at a time from the file. The loop continues until it
reaches the end of the file (false).
• The while loop ensures that each line of the file is read and printed.
PHP also allows you to write data to a file. You can either append to a file or
overwrite it entirely. The key functions for writing to files are:
The fwrite() function is used in combination with fopen() to write data to a file.
You can specify whether to overwrite or append the file by choosing the
appropriate mode in fopen().
if ($file) {
fwrite($file, "This is some new content.\n"); // Write data to
the file
fwrite($file, "This is a second line.\n");
fclose($file); // Close the file
} else {
echo "Could not open the file for writing.";
}
?>
• fopen("example.txt", "w"): Opens the file example.txt for writing. The "w"
mode will overwrite the file if it exists or create a new file if it doesn't.
• fwrite($file, "text"): Writes the specified string into the file.
• fclose($file): Closes the file after writing.
• FILE_APPEND: This flag tells PHP to append the content instead of overwriting the file.
It's important to handle errors when working with files, as file operations can fail
for various reasons (e.g., file not found, permissions issues). PHP provides
functions like is_readable(), is_writable(), and file_exists() to check file
status before performing operations.
if (file_exists($file_path)) {
if (is_readable($file_path)) {
$content = file_get_contents($file_path);
echo $content;
} else {
echo "The file is not readable.";
}
} else {
echo "The file does not exist.";
}
?>
A session allows you to store information (in variables) across multiple pages for a
user. This information is available throughout the user's visit (session). A session is
identified by a unique session ID, which PHP generates automatically. Sessions are
stored on the server, and the session ID is typically passed to the browser via
cookies.
Starting a Session
To use session variables, you first need to start a session using the
session_start() function. This function must be called at the beginning of the
script, before any HTML or other output.
• session_start(): Starts the session and ensures that the session ID is passed
between the client and the server.
• $_SESSION['variable_name']: Used to store data in the session. In this case, we
store the username 'john_doe'.
Once a session is started, you can store and retrieve data using the $_SESSION
superglobal array. You can use it to store any type of data, such as user
preferences, authentication information, etc.
if (isset($_SESSION['username'])) {
echo "Hello, " . $_SESSION['username']; // Output the session
data
} else {
echo "No session found.";
}
?>
• isset(): Checks if the session variable exists.
• $_SESSION['username']: Retrieves the stored session data.
Destroying a Session
You can destroy a session using session_destroy(), which removes all session
data. It's also a good practice to unset individual session variables using unset()
before calling session_destroy().
A cookie is a small piece of data that the server sends to the user's browser. The
browser stores the cookie, and it is sent back to the server with each subsequent
request. Cookies can be used to store user preferences, login information, or other
data across multiple visits.
Setting Cookies
To set a cookie in PHP, you use the setcookie() function. Cookies have an
expiration time, which can be set. If you don't specify an expiration time, the
cookie will last until the user's browser session ends.
You can check if a cookie is set using the isset() function, just like session
variables.
Deleting a Cookie
To delete a cookie, you can set its expiration time to a time in the past (for
example, time() - 3600). This instructs the browser to remove the cookie.
• Security: Be cautious when using sessions and cookies for sensitive data. Cookies can be
manipulated by users, so avoid storing sensitive information like passwords directly in
cookies. For sensitive data, always store it in a session.
• Session Cookies: By default, sessions are stored in cookies, and they expire when the
browser is closed. You can set a custom expiration time for sessions if needed.
• Cross-Browser Compatibility: Cookies are specific to the browser, so they may not be
available when the user switches browsers or devices.
While basic session management involves starting the session, setting variables,
and destroying sessions, there are additional advanced features and considerations
for better session handling.
Session Timeout
You can set a session timeout to automatically expire the session after a certain
period of inactivity. This is commonly done using the session's last activity
time.
In some cases, you may want to store session data in a database instead of the
default PHP file-based session storage. This is particularly useful for high-traffic
websites or when you want to share session data across multiple servers.
To use a database for session storage, you need to configure PHP to use a custom
session handler.
While cookies are commonly used for storing small pieces of data, they also offer
more advanced functionality, such as setting secure cookies and cookies that are
only sent over HTTPS connections.
For better security, especially when handling sensitive information (like tokens or
preferences), you can set cookies to be secure and HTTP-only. A secure cookie is
only sent over HTTPS, and an HTTP-only cookie cannot be accessed through
JavaScript, reducing the risk of cross-site scripting (XSS) attacks.
Example: Setting Secure Cookies
<?php
// Set a secure, HTTP-only cookie that expires in 1 day
setcookie('user', 'john_doe', time() + 86400, '/', '', true, true); //
Secure & HttpOnly flags
if (isset($_COOKIE['user'])) {
echo "Welcome, " . $_COOKIE['user']; // Access the cookie data
} else {
echo "Cookie not set.";
}
?>
• Secure flag (true): Ensures the cookie is sent only over HTTPS.
• HTTP-only flag (true): Prevents the cookie from being accessed by JavaScript, adding
an extra layer of security.
The SameSite cookie attribute controls whether cookies should be sent with cross-
site requests, providing protection against cross-site request forgery (CSRF)
attacks.
• SameSite=Strict: The cookie is only sent if the request is from the same origin.
• SameSite=Lax: The cookie is sent with top-level navigations (e.g., clicking a link).
• SameSite=None: The cookie is sent with all requests (must be Secure).
• 'samesite' => 'Strict': Ensures the cookie is only sent for requests originating
from the same site.
Sessions are widely used for user authentication. When a user logs in, their
credentials are verified, and session variables are set to store their user data (such
as user ID or username). The session ID is then passed with each subsequent
request to keep the user logged in.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
• Session Variables: After login, the username is stored in a session to keep the user
logged in across pages.
For sites with a "Remember Me" feature, you can store a long-lasting cookie that
keeps the user logged in even after the session ends. When the user visits the site
again, the cookie can be checked, and if valid, they are automatically logged in.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['remember_me'])) {
// Set a cookie to remember the user
setcookie('user', $_POST['username'], time() + 86400 * 30,
'/', '', true, true); // Expire in 30 days
}
$_SESSION['username'] = $_POST['username'];
echo "You are logged in.";
} elseif (isset($_COOKIE['user'])) {
// Auto-login if the cookie is set
$_SESSION['username'] = $_COOKIE['user'];
echo "Welcome back, " . $_SESSION['username'];
} else {
echo "Please log in.";
}
?>