PHP Tutorial

Table of Contents

  1. What is PHP?
  2. Installation and Setup
  3. Syntax and Basics
  4. Variables and Data Types
  5. Operators
  6. Control Structures
  7. Functions
  8. Arrays
  9. Strings
  10. Include and Require
  11. Working with Forms
  12. Sessions and Cookies
  13. File Handling
  14. Exception Handling
  15. Object-Oriented Programming in PHP
  16. PHP and MySQL
  17. Advanced Topics

What is PHP?

PHP, which stands for "PHP: Hypertext Preprocessor," is a widely-used open-source scripting language that is especially suited for web development and can be embedded into HTML. It is executed on the server, and the result is returned to the browser as plain HTML. PHP scripts have a file extension of ".php".

PHP is known for its flexibility, ease of use, and a large community of developers. It powers many popular websites and applications, including WordPress, Facebook, and Wikipedia.

Installation and Setup

To start using PHP, you need to set up a web server with PHP installed. Here are the steps:


Installing PHP on Different Operating Systems

Windows: You can use a package like XAMPP or WAMP which includes Apache, MySQL, PHP, and other useful tools.
macOS: Use MAMP or install PHP via Homebrew with brew install php.
Linux: Install Apache and PHP using your distribution's package manager. For example, on Ubuntu:
sudo apt-get install apache2 php libapache2-mod-php


Testing Your Installation

Create a file named info.php in your web server's root directory with the following content:

<?php
phpinfo();
?>

Access http://localhost/info.php in your browser. If you see a page displaying your PHP configuration, you've successfully installed PHP.

Syntax and Basics

PHP scripts are enclosed within <?php ... ?> tags. This tells the server to interpret the enclosed code as PHP.


Basic Syntax

<?php
// Your PHP code goes here
?>

You can also use the shorthand syntax <?= ... ?> to output expressions:

<?= "Hello, World!"; ?>

Note: The shorthand syntax requires the short_open_tag configuration directive to be enabled.


Comments

PHP supports C, C++, and shell-style comments:

<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multi-line comment.
It spans multiple lines.
*/
?>

Variables and Data Types

Variables in PHP are represented by a dollar sign followed by the name of the variable. Variable names are case-sensitive.


Declaring Variables

<?php
$variableName = "Value";
?>

Data Types

String: A sequence of characters.
Integer: A non-decimal number between -2,147,483,648 and 2,147,483,647.
Float (double): A number with a decimal point or in exponential form.
Boolean: Represents two possible states: true or false.
Array: A collection of values.
Object: An instance of a class.
NULL: A variable with no value.
Resource: A special variable holding a reference to an external resource.

Examples

<?php
$string = "Hello, World!";
$integer = 42;
$float = 3.14;
$boolean = true;
$array = array(1, 2, 3);
$nullVariable = NULL;
?>

Operators

Operators are used to perform operations on variables and values.


Arithmetic Operators

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponentiation (introduced in PHP 5.6)

Assignment Operators

Used to write a value to a variable:

=
+=
-=
*=
/=
%=

Comparison Operators

== Equal
=== Identical
!= Not equal
<> Not equal
!== Not identical
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
<=> Spaceship operator (PHP 7+)

Logical Operators

and, && Logical AND
or, || Logical OR
xor Logical XOR
! Logical NOT

Example

<?php
$a = 10;
$b = 5;
$c = $a + $b; // Addition
$d = $a > $b; // Comparison
$e = ($a > $b) && ($b > 0); // Logical AND
?>

Control Structures

Control structures allow you to control the flow of execution in your scripts.


Conditional Statements

if Statement

<?php
if ($a > $b) {
    echo "$a is greater than $b";
}
?>

if...else Statement

<?php
if ($a > $b) {
    echo "$a is greater than $b";
} else {
    echo "$a is not greater than $b";
}
?>

if...elseif...else Statement

<?php
if ($a > $b) {
    echo "$a is greater than $b";
} elseif ($a == $b) {
    echo "$a is equal to $b";
} else {
    echo "$a is less than $b";
}
?>

Switch Statement

<?php
$color = "red";

switch ($color) {
    case "red":
        echo "You selected red.";
        break;
    case "blue":
        echo "You selected blue.";
        break;
    default:
        echo "Color not recognized.";
}
?>

Loops

while Loop

<?php
$i = 0;
while ($i < 5) {
    echo $i;
    $i++;
}
?>

do...while Loop

<?php
$i = 0;
do {
    echo $i;
    $i++;
} while ($i < 5);
?>

for Loop

<?php
for ($i = 0; $i < 5; $i++) {
    echo $i;
}
?>

foreach Loop

<?php
$numbers = array(1, 2, 3, 4, 5);

foreach ($numbers as $number) {
    echo $number;
}
?>

Functions

Functions are blocks of code that can be repeatedly called from different parts of a program.


Defining and Calling Functions

<?php
function sayHello() {
    echo "Hello, World!";
}

sayHello(); // Calls the function
?>

Function Parameters

<?php
function greet($name) {
    echo "Hello, $name!";
}

greet("Alice"); // Outputs: Hello, Alice!
?>

Default Parameters

<?php
function greet($name = "Guest") {
    echo "Hello, $name!";
}

greet(); // Outputs: Hello, Guest!
?>

Return Values

<?php
function add($a, $b) {
    return $a + $b;
}

$result = add(5, 3); // $result is 8
?>

Arrays

Arrays are used to store multiple values in a single variable.


Indexed Arrays

<?php
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[0]; // Outputs: Apple
?>

Associative Arrays

<?php
$age = array("Alice" => 25, "Bob" => 30);
echo $age["Alice"]; // Outputs: 25
?>

Multidimensional Arrays

<?php
$users = array(
    array("name" => "Alice", "age" => 25),
    array("name" => "Bob", "age" => 30)
);

echo $users[0]["name"]; // Outputs: Alice
?>

Array Functions

PHP provides a rich set of functions to work with arrays.

count($array) - Returns the number of elements in an array.
array_merge($array1, $array2) - Merges two or more arrays.
in_array($needle, $haystack) - Checks if a value exists in an array.
array_push($array, $value) - Adds one or more elements to the end of an array.
array_pop($array) - Pops and returns the last value of the array.

Strings

Strings are sequences of characters used to store text.


String Functions

PHP offers a variety of built-in functions to manipulate strings.

strlen($string) - Returns the length of a string.
strpos($haystack, $needle) - Finds the position of the first occurrence of a substring.
str_replace($search, $replace, $subject) - Replaces all occurrences of the search string with the replacement string.
substr($string, $start, $length) - Returns a part of a string.
trim($string) - Strips whitespace from the beginning and end of a string.

String Concatenation

Strings can be concatenated using the dot operator ..

<?php
$greeting = "Hello, " . "World!";
echo $greeting; // Outputs: Hello, World!
?>

Variable Interpolation

When using double-quoted strings, variables are parsed within the string.

<?php
$name = "Alice";
echo "Hello, $name!"; // Outputs: Hello, Alice!
?>

For more complex expressions, use braces:

<?php
$fruit = "apple";
echo "I have {$fruit}s."; // Outputs: I have apples.
?>

Include and Require

The include and require statements are used to include files in your PHP scripts.


include

If the file is not found, a warning is issued, but the script continues execution.

<?php
include 'header.php';
?>

require

If the file is not found, a fatal error occurs, and the script stops execution.

<?php
require 'config.php';
?>

include_once and require_once

These ensure that the file is included only once.

<?php
include_once 'functions.php';
require_once 'database.php';
?>

Working with Forms

PHP can collect form data sent via HTTP GET and POST methods.


Creating an HTML Form

<form action="process.php" method="post">
    Name: <input type="text" name="name">
    <input type="submit" value="Submit">
</form>

Processing Form Data

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    echo "Hello, $name!";
}
?>

Always validate and sanitize user input to prevent security issues like SQL injection and XSS attacks.


Superglobals

PHP provides several superglobal variables:

$_GET - Contains variables passed via the URL parameters.
$_POST - Contains variables passed via the HTTP POST method.
$_REQUEST - Contains variables from both $_GET and $_POST.
$_SERVER - Contains server and execution environment information.
$_SESSION - Contains session variables.
$_COOKIE - Contains HTTP cookies.
$_FILES - Contains information about uploaded files.

Sessions and Cookies

Sessions and cookies are used to store data across multiple pages.


Sessions

Sessions store data on the server.

Starting a Session

<?php
session_start();
$_SESSION['username'] = 'Alice';
?>

Accessing Session Data

<?php
session_start();
echo $_SESSION['username']; // Outputs: Alice
?>

Destroying a Session

<?php
session_start();
session_unset();
session_destroy();
?>

Cookies

Cookies store data on the client's computer.

Setting a Cookie

<?php
setcookie("username", "Alice", time() + (86400 * 30), "/"); // Expires in 30 days
?>

Accessing a Cookie

<?php
echo $_COOKIE['username']; // Outputs: Alice
?>

Deleting a Cookie

<?php
setcookie("username", "", time() - 3600, "/"); // Expired 1 hour ago
?>

File Handling

PHP provides functions to read from and write to files on the server.


Opening a File

<?php
$file = fopen("test.txt", "r"); // Open for reading
?>

Reading from a File

<?php
$content = fread($file, filesize("test.txt"));
echo $content;
?>

Writing to a File

<?php
$file = fopen("test.txt", "w"); // Open for writing
fwrite($file, "Hello, World!");
fclose($file);
?>

File Modes

"r" - Read-only.
"w" - Write-only; truncates existing file or creates new one.
"a" - Write-only; appends to the end of the file.
"x" - Write-only; creates a new file. Returns FALSE if file exists.
"r+" - Read/write.
"w+" - Read/write; truncates existing file or creates new one.
"a+" - Read/write; appends to the end of the file.
"x+" - Read/write; creates a new file. Returns FALSE if file exists.

Exception Handling

Exceptions are used to handle errors in a controlled way.


Try...Catch Blocks

<?php
function divide($dividend, $divisor) {
    if ($divisor == 0) {
        throw new Exception("Division by zero.");
    }
    return $dividend / $divisor;
}

try {
    echo divide(10, 0);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

Custom Exceptions

<?php
class CustomException extends Exception {}

try {
    throw new CustomException("A custom exception occurred.");
} catch (CustomException $e) {
    echo $e->getMessage();
}
?>

Object-Oriented Programming in PHP

PHP supports object-oriented programming (OOP) concepts such as classes, objects, inheritance, and more.


Classes and Objects

<?php
class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function introduce() {
        echo "Hi, I'm {$this->name} and I'm {$this->age} years old.";
    }
}

$person = new Person("Alice", 25);
$person->introduce();
?>

Access Modifiers

public - Accessible from anywhere.
protected - Accessible within the class and its subclasses.
private - Accessible only within the class.

Inheritance

<?php
class Employee extends Person {
    public $position;

    public function __construct($name, $age, $position) {
        parent::__construct($name, $age);
        $this->position = $position;
    }

    public function introduce() {
        parent::introduce();
        echo " I work as a {$this->position}.";
    }
}

$employee = new Employee("Bob", 30, "Developer");
$employee->introduce();
?>

Interfaces

<?php
interface Logger {
    public function log($message);
}

class FileLogger implements Logger {
    public function log($message) {
        // Code to log message to a file
    }
}
?>

Traits

Traits are a mechanism for code reuse in single inheritance languages like PHP.

<?php
trait LoggerTrait {
    public function log($message) {
        echo "Log: $message";
    }
}

class Application {
    use LoggerTrait;

    public function run() {
        $this->log("Application started.");
    }
}

$app = new Application();
$app->run();
?>

PHP and MySQL

PHP can interact with databases like MySQL to store and retrieve data.


MySQLi Extension

The MySQLi extension provides methods to interact with MySQL databases.

Connecting to a Database

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

Executing a Query

<?php
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"];
    }
} else {
    echo "0 results";
}
$conn->close();
?>

Prepared Statements

Prepared statements are used to execute the same or similar SQL statements repeatedly with high efficiency and to prevent SQL injection attacks.

<?php
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

$name = "Alice";
$email = "alice@example.com";
$stmt->execute();

$name = "Bob";
$email = "bob@example.com";
$stmt->execute();

$stmt->close();
$conn->close();
?>

PDO Extension

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP.

Connecting with PDO

<?php
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Advanced Topics


Namespaces

Namespaces are a way of encapsulating items so that same names can be reused without conflict.

<?php
namespace MyProject;

class MyClass {
    // Class code here
}
?>

Anonymous Functions and Closures

<?php
$greet = function($name) {
    echo "Hello, $name";
};

$greet("Alice"); // Outputs: Hello, Alice
?>

Generators

Generators provide a simple way to iterate through data without the need to build an array in memory.

<?php
function xrange($start, $end, $step = 1) {
    for ($i = $start; $i <= $end; $i += $step) {
        yield $i;
    }
}

foreach (xrange(1, 10) as $number) {
    echo $number;
}
?>

Type Declarations (PHP 7+)

PHP allows specifying types for function arguments and return values.

<?php
function add(int $a, int $b): int {
    return $a + $b;
}

echo add(5, 3); // Outputs: 8
?>

Composer and Autoloading

Composer is a dependency manager for PHP. Autoloading allows automatic inclusion of class files.

composer require vendor/package

In your PHP script:

<?php
require 'vendor/autoload.php';
?>

Next: PHP Development Environment

>