PHP: Starting out

Day 1 Task: Introduction to PHP & Setup

Goals:

  • Understand what PHP is.

  • Set up the development environment (local server).

  • Write your first PHP script.


Step-by-Step Tasks:

1. Install XAMPP/MAMP (Development Environment)

  • Download and install XAMPP:

    • Go to XAMPP's official website.

    • Download and install XAMPP based on your operating system (Windows, macOS, or Linux).

    • Open XAMPP and start the Apache server (this will allow PHP to run locally).

  • OR Install MAMP (if you prefer MAMP):

2. Setting up Your First PHP Project

  • After installing XAMPP/MAMP, navigate to the htdocs directory (XAMPP) or MAMP's root directory (MAMP), and create a new folder for your PHP project, e.g., my_first_php_site.

  • In the folder, create a PHP file. Name it index.php.

3. Write Your First PHP Script

  • Open index.php in your text editor (e.g., VSCode, Sublime Text, or even Notepad++).

  • Add this simple PHP code:

<?php
// This is a simple PHP script
echo "Hello, World! Welcome to PHP!";
?>
  • Explanation:

    • <?php and ?> are PHP tags that tell the server to run PHP code inside them.

    • echo is a command used to display output on the browser.

    • Everything after // is a comment in PHP, which is ignored when the script runs.

4. View the Output in a Browser

5. Modify the Script

  • Try modifying the message displayed by changing the text inside the echo statement.
<?php
echo "This is my first PHP website!";
?>
  • Refresh your browser, and you should see the new message.

Task Recap for Day 1:

  1. Install a local development environment (XAMPP/MAMP).

  2. Create a folder in the local server's directory (htdocs) for your PHP project.

  3. Write a basic PHP script with the echo statement to output text to the browser.

  4. Test your script by opening it in your browser.


Goal for Day 1:

  • By the end of Day 1, you should have a basic understanding of how PHP works and be able to set up a simple PHP script that displays text in your browser.

Day 2 Task: Variables, Data Types & Operators in PHP

Goals:

  • Learn how to use variables and different data types in PHP.

  • Understand how to use operators (arithmetic, assignment, comparison) in PHP.


Step-by-Step Tasks:

1. Understanding Variables in PHP

  • Variables are used to store data. In PHP, variables are declared using the $ symbol followed by the variable name.
<?php
$name = "John";      // String variable
$age = 25;           // Integer variable
$height = 5.9;       // Float variable
$isStudent = true;   // Boolean variable
?>
  • Rules for Naming Variables:

    • Variable names must start with a letter or an underscore ($name, $age), but not a number ($1name is invalid).

    • Variable names are case-sensitive ($name and $Name are different).

2. Displaying Variables

  • You can display the value of a variable using echo or print.
<?php
$name = "John";
$age = 25;

echo "Hello, my name is $name and I am $age years old.";
?>
  • Note: PHP supports variable interpolation inside double-quoted strings, which means you can directly place variables inside the string.

3. Data Types in PHP

PHP supports several types of data:

  • String: Text data, e.g., "Hello, World!"

  • Integer: Whole numbers, e.g., 25, 100

  • Float: Decimal numbers, e.g., 3.14, 9.8

  • Boolean: true or false

  • Array: A collection of data.

  • NULL: Represents no value.

<?php
$stringVar = "Hello";     // String
$intVar = 100;            // Integer
$floatVar = 99.9;         // Float
$boolVar = true;          // Boolean
$arrayVar = [1, 2, 3];    // Array
$nullVar = null;          // NULL
?>

4. Using var_dump() to Inspect Variables

  • The var_dump() function is useful for debugging and checking the data type and value of a variable.
<?php
$age = 25;
var_dump($age);   // Output: int(25)
?>
  • This will show the data type and the value of the variable.

5. Operators in PHP

  • Arithmetic Operators: Used to perform basic math operations.

    • + (addition), - (subtraction), * (multiplication), / (division), % (modulo)
<?php
$num1 = 10;
$num2 = 5;
echo $num1 + $num2;  // Output: 15
echo $num1 - $num2;  // Output: 5
echo $num1 * $num2;  // Output: 50
echo $num1 / $num2;  // Output: 2
?>
  • Assignment Operators: Used to assign values to variables.

    • = (simple assignment), +=, -=, *=, /=
<?php
$x = 10;
$x += 5;  // $x = $x + 5; (adds 5 to $x)
echo $x;  // Output: 15
?>
  • Comparison Operators: Used to compare values.

    • == (equal), === (equal and same type), != (not equal), > (greater than), < (less than), >= (greater than or equal), <= (less than or equal)
<?php
$a = 5;
$b = 10;
var_dump($a == $b);  // Output: bool(false)
var_dump($a != $b);  // Output: bool(true)
var_dump($a < $b);   // Output: bool(true)
?>
  • Logical Operators: Used to perform logical operations (typically in conditional statements).

    • && (and), || (or), ! (not)
<?php
$x = true;
$y = false;

var_dump($x && $y);  // Output: bool(false)
var_dump($x || $y);  // Output: bool(true)
?>

Exercise for Day 2:

  1. Create a Script Using Variables and Operators:

    • Create variables to store your name, age, and favorite number.

    • Display them using echo.

    • Perform some basic arithmetic (e.g., find the difference between your age and your favorite number).

    • Use the var_dump() function to check the data types of these variables.

Example Code:

<?php
// Declare Variables
$name = "Alice";
$age = 30;
$favoriteNumber = 7;
$isStudent = false;

// Display Information
echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Favorite Number: " . $favoriteNumber . "<br>";
echo "Are you a student? " . ($isStudent ? "Yes" : "No") . "<br>";

// Perform Arithmetic Operation
$ageDifference = $age - $favoriteNumber;
echo "The difference between my age and my favorite number is: " . $ageDifference . "<br>";

// Inspect data types
var_dump($name);           // string
var_dump($age);            // int
var_dump($favoriteNumber); // int
var_dump($isStudent);      // bool
?>
  1. Expected Output:
Name: Alice
Age: 30
Favorite Number: 7
Are you a student? No
The difference between my age and my favorite number is: 23
string(5) "Alice"
int(30)
int(7)
bool(false)

Task Recap for Day 2:

  1. Learn Variables:

    • Create variables and assign values to them.

    • Display values with echo and check types using var_dump().

  2. Understand Data Types:

    • Get familiar with strings, integers, floats, booleans, arrays, and NULL.
  3. Use Operators:

    • Perform basic arithmetic and logical operations with PHP operators.

Goal for Day 2:

  • By the end of Day 2, you should be comfortable with PHP variables, data types, and operators. You’ll also be able to perform basic operations and display results on the web page.

Day 3 Task: Conditional Statements in PHP

Goals:

  • Learn how to use conditional statements (if, else, elseif, and switch) to control the flow of your program.

  • Understand logical operators and how to combine conditions.


Step-by-Step Tasks:

1. Using if, else, and elseif Statements

Conditional statements allow you to execute certain blocks of code based on whether a condition is true or false.

  • Basic if statement:

    • The if statement evaluates a condition and runs the code inside the block if the condition is true.
<?php
$age = 20;
if ($age >= 18) {
    echo "You are an adult.";
}
?>
  • Using else:

    • The else statement is used to execute a block of code if the condition is false.
<?php
$age = 16;
if ($age >= 18) {
    echo "You are an adult.";
} else {
    echo "You are a minor.";
}
?>
  • Using elseif:

    • The elseif statement lets you check multiple conditions in sequence.
<?php
$age = 18;
if ($age < 18) {
    echo "You are a minor.";
} elseif ($age == 18) {
    echo "You are just an adult.";
} else {
    echo "You are an adult.";
}
?>
  • Combining conditions:

    • You can combine multiple conditions using logical operators like && (and), || (or), and ! (not).
<?php
$age = 22;
$isStudent = true;

if ($age >= 18 && $isStudent) {
    echo "You are an adult and a student.";
} else {
    echo "You either are not an adult or not a student.";
}
?>

2. Using switch Statement

  • The switch statement is useful when you need to check multiple possible values for a variable. It’s a cleaner alternative to using multiple elseif statements.
<?php
$day = "Monday";

switch ($day) {
    case "Monday":
        echo "Today is Monday.";
        break;
    case "Tuesday":
        echo "Today is Tuesday.";
        break;
    case "Wednesday":
        echo "Today is Wednesday.";
        break;
    default:
        echo "Invalid day.";
}
?>
  • Break statement: The break statement ensures that the code exits the switch block once a match is found. Without it, the code will continue executing all the subsequent cases.

3. Logical Operators in Conditional Statements

  • Logical operators are used to combine multiple conditions.

    • AND (&&): Both conditions must be true.

    • OR (||): At least one condition must be true.

    • NOT (!): Reverses the condition (true becomes false, and false becomes true).

Examples:

<?php
$age = 25;
$isStudent = true;

// AND condition (both must be true)
if ($age >= 18 && $isStudent) {
    echo "You are an adult and a student.";
}

// OR condition (at least one must be true)
if ($age >= 18 || $isStudent) {
    echo "You are either an adult or a student.";
}

// NOT condition (reverses the condition)
if (!$isStudent) {
    echo "You are not a student.";
}
?>

Exercise for Day 3:

1. Check User's Age and Display Appropriate Message

Create a PHP script that takes a user’s age and displays one of the following messages:

  • If the user is under 18, display: "You are a minor."

  • If the user is 18, display: "You are just an adult."

  • If the user is over 18, display: "You are an adult."

You can use a simple variable for the age or get it dynamically via a form in future tasks.

<?php
$age = 16;  // Change this value to test different outcomes

if ($age < 18) {
    echo "You are a minor.";
} elseif ($age == 18) {
    echo "You are just an adult.";
} else {
    echo "You are an adult.";
}
?>

2. Use switch to Display Days of the Week

Write a script that uses the switch statement to display a message based on the day of the week.

For example:

  • If the day is "Monday", display: "Start of the week!"

  • If the day is "Friday", display: "Almost weekend!"

  • For any other day, display: "Keep going!"

<?php
$day = "Friday";  // Change this value to test different outcomes

switch ($day) {
    case "Monday":
        echo "Start of the week!";
        break;
    case "Friday":
        echo "Almost weekend!";
        break;
    default:
        echo "Keep going!";
}
?>

3. Check Multiple Conditions

Create a script that checks:

  • If the user is older than 18 and is a student, display: "Adult student."

  • If the user is younger than 18 or not a student, display: "You need to study."

<?php
$age = 20;
$isStudent = true;

if ($age > 18 && $isStudent) {
    echo "Adult student.";
} elseif ($age < 18 || !$isStudent) {
    echo "You need to study.";
}
?>

Task Recap for Day 3:

  1. Learn Conditional Statements:

    • Use if, else, elseif, and switch to control the flow of your program.

    • Combine conditions using logical operators (&&, ||, !).

  2. Practice with Real-life Examples:

    • Create scripts that respond to different conditions (e.g., age checks, days of the week).

Goal for Day 3:

  • By the end of Day 3, you should be able to use conditional statements to control the flow of your program based on user input or other conditions. You should also be comfortable using logical operators and switching between different cases using switch statements.

Sure! Let's walk through the process of building a simple one-page PHP website. This will be a basic site that includes:

  1. A header with a navigation menu.

  2. A form where users can submit their name.

  3. A dynamic PHP section that displays a personalized greeting based on the form input.

  4. Basic styling for the page using inline CSS.

File Structure:

  • index.php - The main PHP page where the form will be displayed and processed.

  • styles.css - A simple external CSS file for styling.


1. Create the HTML Form and PHP Logic (index.php)

Here’s a basic index.php file. It includes the form, PHP logic to handle form submissions, and displays a personalized greeting.

<?php
// PHP logic to handle the form data
$name = ""; // Initialize the variable

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if the form is submitted and process the input
    if (!empty($_POST['name'])) {
        $name = htmlspecialchars($_POST['name']); // Sanitize input
    } else {
        $name = "Guest"; // Default to "Guest" if no name is entered
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple PHP Website</title>
    <link rel="stylesheet" href="styles.css"> <!-- External CSS file -->
</head>
<body>

    <!-- Header with navigation -->
    <header>
        <h1>Welcome to My Simple PHP Website</h1>
        <nav>
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>
    </header>

    <!-- Main content area -->
    <main>
        <section>
            <h2>Hello, <?php echo $name; ?>!</h2> <!-- Display the personalized greeting -->

            <p>Welcome to my PHP website. Please enter your name below to be greeted!</p>

            <!-- Form to collect user's name -->
            <form action="index.php" method="POST">
                <input type="text" name="name" placeholder="Enter your name" value="<?php echo $name; ?>" required>
                <button type="submit">Submit</button>
            </form>
        </section>
    </main>

    <!-- Footer -->
    <footer>
        <p>&copy; <?php echo date("Y"); ?> My Simple PHP Website</p>
    </footer>

</body>
</html>

Explanation of index.php:

  1. PHP Logic (Greeting):

    • When the form is submitted, the PHP code checks if the name field is filled.

    • If a name is entered, it is sanitized using htmlspecialchars() to prevent XSS attacks.

    • If no name is entered, it defaults to "Guest."

    • The PHP block handles both the display of the greeting and the form submission logic.

  2. HTML Structure:

    • The form uses POST to submit the data back to index.php.

    • The greeting (displayed within the <h2> tag) is dynamically updated based on the form submission using PHP.

    • The <input> value is pre-filled with the user's input (or "Guest" by default).

  3. Navigation Menu:

    • A simple unordered list (<ul>) serves as the navigation menu, although it's not linked to any pages since this is a one-page site.
  4. Footer:

    • The footer dynamically displays the current year using date("Y").

2. Create the External CSS File (styles.css)

Here's a simple CSS file (styles.css) to add some basic styling to the page.

/* General body styling */
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f4f4f9;
    color: #333;
}

/* Header styling */
header {
    background-color: #4CAF50;
    color: white;
    padding: 20px;
    text-align: center;
}

header h1 {
    margin: 0;
    font-size: 2em;
}

nav ul {
    list-style: none;
    padding: 0;
}

nav ul li {
    display: inline;
    margin: 0 15px;
}

nav ul li a {
    color: white;
    text-decoration: none;
    font-weight: bold;
}

nav ul li a:hover {
    text-decoration: underline;
}

/* Main content section */
main {
    padding: 20px;
    text-align: center;
}

/* Form styling */
form {
    margin-top: 20px;
}

form input[type="text"] {
    padding: 10px;
    font-size: 1em;
    width: 250px;
    margin-right: 10px;
    border: 2px solid #ddd;
    border-radius: 5px;
}

form button {
    padding: 10px 15px;
    font-size: 1em;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

form button:hover {
    background-color: #45a049;
}

/* Footer styling */
footer {
    background-color: #333;
    color: white;
    padding: 10px;
    text-align: center;
    position: fixed;
    width: 100%;
    bottom: 0;
}

Explanation of styles.css:

  1. General Styling:

    • The body is given a light background color (#f4f4f9) with some padding and margin resets.

    • A simple font-family (Arial) is used for readability.

  2. Header Styling:

    • The header has a green background (#4CAF50) with white text.

    • The navigation menu is styled with inline list items (<li>) and white, bold links.

  3. Main Section (Content) Styling:

    • The content area is centered with some padding.

    • The form fields are styled to have some space, padding, and borders to make them look nice.

  4. Footer Styling:

    • The footer has a dark background (#333) and white text, and it’s fixed at the bottom of the page.

3. Folder Structure

Make sure your folder structure looks like this:

/my-php-site
    ├── index.php
    └── styles.css

4. Testing Your Site

To run this website:

  1. Make sure you have a PHP development environment set up (like XAMPP, MAMP, or a live server with PHP support).

  2. Place both index.php and styles.css in the same directory.

  3. Open index.php in your browser, and test the form by submitting your name.


Conclusion

This is a simple one-page PHP website that:

  • Greets the user by name (or as "Guest" if no name is provided).

  • Has a basic navigation menu (though it's non-functional in this case).

  • Includes a form to collect input and dynamically display a greeting.

  • Has some basic styling with external CSS for a neat, professional appearance.

You can easily extend this by adding more features, like handling multiple form inputs, integrating a database, or using JavaScript for interactive elements!