Introduction to PHP

Jun 28, 2024

Introduction to PHP

Overview

  • PHP is a server-side scripting language used to create dynamic web pages.
  • Runs on a server, not the user's web browser.
  • Used by approximately 70% of websites.

Why Use PHP?

  • Speed, simplicity, and flexibility.
  • Popular among small businesses and freelancers.

History

  • Released in 1995.
  • Originally stood for Personal Home Page.
  • Later renamed to PHP Hypertext Preprocessor.
  • Mascot: Elephant named 'elephant Ella'.

Basic PHP Workflow

  1. Browser sends a request to the server.
  2. PHP processes the request on the server.
  3. Server sends back HTML to the browser.
  4. PHP can interact with databases like MySQL, PostgreSQL, Oracle.
  5. Can be embedded in HTML.

Requirements

  • Basic understanding of HTML.
  • MySQL knowledge (later needed).
  • Web server software (e.g., XAMPP).
  • Text editor (e.g., Visual Studio Code).

Setting Up the Environment

Downloading XAMPP and VS Code

Configuring XAMPP

  • Open XAMPP Control Panel.
  • Start Apache and MySQL services.
  • Ensure the Apache and MySQL modules are green.

Basic PHP File Setup

  • Create a directory in htdocs called website.
  • Within that directory, create a file named index.php with basic PHP syntax to output text.

PHP Syntax and Operations

Basic Syntax

  • PHP code starts with <?php and ends with ?>.
  • To display output: echo 'text';.

Variables and Data Types

  • Variables declared with $ (e.g., $name).
  • Key data types: strings, integers, floats, booleans.
  • Example: $name = 'John';.

Arithmetic Operations

  • Operators: +, -, *, /, **, %.
  • Increment and decrement: ++, --.

Conditional Statements

  • if, else if, else.
  • Example: if ($a > $b) { echo 'a is larger'; } else { echo 'a is not larger'; }.

Logical Operators

  • && (and), || (or), ! (not).

Switch Statements

  • Useful for multiple conditions.
  • Example:
switch ($value) {
    case 1:
        echo 'One';
        break;
    // more cases
}

Loops

For Loop

  • Syntax:
for ($i = 0; $i < 10; $i++) {
    echo $i;
}

While Loop

  • Syntax:
while ($i < 10) {
    echo $i;
    $i++;
}

Arrays and Functions

Arrays

  • Declare an array:
$foods = array('Apple', 'Orange', 'Banana');
  • Access elements with index: $foods[0].
  • Associative arrays:
$capitals = array('USA' => 'Washington DC', 'Japan' => 'Tokyo');
  • Loop through an array: foreach ($foods as $food) { echo $food; }

Functions

  • Declare a function:
function sayHello() {
    echo 'Hello';
}
  • Call a function: sayHello();
  • Functions with parameters and return values:
function add($a, $b) {
    return $a + $b;
}

PHP and HTML Forms

GET and POST

  • Use $_GET and $_POST to collect form data.
  • Example:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = $_POST['name'];
    echo $name;
}

String Functions

Common Functions

  • Convert to lower case: strtolower($str).
  • Convert to upper case: strtoupper($str).
  • Trim spaces: trim($str).
  • Replace substrings: str_replace('search', 'replace', $str).

Cookies and Sessions

Cookies

  • Set a cookie: setcookie('name', 'value', time() + 86400);.
  • Accessing cookies: $_COOKIE['name'].

Sessions

  • Start session: session_start();.
  • Set session variables: $_SESSION['name'] = 'value';.
  • Access session variables across pages.

Connecting to a MySQL Database

Using mysqli extension

  • Establish a connection:
$con = mysqli_connect('localhost', 'root', '', 'database');
  • Check connection:
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

CRUD Operations

Insert

  • Basic insert statement:
$sql = "INSERT INTO users (name, password) VALUES ('John', '1234')";
mysqli_query($con, $sql);

Retrieve

  • Basic select statement:
$sql = "SELECT * FROM users WHERE id = 1";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);

Security and Validation

Sanitizing Input

  • filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);

Validating Input

  • filter_var($email, FILTER_VALIDATE_EMAIL);

Hashing Passwords

  • Hash a password: password_hash($password, PASSWORD_DEFAULT);
  • Verify password: password_verify($password, $hash);

Exception Handling

  • Use try and catch to handle exceptions.

Including Files

  • Include: include('file.php');
  • Require: require('file.php');

Final Project: Registration Form

Setup

  • HTML form for registration with username and password fields.
  • PHP script to handle form submission.

Inserting Users

  • Sanitize and validate user input.
  • Hash the password before storing in the database.
  • Check for existing usernames to prevent duplicates.

Conclusion

  • PHP fundamentals.
  • Dynamic web page creation.
  • Database interaction.