Web Development using PHP
UNIT-I: Introduction to PHP
Introduction to PHP, History of PHP, Versions of PHP, Features of PHP, Advantages of PHP over Other Scripting Languages, software requirements, Installation and Configuration of PHP, Installing and Configuring Apache to use PHP on Windows, Basic HTML, Embedding PHP in HTML, PHP Basic syntax, data types, comments, variables and constants, scope of variables, PHP arrays: creating array and accessing array elements, PHP String, PHP operators, precedence of operators, expressions, creating a PHP Script, running a PHP script.
UNIT-II: PHP Control Structures and Functions
PHP conditional statements, switch case, PHP looping statements, while, for and do while loop, break, continue, exit, PHP functions: built-in and user defined function, declaration and calling of a function, function argument with call by value, call by reference, string manipulation, mathematical, date and time functions.
UNIT-III: Web Forms and Data Handling
Introduction to a web form, processing a web form, capturing form data, passing information between pages, PHP $_GET, PHP $_POST, with multi value fields, validating a web form, input validation, exception and error handling, introduction to cookies and session handling.
UNIT-IV: Database Connectivity with PHP
Working with database: PHP supported databases, using PHP & MySQL: Installation and configuration of MySQL on windows, checking configuration, connecting to database, selecting a database, adding table and altering table in a database, inserting, deleting and modifying data in a table, retrieving data, performing queries, processing result sets.
UNIT-V: Advanced PHP Concepts
Code re-use, require(), include(), and the include_path, PHP file permissions, working with files: opening, closing, reading, writing a file, file system functions and file input and output, working with directory: creating, deleting, changing a directory, file uploads, introduction to object oriented programming with PHP.

UNIT-I: Introduction to PHP

1. Introduction to PHP

PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed for web development. It can be embedded into HTML to create dynamic web pages.

History and Versions

PHP was created by Rasmus Lerdorf in 1994. It has gone through several major versions:

Features of PHP

Advantages Over Other Scripting Languages

2. Software Requirements

3. Installation and Configuration

You can install PHP using XAMPP or WAMP which bundles Apache, MySQL, and PHP.

        Steps for Windows:
        1. Download XAMPP from Apache Friends website.
        2. Install and launch XAMPP Control Panel.
        3. Start Apache and MySQL.
        4. Place PHP files in the htdocs folder.
                

4. Basic HTML and Embedding PHP

PHP is embedded in HTML using <?php ?> tags.

        <!DOCTYPE html>
        <html>
        <body>
            <h1>PHP Test</h1>
            <?php
                echo "Hello World!";
            ?>
        </body>
        </html>
                

5. PHP Syntax and Data Types

        $name = "John"; // String
        $age = 25;      // Integer
        $price = 19.99; // Float
        $is_admin = true; // Boolean
                

6. Variables, Constants, and Scope

Variables are declared with a $ sign. Constants use define(). Variable scope can be local, global, or static.

        define("SITE_NAME", "MySite");
        $x = 5; // Global variable
    
        function testScope() {
            global $x;
            echo $x;
        }
                

7. PHP Arrays

Arrays are used to store multiple values in one variable.

        $fruits = array("Apple", "Banana", "Orange");
        echo $fruits[1]; // Outputs: Banana
                

8. PHP Strings

PHP provides several functions for working with strings like strlen(), str_replace(), and strpos().

        $msg = "Welcome";
        echo strlen($msg); // Outputs: 7
        echo str_replace("Wel", "Hel", $msg); // Outputs: Helcome
                

9. Operators and Expressions

PHP supports arithmetic, comparison, logical, and assignment operators.

        $a = 10;
        $b = 5;
        $sum = $a + $b;
        echo $sum; // 15
                

10. Creating and Running a PHP Script

        // save as hello.php in htdocs
        <?php
            echo "PHP is working!";
        ?>
                

To run: Open http://localhost/hello.php in your browser.

UNIT-II: PHP Control Structures and Functions

1. PHP Conditional Statements

Conditional statements in PHP allow decision-making in code based on conditions.

if Statement

Executes code if the condition is true.

    if (condition) {
        // code to execute
    }
                

if-else Statement

Executes one block if true, another if false.

    if (condition) {
        // true block
    } else {
        // false block
    }
                

if-elseif-else Statement

Multiple conditions can be checked in sequence.

    if (condition1) {
        // block 1
    } elseif (condition2) {
        // block 2
    } else {
        // default block
    }
                

switch Statement

Used to perform different actions based on different conditions.

    switch (variable) {
        case value1:
            // code
            break;
        case value2:
            // code
            break;
        default:
            // default code
    }
                

2. PHP Looping Statements

Loops are used to execute the same block of code repeatedly.

while Loop

    while (condition) {
        // code to be executed
    }
                

do-while Loop

This loop runs the block once before checking the condition.

    do {
        // code to be executed
    } while (condition);
                

for Loop

    for (initialization; condition; increment) {
        // code to be executed
    }
                

Control Statements

3. PHP Functions

Functions are blocks of code that perform specific tasks.

Built-in Functions

User-defined Functions

These functions are created by the user.

    function greet() {
        echo "Hello, World!";
    }
    greet();
                

Function Arguments

Call by Value

    function increment($num) {
        $num++;
    }
                

Call by Reference

    function increment(&$num) {
        $num++;
    }
                

4. String Manipulation Functions

5. Mathematical Functions

6. Date and Time Functions

UNIT-III: PHP Forms, Data Handling & Sessions

1. Introduction to a Web Form

A web form allows users to input data and submit it to a server. Forms are created using the <form> tag.

    
Name: <input type="text" name="username"> <input type="submit" value="Submit">

2. Processing a Web Form

Form data can be processed using PHP with the $_GET or $_POST superglobals depending on the method used.

    <?php
    $name = $_POST['username'];
    echo "Hello, " . $name;
    ?>
                

3. Capturing Form Data

Data entered in the form fields can be captured using:

4. Passing Information Between Pages

You can pass data between pages using:

    
    Click Here
    
    
    <?php echo $_GET['name']; ?>
                

5. PHP $_GET and $_POST with Multi-value Fields

Checkboxes or multiple selects allow sending multiple values.

    
<input type="checkbox" name="fruits[]" value="Apple">Apple <input type="checkbox" name="fruits[]" value="Banana">Banana <input type="submit">
<?php if (isset($_POST['fruits'])) { foreach ($_POST['fruits'] as $fruit) { echo $fruit . "<br>"; } } ?>

6. Validating a Web Form

Validation ensures correct and expected input from users before processing.

Example: Basic Name Validation

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = trim($_POST["name"]);
        if (empty($name)) {
            echo "Name is required.";
        } else {
            echo "Welcome, " . htmlspecialchars($name);
        }
    }
    ?>
                

7. Input Validation Techniques

8. Exception and Error Handling

PHP supports try-catch blocks for handling exceptions gracefully.

    <?php
    try {
        if (!file_exists("data.txt")) {
            throw new Exception("File not found!");
        }
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
    ?>
                

9. Introduction to Cookies

Cookies store small amounts of data on the client-side browser.

    <?php
    setcookie("user", "John", time() + 3600);
    echo $_COOKIE["user"];
    ?>
                

10. Session Handling

Sessions store user data on the server for use across multiple pages.

    <?php
    session_start();
    $_SESSION["username"] = "John";
    echo $_SESSION["username"];
    ?>
                

UNIT-IV: Working with Database in PHP

1. PHP Supported Databases

PHP supports a wide range of databases, including:

MySQL is the most commonly used database with PHP.

2. Using PHP & MySQL

Installation and Configuration of MySQL on Windows

3. Checking Configuration

    <?php
    phpinfo(); // Displays PHP configuration including MySQL support
    ?>
                

4. Connecting to a Database

    <?php
    $conn = mysqli_connect("localhost", "root", "", "mydatabase");
    
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    echo "Connected successfully";
    ?>
                

5. Selecting a Database

Already done during connection using "mydatabase". You can also use:

    mysqli_select_db($conn, "mydatabase");
                

6. Adding and Altering Tables

Create Table

    $sql = "CREATE TABLE students (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50),
        age INT
    )";
    mysqli_query($conn, $sql);
                

Alter Table

    $sql = "ALTER TABLE students ADD email VARCHAR(100)";
    mysqli_query($conn, $sql);
                

7. Inserting, Deleting, and Modifying Data

Insert Data

    $sql = "INSERT INTO students (name, age) VALUES ('John', 20)";
    mysqli_query($conn, $sql);
                

Delete Data

    $sql = "DELETE FROM students WHERE id=1";
    mysqli_query($conn, $sql);
                

Update Data

    $sql = "UPDATE students SET age=21 WHERE name='John'";
    mysqli_query($conn, $sql);
                

8. Retrieving Data

    $sql = "SELECT * FROM students";
    $result = mysqli_query($conn, $sql);
    
    while ($row = mysqli_fetch_assoc($result)) {
        echo $row["name"] . " - " . $row["age"] . "<br>";
    }
                

9. Performing Queries and Processing Result Sets

Use mysqli_query() to perform queries and mysqli_fetch_assoc() to process results.

    $result = mysqli_query($conn, "SELECT * FROM students");
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            echo "Name: " . $row["name"] . ", Age: " . $row["age"] . "<br>";
        }
    } else {
        echo "No records found.";
    }
                

UNIT-V: Code Re-use, File Handling, and OOP in PHP

1. Code Re-use

PHP allows reusing code using require() and include() functions. This helps keep your code modular and maintainable.

    // file: header.php
    <h1>Welcome to My Site</h1>
    
    // file: index.php
    <?php
    include("header.php");
    ?>
                

2. require(), include(), and include_path

    include("config.php");
    require("database.php");
                

include_path: It's a directive that tells PHP where to look for included files. You can set it in php.ini or at runtime.

3. PHP File Permissions

4. Working with Files

Opening and Closing Files

    $file = fopen("data.txt", "r");
    fclose($file);
                

Reading a File

    $file = fopen("data.txt", "r");
    while (!feof($file)) {
        echo fgets($file);
    }
    fclose($file);
                

Writing to a File

    $file = fopen("data.txt", "w");
    fwrite($file, "Hello World!");
    fclose($file);
                

5. File System Functions

    if (file_exists("data.txt")) {
        echo "File size: " . filesize("data.txt");
    }
                

6. Working with Directory

Creating and Deleting Directory

    mkdir("mydir");
    rmdir("mydir");
                

Changing Directory

    chdir("mydir");
    echo getcwd(); // Get current working directory
                

7. File Uploads

To upload files in PHP:

  1. Set form method to POST and enctype="multipart/form-data".
  2. Access uploaded file using $_FILES.
    // HTML form
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="myfile">
        <input type="submit" value="Upload">
    </form>
    
    // PHP handler
    <?php
    move_uploaded_file($_FILES["myfile"]["tmp_name"], "uploads/" . $_FILES["myfile"]["name"]);
    ?>
                

8. Introduction to Object Oriented Programming with PHP

PHP supports OOP with the following concepts:

Basic Example:

    class Car {
        public $color;
    
        function setColor($c) {
            $this->color = $c;
        }
    
        function getColor() {
            return $this->color;
        }
    }
    
    $myCar = new Car();
    $myCar->setColor("Red");
    echo $myCar->getColor();