What is PHP?

PHP (which stands for Hypertext Preprocessor) is a server-side scripting language that is primarily used for web development. It allows developers to create dynamic web pages, manage forms, interact with databases, and handle user input. PHP is embedded directly within HTML and runs on the server, meaning it generates content that is sent to the user’s browser as plain HTML.

PHP is widely used to build websites and web applications. Some of the world’s most popular content management systems (CMS) like WordPress, Drupal, and Joomla are built with PHP.


Key Features of PHP

  1. Server-Side Language: PHP is executed on the server. This means that the code you write runs on a web server, and only the resulting HTML (or other output) is sent to the browser.
    • Example: If you have a PHP file on your server like example.php, when someone accesses that file, PHP processes the code and sends the output to the user’s browser.
  2. Dynamic Content Generation: With PHP, you can generate dynamic content based on user input, databases, session data, etc. This makes websites interactive and personalized.
  3. Ease of Integration: PHP integrates well with other web technologies like HTML, CSS, JavaScript, and databases like MySQL, which makes it highly versatile in web development.
  4. Database Connectivity: PHP can connect to various databases such as MySQL, PostgreSQL, or SQLite. This is one of the reasons why PHP is used to build data-driven websites.
  5. Open Source: PHP is free to use and has an active community of developers who continuously improve and expand its capabilities.
  6. Cross-Platform: PHP is platform-independent, meaning it can run on different operating systems, such as Windows, Linux, and macOS.

Basic PHP Syntax

PHP is embedded inside HTML and starts with <?php and ends with ?>. Anything between these tags is interpreted as PHP code.

Example: A Basic PHP Script

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Example</title>
</head>
<body>
    <h1>Welcome to my PHP page!</h1>
    
    <?php
        echo "Hello, World!"; // Outputting a simple string
    ?>

</body>
</html>

Key Points:

  • The <?php ... ?> tags tell the server to execute PHP code.
  • The echo command is used to output content (usually HTML) to the browser.

Variables in PHP

In PHP, variables are used to store values. They start with a dollar sign ($) followed by the variable name.

Example:

<?php
$name = "Alice"; // A string variable
$age = 25; // An integer variable

echo "Hello, my name is $name and I am $age years old.";
?>
  • PHP variables can store different types of data such as strings, integers, floats, arrays, and objects.
  • PHP is loosely typed, meaning you don’t have to declare the type of the variable before using it. PHP will automatically detect the data type.

Control Structures in PHP

PHP provides various control structures like if statements, loops, and switch to control the flow of the program.

If-Else Statement

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

For Loop

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

While Loop

<?php
$count = 1;
while ($count <= 5) {
    echo "Count: $count<br>";
    $count++;
}
?>

Functions in PHP

A function is a block of code that performs a specific task and can be reused throughout your program.

Example:

<?php
// Define a function
function greet($name) {
    echo "Hello, $name!";
}

// Call the function
greet("Alice");  // Outputs: Hello, Alice!
?>
  • Functions in PHP are defined using the function keyword.
  • You can pass data to the function using parameters (like $name in the example above).

Handling Forms in PHP

PHP is commonly used to handle forms on websites. For example, you might have a contact form where users can input their data, and PHP can process that data once the form is submitted.

Example: Handling a Simple Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Form Example</title>
</head>
<body>
    <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        Name: <input type="text" name="name"><br><br>
        <input type="submit" value="Submit">
    </form>

    <?php
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            // Collect and sanitize input
            $name = htmlspecialchars($_POST['name']);
            echo "Hello, $name!";
        }
    ?>
</body>
</html>

Explanation:

  • $_SERVER['PHP_SELF']: Refers to the current PHP file, allowing the form to submit and display results on the same page.
  • $_POST: Used to collect data from a form submitted via the POST method.
  • htmlspecialchars(): Prevents XSS (Cross-Site Scripting) attacks by converting special characters to HTML entities.

PHP and Databases (MySQL Example)

PHP is often used with databases to store and retrieve data. A common combination is PHP with MySQL for data storage.

Example: Connecting to a MySQL Database

<?php
// Create connection
$conn = new mysqli("localhost", "username", "password", "database_name");

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";

// Close the connection
$conn->close();
?>

Explanation:

  • new mysqli(): Creates a connection to the MySQL database.
  • Always ensure to check if the connection was successful before interacting with the database.

PHP Conclusion

PHP is a powerful and flexible language used primarily for web development. It’s fast, easy to learn, and integrates well with various databases and technologies. Whether you’re building simple scripts or large, complex web applications, PHP is a great tool to have in your development toolkit.

In summary, PHP:

  • Is embedded within HTML to create dynamic content.
  • Supports object-oriented programming and procedural programming.
  • Has robust support for handling forms, sessions, and interacting with databases.
  • Works on most web servers and is widely supported.

PHP remains a popular choice for server-side scripting due to its simplicity, performance, and the fact that it’s open-source. So if you’re diving into web development, PHP is a great language to start with!