PHP Tutorial

Introduction to PHP

Welcome to the comprehensive PHP tutorial! PHP (Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

What is PHP?

PHP is a server-side scripting language, meaning it runs on the web server, not in the user's browser. When a user requests a page containing PHP code, the server processes the PHP code, generates plain HTML, and then sends that HTML to the user's browser. This makes PHP ideal for dynamic content, database interactions, and user authentication.

Setting Up Your Development Environment

To run PHP code, you need a web server (like Apache or Nginx) and a PHP interpreter. The easiest way to get started is by installing a "WAMP" (Windows, Apache, MySQL, PHP), "LAMP" (Linux, Apache, MySQL, PHP), or "MAMP" (macOS, Apache, MySQL, PHP) stack.

  1. **Download a Stack:** Popular choices include XAMPP (cross-platform), WampServer (Windows), or MAMP (macOS).
  2. **Installation:** Follow the installation instructions for your chosen stack. This will typically install Apache (or Nginx), MySQL (or MariaDB), and PHP.
  3. **Start Servers:** After installation, start the Apache/Nginx and MySQL services from the control panel provided by your stack.
  4. **Create a PHP file:** PHP files typically have the `.php` extension. Place your PHP files in the web server's document root (e.g., `htdocs` for XAMPP).
  5. **Access in Browser:** Open your web browser and navigate to `http://localhost/your_file.php` (replace `your_file.php` with your actual file name).

Your First PHP Program: "Hello, World!"

Let's write the classic "Hello, World!" program. Save this code as `hello.php` in your web server's document root.


<!DOCTYPE html>
<html>
<body>

<h1>My First PHP Page</h1>

<?php
echo "Hello, World!"; // The echo statement is used to output text
?>

</body>
</html>
            

Explanation:


PHP Fundamentals

Variables and Data Types

Variables in PHP start with a dollar sign (`$`). PHP is a loosely typed language, meaning you don't have to declare the data type of a variable, it's determined at runtime.


<?php
$name = "Alice"; // String
$age = 30; // Integer
$price = 19.99; // Float
$is_active = true; // Boolean
$fruits = array("Apple", "Banana", "Cherry"); // Array

echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Price: " . $price . "<br>";
echo "Is Active: " . ($is_active ? "Yes" : "No") . "<br>";
echo "First Fruit: " . $fruits[0] . "<br>";
?>
            

Common data types include String, Integer, Float (or Double), Boolean, Array, Object, NULL, and Resource.

Operators

Operators are used to perform operations on values and variables.


<?php
$x = 10;
$y = 5;

echo "Addition: " . ($x + $y) . "<br>"; // 15
echo "Subtraction: " . ($x - $y) . "<br>"; // 5
echo "Multiplication: " . ($x * $y) . "<br>"; // 50
echo "Division: " . ($x / $y) . "<br>"; // 2
echo "Modulus: " . ($x % $y) . "<br>"; // 0

$is_equal = ($x == $y); // false
$is_identical = ($x === 10); // true (value and type match)
?>
            

Control Flow

Control flow statements dictate the order in which code is executed.

If-Elseif-Else Statements


<?php
$time = date("H"); // Get current hour (0-23)

if ($time < "12") {
    echo "Good morning!";
} elseif ($time < "18") {
    echo "Good afternoon!";
} else {
    echo "Good evening!";
}
?>
            

Switch Statements


<?php
$favcolor = "red";

switch ($favcolor) {
    case "red":
        echo "Your favorite color is red!";
        break;
    case "blue":
        echo "Your favorite color is blue!";
        break;
    case "green":
        echo "Your favorite color is green!";
        break;
    default:
        echo "Your favorite color is neither red, blue, nor green!";
}
?>
            

Loops (while, for, foreach)


<?php
// While loop
$i = 1;
while($i <= 5) {
    echo "The number is: " . $i . "<br>";
    $i++;
}

// For loop
for ($j = 0; $j < 3; $j++) {
    echo "Iteration: " . $j . "<br>";
}

// Foreach loop (for arrays)
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
    echo $value . "<br>";
}
?>
            

Functions

Functions are blocks of code that can be called and reused multiple times.


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

function addNumbers($num1, $num2) {
    return $num1 + $num2;
}

greet("John"); // Call the greet function
$sum = addNumbers(5, 7);
echo "Sum: " . $sum . "<br>"; // Output: Sum: 12
?>
            

Object-Oriented Programming (OOP) in PHP

PHP has robust support for Object-Oriented Programming (OOP), allowing you to structure your code using classes and objects.

Classes and Objects

A **class** is a blueprint, and an **object** is an instance of that class.


<?php
class Car {
    // Properties
    public $model;
    public $color;

    // Constructor
    public function __construct($model, $color) {
        $this->model = $model;
        $this->color = $color;
    }

    // Method
    public function drive() {
        echo $this->model . " is driving.<br>";
    }
}

// Creating objects
$myCar = new Car("Toyota", "Blue");
echo "My car is a " . $myCar->color . " " . $myCar->model . ".<br>";
$myCar->drive();
?>
            

Inheritance

Inheritance allows a class to inherit properties and methods from another class.


<?php
class Vehicle { // Parent class
    public $brand;

    public function __construct($brand) {
        $this->brand = $brand;
    }

    public function honk() {
        echo "Tuut, tuut!<br>";
    }
}

class Bicycle extends Vehicle { // Child class
    public $numberOfGears;

    public function __construct($brand, $gears) {
        parent::__construct($brand);
        $this->numberOfGears = $gears;
    }
}

$myBicycle = new Bicycle("Giant", 21);
echo "My bicycle is a " . $myBicycle->brand . " with " . $myBicycle->numberOfGears . " gears.<br>";
$myBicycle->honk();
?>
            

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common type, often through method overriding or interfaces.


<?php
interface Animal {
    public function makeSound();
}

class Dog implements Animal {
    public function makeSound() {
        echo "The dog barks.<br>";
    }
}

class Cat implements Animal {
    public function makeSound() {
        echo "The cat meows.<br>";
    }
}

$dog = new Dog();
$cat = new Cat();

$animals = array($dog, $cat);

foreach ($animals as $animal) {
    $animal->makeSound();
}
?>
            

Encapsulation

Encapsulation involves bundling data and methods that operate on the data within a single unit (class) and restricting direct access to some of the object's components. This is done using access modifiers (`public`, `protected`, `private`).


<?php
class BankAccount {
    private $balance; // Private property

    public function __construct($initialBalance) {
        $this->balance = $initialBalance;
    }

    public function deposit($amount) {
        if ($amount > 0) {
            $this->balance += $amount;
            echo "Deposited: " . $amount . ". New balance: " . $this->balance . "<br>";
        }
    }

    public function getBalance() { // Public method to access private property
        return $this->balance;
    }
}

$account = new BankAccount(1000);
$account->deposit(500);
echo "Current balance: " . $account->getBalance() . "<br>";
// echo $account->balance; // This would cause an error due to private access
?>
            

Abstraction

Abstraction involves hiding complex implementation details and showing only the necessary features. In PHP, this is achieved using abstract classes and interfaces.


<?php
abstract class Shape {
    abstract public function getArea(); // Abstract method (no implementation)

    public function display() {
        echo "This is a shape.<br>";
    }
}

class Circle extends Shape {
    public $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function getArea() { // Must implement abstract method
        return M_PI * $this->radius * $this->radius;
    }
}

$circle = new Circle(5);
echo "Area of Circle: " . $circle->getArea() . "<br>";
$circle->display();
?>
            

Key PHP Features

PHP Superglobals

PHP Superglobals are built-in variables that are always available in all scopes. They are used to collect data from forms, cookies, sessions, and server information.


<!-- Example of using $_GET (save as example.php) -->
<a href="example.php?name=Alice&age=30">Click Me</a>

<?php
// In example.php
if (isset($_GET['name'])) {
    echo "Hello, " . $_GET['name'] . "! You are " . $_GET['age'] . " years old.<br>";
}
?>
            

Handling HTML Forms

PHP is commonly used to process data submitted through HTML forms.


<!-- Save this as form.html -->
<form action="process_form.php" method="post">
    Name: <input type="text" name="username"><br>
    Email: <input type="email" name="useremail"><br>
    <input type="submit" value="Submit">
</form>

<!-- Save this as process_form.php -->
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST['username']); // Sanitize input
    $email = htmlspecialchars($_POST['useremail']);

    if (!empty($name) && !empty($email)) {
        echo "Thank you, " . $name . "! Your email is " . $email . ".<br>";
    } else {
        echo "Please fill in all fields.<br>";
    }
}
?>
            

Database Interaction (MySQLi and PDO)

PHP can connect to and interact with various databases. MySQL is a popular choice, and PHP offers two main extensions for this: MySQLi and PDO. PDO (PHP Data Objects) is generally recommended for its flexibility and support for multiple database systems.

Using MySQLi (Procedural)


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

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // Output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>
            

Using PDO (Recommended)


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

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // Set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
    $stmt->execute();

    // Set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new RecursiveArrayIterator($stmt->fetchAll()) as $k=>$v) {
        echo "id: " . $v['id'] . " - Name: " . $v['firstname'] . " " . $v['lastname'] . "<br>";
    }
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null; // Close connection
?>
            

Conclusion and Next Steps

This tutorial has provided a strong foundation in PHP, from its basics to advanced features like OOP and database interaction. PHP's versatility makes it a powerful tool for web development. To deepen your understanding:

Happy coding!