teaching_web_development

Introduction to PHP

PHP (Hypertext Preprocessor) is a popular server-side scripting language designed for web development but also used as a general-purpose programming language.

It is especially suited for creating dynamic web pages and applications.

Resources

Slides

Features

Philosophy of PHP

Key Features of PHP

Example PHP Code

<h1> Hello from HTML </h1>

<?php
// This is a simple PHP script that outputs "Hello, World!"
echo "Hello, World!";
?>

<p> This is more HTML content. </p>

Hello from HTML
Hello, World!
This is more HTML content.

Getting Started with PHP

_ Click on โ€œStartโ€ to start the Apache server.

Configuring PHP

<?php
// Your PHP code goes here
echo "Hello World!";
?>

PHP Script

Syntax Basics

<?php
$age = 25; // $age is an integer
$name = "Alice"; // $name is a string
$price = 19.99; // $price is a float
?>

๐Ÿ“ Examples

<?php
// Example 1: Variables and Output
$name = "John";
echo "Hello, " . $name . "!"; // Outputs: Hello, John!
?>
<?php
// Example 2: Conditional Statements
$age = 20;
if ($age >= 18) {
    echo "You are an adult.";
} else {
    echo "You are a minor.";
}
?>
<?php
// Example 3: Looping
for ($i = 1; $i <= 5; $i++) {
    echo "Number: " . $i . "<br>";
}
?>
<?php
// Example 4: Functions
function greet($name) {
    return "Hello, " . $name . "!";
} 

echo greet("Alice"); // Outputs: Hello, Alice!
?>
<?php
// Example 5: Arrays
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}
?>

Implicit type conversions

<?php
$number = "10"; // string
$sum = $number + 5; // PHP converts $number to an integer
echo $sum; // Outputs: 15
?>

Operators

<?php
$a = 10;
$b = 5; 
$sum = $a + $b; // Addition
$difference = $a - $b; // Subtraction
$product = $a * $b; // Multiplication
$quotient = $a / $b; // Division
$isEqual = ($a == $b); // Comparison
$isGreater = ($a > $b); // Comparison
$andCondition = ($a > 5 && $b < 10); // Logical AND
$orCondition = ($a < 5 || $b < 10); // Logical OR
?>

Increment and Decrement Operators

๐ŸŽฎ Fun Activity

<?php
$x = 12;
$y = 15 + $x++;
echo "x is $x and y is $y";
$z = 20 + ++$x;
echo "x is $x and y is $y and z is $z";
?>

String concatenation

<?php

$a = "Hello " . "World";
echo $a . "\n";

?>

Side effect assignment

<?php

$x = 10;
$x += 2;
echo $x;

?>

Type casting

<?php

$x = 56;
$y = 12;
echo $x / $y;

?>

Activities: ๐ŸŽฎ

<?php

$z = "100" + 36.25 + TRUE;
echo $z;

?>

<?php

echo "100" + (string) 10;

?>
<?php

echo "100" . string(10)

?>
<?php

echo (int) 9.9 - 1.9;

?>
<?php

echo "Soumya" . 25;

?>
<?php

echo "Soumya" + 25;

?>

Equality vs. Identity

<?php
if (123 == "123") print ("Equal \n");

if (123 === "123") print ("Equal \n");
?>

Function return values

Comments

Diagrammatic summary of PHP basics

Summary of PHP basics

๐Ÿ› ๏ธ Interview with PHP creator

Arrays

<?php
$str_array = array("Hello", "World");
echo $str_array[1];
?>

Array functions

Functions

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

Form processing in PHP

๐ŸŽฎ Practical for PHP forms


<p> Forms in PHP</p>
<form method="post">
  <label>Input guess</label>
    <input type="text" name="guess" id="guess"/>
    <input type="submit">
</form>


<?php
print_r($_POST)
?>

๐ŸŽฎ Full code


<!DOCTYPE html>
<html>
<body>

<?php
$txt = "PHP";
echo "I love $txt!";
?>


<p> Forms in PHP</p>

<form method="post">
  <label>Input guess</label>
    <input type="text" name="guess" id="guess"/>
    <input type="submit">
</form>


<pre>
<?php
print_r($_POST)
?>
</pre>

</body>
</html>

Other input types in forms

๐ŸŽฎ Exercise

Try the following in PHP

Solution Example

<!DOCTYPE html>
<html>
<body>

<h2>Login Form</h2>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $age = $_POST['age'] ?? '';
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    // Age check server side
    if (!is_numeric($age) || (int)$age < 18) {
        echo "<p><em>No further access</em></p>";
    } else {
        // Check alphanumeric no special symbols for username
        if (!preg_match("/^[a-zA-Z0-9]+$/", $username)) {
            echo "<p>Username must be alphanumeric with no special symbols.</p>";
        } else {
            echo "<p>Welcome, " . htmlspecialchars($username) . "!</p>";
        }
    }
}
?>
```php

- `input.html` should have the following

```html
<form method="post" action="welcome.php">
  <label for="age">Age:</label><br>
  <input type="text" name="age" id="age" required><br><br>

  <label for="username">Username (alphanumeric only):</label><br>
  <input type="text" name="username" id="username" required><br><br>

  <label for="password">Password:</label><br>
  <input type="password" name="password" id="password" required><br><br>

  <input type="submit" value="Submit">
</form>

</body>
</html>

Client-Side Age Check (JavaScript)

You can also use JavaScript to perform the age validation directly in the browser before the form is even submitted:

<script>
document.querySelector("form").addEventListener("submit", function(event) {
    const ageInput = document.getElementById("age").value;
    
    // Check if the age is numeric and 18 or older
    if (isNaN(ageInput) || Number(ageInput) < 18) {
        event.preventDefault(); // Stop form from submitting
        alert("No further access: You must be 18 or older.");
    }
});
</script>

Client side vs. Server side validation

HTML Forms and inserting data to SQL database using PHP

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Search Students</title>
</head>
<body>
  <h1>Search Students</h1>

  <form action="search.php" method="post">
    <label for="name">Student name:</label>
    <input type="text" id="name" name="name" required>

    <button type="submit">Search</button>
  </form>
</body>
</html>
<?php
require_once "db.php";

$name = $_POST["name"] ?? "";

if ($name === "") {
    die("Please enter a name.");
}

$sql = "SELECT id, name, email FROM students WHERE name LIKE :name";
$stmt = $pdo->prepare($sql);
$stmt->execute([
    ":name" => "%" . $name . "%"
]);

$results = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Search Results</title>
</head>
<body>
  <h1>Search Results</h1>

  <?php if (count($results) > 0): ?>
    <table border="1" cellpadding="8">
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
      </tr>
      <?php foreach ($results as $row): ?>
        <tr>
          <td><?= htmlspecialchars($row["id"]) ?></td>
          <td><?= htmlspecialchars($row["name"]) ?></td>
          <td><?= htmlspecialchars($row["email"]) ?></td>
        </tr>
      <?php endforeach; ?>
    </table>
  <?php else: ?>
    <p>No matching students found.</p>
  <?php endif; ?>

  <p><a href="index.html">Back</a></p>
</body>
</html>



- `db.php`

```php
<?php
$host = "localhost";
$dbname = "school";
$username = "root";
$password = "";

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

Cookies

Sessions

Next: Javascript