PHP Concepts to Start a Project (Part 1)

Speed up your PHP project by learning these key concepts.

Dec 01, 2024

PHP Concepts to Start a Project (Part 1)

PHP is a powerful, open-source server-side scripting language used for web development. Created in 1993, it powers over 70% of websites today due to its simplicity, flexibility, and ease of integration with databases like MySQL. PHP allows developers to build dynamic web applications efficiently, handling server-side logic, user sessions, and database interactions.

To start a PHP project, you only need to grasp a few key concepts that are foundational to web development. Let’s dive in and get you up to speed quickly.

Get Started

To get started, we need to set up a local PHP development environment. This involves installing a development environment (Laragon), a code editor (VS Code), and creating a simple PHP file to run a "Hello, World!" script. Follow these steps:

Install Laragon

  1. Download from laragon.org and install.
  2. Launch Laragon, which includes PHP, MySQL, and Apache.

Install Code Editor (VS Code)

  1. Download from code.visualstudio.com and install.
  2. Install the PHP Intelephense extension for PHP support.

Create Your First PHP File

  1. In Laragon, click root menu, you will go to the www directory. Create a new project folder.
  2. Inside the folder, create a file called index.php.
  3. Open the index.php in Visual Studio Code
  4. Add the following code:
index.php
<?php
  echo "Hello, World!";
?>

Run Your PHP Project

  1. Start the Laragon server by clicking Start All.
  2. Open your browser and visit http://localhost/index.php to see "Hello, World!" displayed.

When you open http://localhost/index.php, the web server (Apache via Laragon) processes the request, finds the index.php file in the www directory, and executes the PHP code. The server then outputs the result, like displaying "Hello, World!" or any HTML content, to the browser.

Congrats! You’ve now set up a simple PHP project.

Basic PHP Syntax

PHP scripts are embedded within HTML using <?php ?> tags. Anything between these tags is treated as PHP code and executed on the server. For example:

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

This outputs "Hello, World!" to the browser.

Note:

  • Always end the statement block with semicolon ;
  • The echo statement is used to output data, whether it's text, HTML, or variables. For example, to output HTML button:
php
<?php
  echo '<button>Click Me!</button>';
?>

This will display a button with the text "Click Me!" on the webpage.

Core Syntax

  • Variables: Variables in PHP are prefixed with the $ sign. You can store different types of data in variables.
  • Data Types: PHP supports several data types: string, integer, float, boolean, array, null, and object (instace of class)
php
<?php
$name = "John" // string
$age = 30;  // integer
$price = 19.99;  // float
$isAvailable = true;  // boolean
$fruits = ["apple", "banana", "cherry"]; // array
$animals = null // null

// class creaton
class Car {
    public $brand; // property / field

    // setter method
    public function setBrand($brand) {
        $this->brand = $brand; // $this refers to the current object
    }

    // getter method
    public function getBrand() {
        return $this->brand;
    }
}

// object initaion
$car = new Car();
echo $car -> brand; // null | accessing property
$car->setBrand("Toyota"); // accessting method
echo $car->getBrand(); // Outputs: Toyota

?>
  • For Loops:
php
<?php
for ($i = 0; $i < 5; $i++) {
  echo $i;
}
?>
  • While loop:
php
<?php
$i = 0;
while ($i < 5) {
  echo $i;
  $i++;
}
?>
  • Foreach loop (works with arrays):
php
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
  echo $fruit;
}
?>
  • Conditionals: Use if, else, elseif to make decisions.
php
<?php
if ($age >= 18) {
  echo "Adult";
} else {
  echo "Minor";
}
?>
  • Functions: You can define functions to group reusable code.
php
<?php
function greet($name) {
  return "Hello, $name!";
}
echo greet("John");
?>
  • Built-in Functions: PHP provides many built-in functions. For example, strlen() to get string length, str_replace() to replace text, and array_merge() to combine arrays. See all built-in functions.
php
<?php
echo strlen("Hello");  // Outputs: 5
?>
  • Interating Over Array
    • array_map(): Applies a function to each element of an array and returns a new array.
    • array_walk(): Applies a function to each element of an array and can modify the original array directly.
php
<?php
// Original array
$numbers = [1, 2, 3];

// Using array_map() - creates a new array
$squared = array_map(fn($n) => $n * $n, $numbers);
print_r($squared); // Output: [1, 4, 9]

// Using array_walk() - modifies the original array
array_walk($numbers, function (&$n) {
    $n = $n * $n;
});
print_r($numbers); // Output: [1, 4, 9]
?>
  • try-catch: used to handle exceptions and manage errors gracefully.
php
<?php

try {
    $result = 10 / 0; // Error-prone code
} catch (DivisionByZeroError $e) { 
    // DivisionByZeroError is built-in error type
    // $e is variable for error
    echo "Error: " . $e->getMessage();
}

?>

Practical Example

Let's create a PHP program to store prime numbers up to a variable $endNumber using a while loop and echo each:

php
<?php
$endNumber = 20;
$primeNumbers = [];
$i = 2;  // Starting from the first prime number

while ($i <= $endNumber) {
    $isPrime = true;
    for ($j = 2; $j <= sqrt($i); $j++) {
        if ($i % $j == 0) {
            $isPrime = false;
            break;
        }
    }
    if ($isPrime) {
        $primeNumbers[] = $i;
    }
    $i++;
}

foreach ($primeNumbers as $prime) {
    echo $prime . " ";
}
?>

Handling User Input

PHP makes it easy to create and process forms using the $_GET and $_POST superglobals. These allow you to retrieve data submitted by the user.

Creating and Processing Forms

To create a simple form in HTML and send the data to PHP:

html
<form method="POST" action="process.php">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <input type="submit" value="Submit">
</form>

In this form, data is sent using the POST method to process.php. In the PHP file, you can access the form data like this:

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

You can also use the $_GET method to send data through the URL (useful for search or filters):

html
<form method="GET" action="process.php">
  <input type="text" name="search">
  <input type="submit" value="Search">
</form>
process.php
<?php
  $search = $_GET['search'];
  echo "Searching for: $search";
?>

Input Validation and Sanitization

It's important to validate and sanitize user input to prevent malicious data from being processed (e.g., XSS or SQL injection). PHP offers built-in functions to help with sanitizing and validating user input, making it safer to use in your application.

Sanitize Input

Sanitizing input means removing or altering unwanted characters in the data. PHP provides functions like filter_var() to sanitize input data.

Example of sanitizing an email input:

php
<?php
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
?>

Validate Input

Validating input ensures the data matches the expected format. Here is an example of validating an email input:

php
<?php
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
  echo "Invalid email format";
}
?>

Note: PHP's built-in function filter_var() can be used to sanitize and validate user input. The second argument is important: FILTER_SANITIZE_* options clean the input, while FILTER_VALIDATE_* checks if the input meets a specific format. For a full list of sanitization and validation filters, check the PHP documentation.

Example: Form Submission with Feedback

Here's a simple form with feedback on the data entered:

index.php
<form method="POST" action="index.php">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <input type="submit" value="Submit">
</form>

// You can combine php code and html in one file php
<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    if (empty($name)) {
      echo "Name is required.";
    } else {
      echo "Hello, $name!";
    }
  }
?>

This simple feedback system checks if the user has submitted the form without entering a name and shows a message accordingly.

Sessions and Cookies

Do you know how servers remember who logged in, even though you only input your password once? Client-server communication is stateless, meaning the server cannot remember the user between requests. Sessions and cookies solve this problem.

What Is a Session & Cookie?

A session allows the server to store user data temporarily. When a user logs in, PHP generates a unique session ID and stores session data on the server. The session ID is then sent to the browser as a cookie.

A cookie is a small piece of data stored on the client side (in the browser). It persists between requests and is sent to the server with each request. After the user logs in, the cookie with the session ID is automatically included in the HTTP request header, enabling the server to recognize the user on subsequent requests.

Creating Sessions and Cookies

  • Creating a Session: Use session_start() to start or resume a session. Store session data in $_SESSION:
php
<?php
session_start();
$_SESSION['username'] = 'john_doe';
echo "Welcome, " . $_SESSION['username'];
?>
  • Creating a Cookie: Use setcookie() to set a cookie. It can store data like user preferences or session IDs:
php
<?php

// setcookie(name, value, expire, path, domain, secure, httponly);
setcookie('user', 'john_doe', time() + 3600 * 24 * 30); // 30 days


echo isset($_COOKIE['user']) ? "Hello, " . $_COOKIE['user'] : "Cookie not set.";
/* The isset() function checks if a variable is set and is not null. It returns true if the variable exists and has a value, otherwise false. */
?>

Sessions store data on the server and maintain user states, while cookies store data on the client side and help with identifying users across multiple requests.

Complete Example Authentication

Here’s a complete example of how to implement sessions and cookies to store user data (username, password, and age), store the session ID, and check if the user is logged in via cookies and sessions.

Login Page

This page allows the user to input their username, password, and age, then stores the data in the session. The session ID is sent as a cookie.

login.php
<?php
session_start(); // Start the session

// Check if form is submitted
if (isset($_POST['submit'])) {
    // Store user data in session
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['password'] = $_POST['password'];
    $_SESSION['age'] = $_POST['age'];

    // Generate a session ID and store it in a cookie
    session_regenerate_id(); // Generate a new session ID for security
    setcookie('PHPSESSID', session_id(), time() + 3600, "/"); // Cookie expires in 1 hour

    echo "Login successful! Redirecting to dashboard...";
    header("Location: dashboard.php"); // Redirect to dashboard
    exit();
}
?>

<!-- HTML Form for User Login -->
<form method="POST">
    <input type="text" name="username" placeholder="Username" required><br>
    <input type="password" name="password" placeholder="Password" required><br>
    <input type="number" name="age" placeholder="Age" required><br>
    <button type="submit" name="submit">Login</button>
</form>

Dashboard Page

This page checks if the user is logged in by looking at the session data and session ID stored in the cookie. If the user is logged in, it displays their data.

dashboard.php
<?php
session_start(); // Start the session

// Check if the session ID cookie exists
if (isset($_COOKIE['PHPSESSID'])) {
    // Check if the session is valid and the user is logged in
    if (isset($_SESSION['username'], $_SESSION['password'], $_SESSION['age'])) {
        echo "<h1>Welcome to Your Dashboard</h1>";
        echo "<p><strong>Username:</strong> " . $_SESSION['username'] . "</p>";
        echo "<p><strong>Password:</strong> " . $_SESSION['password'] . "</p>";
        echo "<p><strong>Age:</strong> " . $_SESSION['age'] . "</p>";
    } else {
        echo "Please log in first.";
    }
} else {
    echo "No session found. Please log in.";
}
?>

This approach uses sessions to store user data securely on the server and cookies to store the session ID on the client-side. It ensures that user data persists across multiple requests until the session expires or the user logs out.

Continue to Part 2

Web Development
PHP