Introduction to PHP and Its Importance for WordPress
Learning Objectives
- Understand PHP basics
- Set up PHP development environment
- Write server-side code
- Prepare for WordPress development
Welcome to PHP!
Today we begin our journey into the world of PHP, the programming language that powers WordPress and approximately 77% of websites that use a server-side language. This session will provide you with a fundamental understanding of what PHP is, why it was created, how it functions, and why it's crucial for WordPress development.
What is PHP?
PHP (PHP: Hypertext Preprocessor) is a server-side scripting language designed primarily for web development. Created by Rasmus Lerdorf in 1994, PHP has evolved from a simple set of Common Gateway Interface (CGI) binaries to a full-featured programming language.
Think of PHP as a chef in a restaurant kitchen. The chef (PHP) works behind the scenes, receiving orders (requests) from customers (users), preparing the meals (processing data), and sending out beautifully plated dishes (HTML) to be served to the customers. The customers never see the kitchen or the preparation process; they only enjoy the final product.
Key Characteristics of PHP
- Server-Side Execution: Unlike JavaScript which runs in the browser, PHP code executes on the web server.
- Dynamic Content Generation: PHP can generate dynamic page content based on various conditions.
- Database Integration: PHP works seamlessly with databases like MySQL to store and retrieve data.
- Cross-Platform: PHP runs on various platforms (Windows, Linux, Unix, macOS).
- Open Source: PHP is free to use and has a large community of developers.
- Versatile: PHP can be embedded directly into HTML code.
To visualize PHP's place in web development:
PHP Syntax Basics
PHP code is enclosed within special start and end tags: <?php and ?>. These tags tell the PHP interpreter which parts of the document to interpret as PHP code.
Basic PHP Script
<!DOCTYPE html>
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<h1>Welcome to PHP!</h1>
<?php
// This is a PHP comment
echo "Hello, World!"; // Outputs: Hello, World!
$name = "Student"; // Variable declaration
echo "<p>Hello, " . $name . "!</p>"; // Concatenation
// PHP can also include HTML directly
echo "<p>Today's date is: " . date("Y-m-d") . "</p>";
?>
<p>This is regular HTML again.</p>
</body>
</html>
In this example:
- PHP begins with
<?phpand ends with?> - The
echostatement outputs text - Variables start with a
$symbol - Statements end with a semicolon
; - PHP can generate HTML content dynamically
Variables and Data Types in PHP
PHP is a loosely typed language, meaning you don't need to declare the data type when creating a variable. PHP automatically converts the variable to the correct data type, depending on its context.
<?php
// String
$name = "John Doe";
// Integer
$age = 30;
// Float/Double
$height = 5.11;
// Boolean
$is_student = true;
// Array
$hobbies = array("reading", "coding", "hiking");
// Modern array syntax (PHP 5.4+)
$skills = ["HTML", "CSS", "JavaScript", "PHP"];
// Null
$certificate = null;
// Object
class Person {
public $name;
public function setName($name) {
$this->name = $name;
}
}
$student = new Person();
$student->setName("Jane");
// Checking variable type
echo gettype($name); // Outputs: string
echo gettype($age); // Outputs: integer
echo gettype($hobbies); // Outputs: array
?>
Key Features of PHP for Web Development
Form Processing
One of PHP's most common uses is processing form data. Here's a simple example:
HTML Form:
<!-- contact.html -->
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Send Message</button>
</form>
PHP Processing Script:
<?php
// process.php
// Access form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Validate data (basic example)
if (empty($name) || empty($email) || empty($message)) {
echo "Please fill all required fields.";
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
exit;
}
// Process the data (here we'll just echo it)
echo "<h2>Form Submission Received</h2>";
echo "<p><strong>Name:</strong> " . htmlspecialchars($name) . "</p>";
echo "<p><strong>Email:</strong> " . htmlspecialchars($email) . "</p>";
echo "<p><strong>Message:</strong> " . htmlspecialchars($message) . "</p>";
// In a real application, you might:
// - Send an email
// - Store in database
// - Redirect user to a thank you page
?>
Think of PHP form processing as a mail sorting facility. The form is like an envelope with information that the user fills out. When submitted, PHP acts as the sorter, opening the envelope, reading the contents, validating the information, and then directing it to the appropriate destination (database, email, etc.).
Database Connectivity
PHP has built-in functions to connect to and manipulate databases. MySQL is the most common database used with PHP.
<?php
// Database connection parameters
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_website";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute a SQL query
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
// Process the results
if ($result->num_rows > 0) {
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["email"] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>
PHP's relationship with a database is like a librarian interacting with a vast library. PHP (the librarian) knows how to navigate the database (library), find specific information (books), organize it, add new entries, update existing ones, or remove outdated records. The librarian brings only the requested books to the patron, just as PHP retrieves only the requested data to show to the user.
Session Management
PHP makes it easy to manage user sessions, which is crucial for creating personalized user experiences and maintaining state across page loads.
<?php
// Start a new session or resume an existing one
session_start();
// Store data in the session
$_SESSION['username'] = "john_doe";
$_SESSION['user_id'] = 123;
$_SESSION['is_logged_in'] = true;
// Accessing session data on another page
// (After calling session_start() on that page)
if (isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] === true) {
echo "Welcome back, " . $_SESSION['username'] . "!";
} else {
echo "Please log in to continue.";
}
// Removing a specific session variable
unset($_SESSION['username']);
// Destroying the entire session
session_destroy();
?>
Session management in PHP is like a wristband at an amusement park. When you first arrive (log in), you get a wristband (session ID) that identifies you. As you move from ride to ride (page to page), the park staff can check your wristband to verify who you are and what rides you're allowed to access, without you having to show your ID each time. When you leave the park (log out), the wristband is removed (session destroyed).
Why PHP is Essential for WordPress
WordPress, powering approximately 42% of all websites on the internet, is built entirely on PHP. Understanding this relationship is crucial for anyone looking to work with WordPress professionally.
Core Architecture
WordPress's core files are written in PHP. These files handle everything from user authentication to content management and database operations. When you navigate to a WordPress site, PHP processes the request, retrieves the necessary data from the database, and generates the HTML that is sent to the browser.
Think of WordPress as a sophisticated house built on a PHP foundation. The foundation (PHP) provides the structural support and utilities needed for the house to function, while the house itself (WordPress) provides a beautiful, functional living space that the homeowner (website owner) can customize to their liking.
Theme Development
WordPress themes determine how a site looks and feels. They are built primarily with PHP, HTML, CSS, and JavaScript. PHP is used to:
- Retrieve content from the database
- Implement WordPress template hierarchy
- Generate dynamic content based on user actions or site settings
- Interface with WordPress core functions
<!-- Example of PHP in a WordPress theme file (header.php) -->
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php wp_title('|', true, 'right'); ?></title>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<header class="site-header">
<div class="site-branding">
<h1 class="site-title">
<a href="<?php echo esc_url(home_url('/')); ?>">
<?php bloginfo('name'); ?>
</a>
</h1>
<p class="site-description"><?php bloginfo('description'); ?></p>
</div>
<nav class="main-navigation">
<?php
wp_nav_menu(array(
'theme_location' => 'primary',
'menu_class' => 'primary-menu',
));
?>
</nav>
</header>
In this example, PHP functions like language_attributes(), bloginfo(), and wp_nav_menu() are used to dynamically generate parts of the HTML document based on the WordPress site's settings and content.
Plugin Development
WordPress plugins extend the platform's functionality. They are written primarily in PHP and interact with WordPress through its Plugin API, hooks, and filters.
<?php
/*
Plugin Name: Simple Contact Form
Description: Adds a basic contact form to your WordPress site
Version: 1.0
Author: Your Name
*/
// Don't allow direct access to the plugin file
if (!defined('ABSPATH')) {
exit;
}
// Add a shortcode for the contact form
function simple_contact_form_shortcode() {
$form_html = '
<form method="post" action="" class="simple-contact-form">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="scf_name" id="name" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="scf_email" id="email" required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea name="scf_message" id="message" required></textarea>
</div>
<input type="hidden" name="scf_submitted" value="1">
<button type="submit">Send Message</button>
</form>';
return $form_html;
}
add_shortcode('contact_form', 'simple_contact_form_shortcode');
// Process form submission
function simple_contact_form_process() {
if (isset($_POST['scf_submitted']) && $_POST['scf_submitted'] == 1) {
$name = sanitize_text_field($_POST['scf_name']);
$email = sanitize_email($_POST['scf_email']);
$message = sanitize_textarea_field($_POST['scf_message']);
// Email to admin
$to = get_option('admin_email');
$subject = 'New Contact Form Submission';
$body = "Name: $name\n\nEmail: $email\n\nMessage: $message";
$headers = "From: $name <$email>";
wp_mail($to, $subject, $body, $headers);
// Redirect to same page with query parameter
wp_redirect(add_query_arg('scf_sent', '1', wp_get_referer()));
exit;
}
}
add_action('init', 'simple_contact_form_process');
// Display thank you message
function simple_contact_form_message() {
if (isset($_GET['scf_sent']) && $_GET['scf_sent'] == '1') {
echo '<div class="scf-success-message">Thank you for your message!</div>';
}
}
add_action('wp_footer', 'simple_contact_form_message');
?>
This simple plugin demonstrates how PHP is used to create WordPress plugins. It defines a shortcode that users can insert into their posts or pages, processes form submissions, and displays a thank you message. All of this functionality is implemented using PHP and WordPress's built-in functions and hooks.
Plugins are like appliances and tools added to our WordPress house. Each plugin (appliance) performs a specific function, and they all connect to the home's electrical system (WordPress hooks and filters) to integrate with the overall structure. PHP is the electrical wiring that allows these appliances to work and communicate with the rest of the house.
Setting Up a Local PHP Environment
To develop PHP applications locally, you need a web server, PHP, and a database server. The most common setups are:
PHP Best Practices
Security
Security is a critical concern in PHP development. Common security practices include:
- Input Validation: Always validate and sanitize user input
- Prepared Statements: Use prepared statements for database queries to prevent SQL injection
- Output Escaping: Escape output to prevent XSS attacks
- Password Hashing: Use PHP's password_hash() and password_verify() functions
- HTTPS: Encourage the use of HTTPS for all websites
<?php
// Bad practice - vulnerable to SQL injection
$username = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
// Good practice - using prepared statements
$username = $_POST['username'];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
// Bad practice - vulnerable to XSS
echo "Welcome, " . $_GET['name'];
// Good practice - escaping output
echo "Welcome, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
// Bad practice - storing plain text passwords
$password = $_POST['password'];
$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
// Good practice - hashing passwords
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $hashed_password);
$stmt->execute();
?>
Code Organization
Well-organized PHP code is easier to maintain and debug:
- Separation of Concerns: Separate business logic, data access, and presentation
- Object-Oriented Programming: Use classes and objects to structure your code
- Consistent Naming Conventions: Follow established naming conventions
- Comments and Documentation: Document your code thoroughly
Performance
Optimizing PHP performance is important for creating responsive web applications:
- Caching: Use caching mechanisms to reduce database queries and computational overhead
- Efficient Database Queries: Optimize database queries and use indexes
- Code Optimization: Write efficient code and avoid unnecessary operations
- Use Latest PHP Version: Newer versions of PHP include performance improvements
What's Next?
In the next sessions, we will dive deeper into PHP programming, covering:
- Control structures (if/else, switches, loops)
- Functions and includes
- Object-oriented PHP
- Working with forms and data
- File handling and uploading
- Error handling and debugging
- MySQL database operations
Homework Assignment
Create a simple PHP script that:
- Creates variables of different data types (string, integer, float, boolean, array)
- Demonstrates basic string operations (concatenation, length, substring)
- Shows examples of arithmetic operations
- Outputs the current date and time using PHP's date function
- Creates a simple HTML form and displays the submitted data
Submit your script as a .php file to the course learning management system.