PHP Tutorial: Basic to Advanced

PHP Tutorial: Basic to Advanced


1. Introduction to PHP

Exercise: Print « Hello, World! »
Code:

<?php
echo "Hello, World!";
?>

Result: Hello, World!


2. Variables and Data Types

Exercise: Declare different data types and print them.
Code:

<?php
$name = "Alice";
$age = 30;
$isAdult = true;
echo "Name: $name, Age: $age, Adult: $isAdult";
?>

Result: Name: Alice, Age: 30, Adult: 1


3. Control Structures

Exercise: Implement a simple if-else statement.
Code:

<?php
$age = 18;
if ($age >= 18) {
    echo "You are an adult.";
} else {
    echo "You are a minor.";
}
?>

Result: You are an adult.


4. Functions

Exercise: Write a function to calculate the sum of two numbers.
Code:

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

Result: 15


5. Arrays

Exercise: Iterate through an array and print each element.
Code:

<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
    echo $fruit . " ";
}
?>

Result: Apple Banana Cherry


6. Strings

Exercise: Concatenate and print two strings.
Code:

<?php
$greeting = "Hello";
$name = "Alice";
echo $greeting . " " . $name;
?>

Result: Hello Alice


7. File Handling

Exercise: Read a file and print its contents.
Code:

<?php
$content = file_get_contents('file.txt');
echo $content;
?>

Result: (Content of ‘file.txt’)


8. Forms and User Input

Exercise: Create a form to input a name, and welcome the user on submission.
HTML Code:

<form action="" method="post">
  <input type="text" name="name" required>
  <input type="submit" value="Submit">
</form>

PHP Code:

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

Result: Welcome, (name entered in form)!


9. Sessions and Cookies

Exercise: Create a simple counter that increments on each page load using sessions.
Code:

<?php
session_start();
if (!isset($_SESSION['counter'])) {
    $_SESSION['counter'] = 0;
}
$_SESSION['counter']++;
echo "You have visited this page " . $_SESSION['counter'] . " times.";
?>

Result: You have visited this page X times.


10. Object-Oriented Programming (OOP)

Exercise: Define a class and create an instance.
Code:

<?php
class Dog {
  public $name;
  public function bark() {
    return "Woof!";
  }
}

$dog = new Dog();
$dog->name = "Rex";
echo $dog->name . " says " . $dog->bark();
?>

Result: Rex says Woof!


11. Error and Exception Handling

Exercise: Divide two numbers, handling division by zero.
Code:

<?php
function divide($a, $b) {
    if ($b == 0) {
        return "Cannot divide by zero!";
    }
    return $a / $b;
}

echo divide(10, 0);
?>

Result: Cannot divide by zero!


12. Database Connection (MySQL)

Exercise: Fetch data from a database.
Code:

<?php
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$sql = "SELECT name FROM users";
foreach ($pdo->query($sql) as $row) {
    echo $row['name'] . "<br />";
}
?>

Result: (Names of users in the database)


13. Web Security: Input Validation

Exercise: Sanitize user input.
Code:

<?php
$username = strip_tags($_POST['username']);
$username = stripslashes($username);
echo "Welcome, $username!";
?>

Result: Welcome, (sanitized username)!


14. JSON and APIs

Exercise: Encode an array into JSON.
Code:

<?php
$data = ["name" => "Alice", "age" => 30];
$json = json_encode($data);
echo $json;
?>

Result: {« name »: »Alice », »age »:30}


15. PHP and AJAX

Exercise: Fetch data using AJAX and display it on the page.
HTML Code:

<button onclick="fetchData()">Fetch Data</button>
<div id="data"></div>

JavaScript Code:

function fetchData() {
    // JavaScript code to fetch data from a PHP file and update the "data" div
}

Result: Content fetched using AJAX appears in the « data » div.


16. Building RESTful APIs with PHP

Exercise: Create a simple RESTful API endpoint that returns user details.
Code:

<?php
header("Content-Type: application/json");
$data = ["name" => "Alice", "age" => 30];
echo json_encode($data);
?>

Result: JSON response with user details.


17. Testing in PHP with PHPUnit

Exercise: Write a test for a simple class.
Code:

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

class CalculatorTest extends PHPUnit\Framework\TestCase {
  public function testAdd() {
    $calculator = new Calculator();
    $result = $calculator->add(5, 10);
    $this->assertEquals(15, $result);
  }
}
?>

Result: Test passes or fails based on the implementation.


18. PHP Frameworks: Introduction to Laravel

Exercise: Create a basic CRUD application using Laravel.
Code: (Complex and beyond the scope of this tutorial snippet)
Result: A functioning CRUD application built with Laravel.


19. Performance and Optimization

Exercise: Implement caching in a PHP application.
Code:

<?php
$cacheFile = 'cache.txt';
if (file_exists($cacheFile)) {
    $content = file_get_contents($cacheFile);
} else {
    $content = get_some_expensive_data();
    file_put_contents($cacheFile, $content);
}
echo $content;
?>

Result: Data is retrieved from the cache or original source, depending on availability.


20. Deploying PHP Applications

Exercise: Deploy a PHP application to a live server.
Code: (Deployment commands and server configuration)
Result: A live, accessible PHP application.


By following this comprehensive guide, you’ll have hands-on experience with various PHP topics, ranging from basic syntax to advanced concepts like OOP, APIs, security, and more. Feel free to expand, modify, and experiment with the exercises to deepen your understanding.