PHP Introduction: Step-by-Step Guide & Best Practices

What is PHP?

PHP (Hypertext Preprocessor) is a widely used open-source scripting language designed for web development. It runs on the server and is embedded in HTML to create dynamic web pages.

Setting Up PHP

Install a Local Server Environment

To run PHP locally, install one of the following:

Verify PHP Installation

After installation, check if PHP is installed:

  1. Open the command prompt (Windows) or terminal (Mac/Linux).
  2. Type:
php -v

This should display the PHP version.

Writing Your First PHP Script

  1. Create a new file: index.php
  2. Add the following code:
     
<?php
echo "Hello, World!";
?>

Save the file in the htdocs (XAMPP) or www (WAMP) directory.

Start Apache from your local server.

Open a browser and visit:

arduino
 
http://localhost/index.php

You should see Hello, World!

 

PHP Syntax Basics

 Variables

$name = "John";
$age = 25;
echo "My name is $name and I am $age years old.";

Data Types

PHP supports:

  • Strings ("Hello")
  • Integers (100)
  • Floats (10.5)
  • Booleans (true or false)
  • Arrays (["Apple", "Banana"])
  • Objects

Conditional Statements

$score = 75;
if ($score >= 50) {
    echo "You passed!";
} else {
    echo "You failed!";
}

 Loops

for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i <br>";
}

 Best Practices for Writing PHP Code

Use Meaningful Variable & Function Names
Bad:

$x = 100;
function a() {}

Good:

$userAge = 100;
function calculateTotal() {}

Sanitize User Input to Prevent Security Issues

$username = htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8');

Use Prepared Statements for SQL Queries

$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();

Enable Error Reporting for Debugging

error_reporting(E_ALL);
ini_set('display_errors', 1);

Follow PSR Coding Standards

  • PSR-1: Basic coding standard
  • PSR-2: Coding style guide
  • PSR-4: Autoloading standard