Introduction:
Explore the fundamentals of PHP if statements and their application in building a secure login system. This lesson provides hands-on examples and best practices for conditional statements in PHP, along with a practical demonstration of creating a login page. Gain insights into user authentication, form handling, and enhancing security in PHP web development.
In PHP, if statements are used to conditionally execute code based on whether a specified condition evaluates to true or false.
The basic syntax of an if statement looks like this:
if (condition) { // code to be executed if the condition is true }
Here’s a simple example:
<?php $number = 10; if ($number > 5) { echo "The number is greater than 5."; } ?>
In this example, the condition is $number > 5. If the value of $number is indeed greater than 5, the code inside the curly braces will be executed, and the message “The number is greater than 5.” will be printed.
You can also use an else statement to specify code that should be executed when the condition is false:
<?php $number = 3; if ($number > 5) { echo "The number is greater than 5."; } else { echo "The number is not greater than 5."; } ?>
In this case, since $number is not greater than 5, the code inside the else block will be executed, and the message “The number is not greater than 5.” will be printed.
You can also use elseif to check multiple conditions:
<?php $number = 5; if ($number > 5) { echo "The number is greater than 5."; } elseif ($number < 5) { echo "The number is less than 5."; } else { echo "The number is equal to 5."; } ?>
Here, the script checks if $number is greater than 5, less than 5, or equal to 5, and prints the corresponding message accordingly.
Remember to replace “condition” with the actual expression you want to evaluate in your if statement. The code inside the curly braces will be executed only if the condition is true.
complete example in html with explanation
Below is a complete example of a simple HTML page with embedded PHP code using if statements.
This example demonstrates a basic login form that checks the entered credentials:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Page</title> </head> <body> <?php // Sample user credentials $correctUsername = 'user123'; $correctPassword = 'pass123'; // Check if the form is submitted if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Retrieve user input from the form $enteredUsername = $_POST['username']; $enteredPassword = $_POST['password']; // Check if the entered credentials match the correct ones if ($enteredUsername === $correctUsername && $enteredPassword === $correctPassword) { $message = "Login successful!"; } else { $message = "Invalid username or password. Please try again."; } } ?> <h2>Login Form</h2> <?php // Display the login result message, if available if (isset($message)) { echo "<p>$message</p>"; } ?> <form method="post" action=""> <label for="username">Username:</label> <input type="text" id="username" name="username" required><br> <label for="password">Password:</label> <input type="password" id="password" name="password" required><br> <button type="submit">Login</button> </form> </body> </html>
Explanation:
This example demonstrates how PHP if statements can be used in the context of an HTML page, especially for handling form submissions and displaying messages based on conditions.
Let’s create a simple PHP application that simulates user authentication. This application will have a login page and a dashboard page. The login credentials are hardcoded for simplicity.
File Structure:
index.php: The main login page.
dashboard.php: The dashboard page to be displayed upon successful login.
index.php:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Page</title> </head> <body> <?php // Sample user credentials $correctUsername = 'user123'; $correctPassword = 'pass123'; // Check if the form is submitted if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Retrieve user input from the form $enteredUsername = $_POST['username']; $enteredPassword = $_POST['password']; // Check if the entered credentials match the correct ones if ($enteredUsername === $correctUsername && $enteredPassword === $correctPassword) { // Redirect to the dashboard upon successful login header('Location: dashboard.php'); exit(); } else { $message = "Invalid username or password. Please try again."; } } ?> <h2>Login Form</h2> <?php // Display the login result message, if available if (isset($message)) { echo "<p style='color: red;'>$message</p>"; } ?> <form method="post" action=""> <label for="username">Username:</label> <input type="text" id="username" name="username" required><br> <label for="password">Password:</label> <input type="password" id="password" name="password" required><br> <button type="submit">Login</button> </form> </body> </html>
dashboard.php:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dashboard</title> </head> <body> <h2>Welcome to the Dashboard!</h2> <p>This is a secure area accessible only to authenticated users.</p> <a href="index.php">Logout</a> </body> </html>
In this example:
Here’s a single web page containing both the login page and the dashboard. Copy and paste the code into a single PHP file (e.g., index.php):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Page</title> </head> <body> <?php // Sample user credentials $correctUsername = 'user123'; $correctPassword = 'pass123'; // Check if the form is submitted if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Retrieve user input from the form $enteredUsername = $_POST['username']; $enteredPassword = $_POST['password']; // Check if the entered credentials match the correct ones if ($enteredUsername === $correctUsername && $enteredPassword === $correctPassword) { // Redirect to the dashboard upon successful login header('Location: index.php?page=dashboard'); exit(); } else { $message = "Invalid username or password. Please try again."; } } ?> <?php if (!isset($_GET['page']) || $_GET['page'] !== 'dashboard') { ?> <h2>Login Form</h2> <?php // Display the login result message, if available if (isset($message)) { echo "<p style='color: red;'>$message</p>"; } ?> <form method="post" action=""> <label for="username">Username:</label> <input type="text" id="username" name="username" required><br> <label for="password">Password:</label> <input type="password" id="password" name="password" required><br> <button type="submit">Login</button> </form> <?php } else { ?> <h2>Welcome to the Dashboard!</h2> <p>This is a secure area accessible only to authenticated users.</p> <a href="index.php">Logout</a> <?php } ?> </body> </html>
This single PHP file includes both the login form and the dashboard content. The $_GET[‘page’] variable is used to determine whether to display the login form or the dashboard content. The header(‘Location: index.php?page=dashboard’) line redirects the user to the dashboard upon successful login. The “Logout” link on the dashboard links back to the login form.
Explanation
Let’s go through the code and provide an explanation for each part:
HTML Structure:
The document starts with the usual HTML structure, including the <!DOCTYPE html> declaration, the <html>, <head>, and <body> tags.
PHP Code Block for Authentication:
Conditional Display of Login Form and Dashboard:
This single PHP file acts as both the login page and the dashboard. It dynamically switches between displaying the login form and the dashboard content based on the presence of the page parameter in the URL. The redirection to the dashboard after a successful login is done using the header(‘Location: index.php?page=dashboard’) statement.
Here’s a quiz with 15 questions related to PHP if statements and the login page example.
A. Looping
B. Conditional execution
C. Defining functions
D. Variable declaration
A. Current date and time
B. Server software version
C. Request method (e.g., GET or POST)
D. User agent information
A. Use $_REQUEST for form data
B. Hardcode all user credentials
C. Validate and sanitize user input
D. Display raw error messages
A. Prints a header message
B. Redirects the user to another page
C. Sets a cookie
D. Includes an external file
A. isset()
B. empty()
C. isset() && !empty()
D. Both A and B
A. Terminates the PHP script
B. Echoes a message to the user
C. Redirects the user
D. Creates an infinite loop
A. Using switch statement
B. Using nested if statements
C. Using only if statements
D. Using if, elseif, and else statements
A. Specifies the HTML version
B. Declares the document as an HTML5 document
C. Defines the character set
D. Comments out HTML code
A. $form->input()
B. $_GET[‘input’]
C. $_POST[‘input’]
D. Both B and C
A. To display error messages
B. To check if the form is submitted
C. To simulate correct user credentials
D. To set the title of the HTML page
A. echo
B. print
C. display
D. output
A. Specifies the field as mandatory
B. Limits the input length
C. Validates the input format
D. Disables the input field
A. Store passwords in plain text
B. Use a secure hash algorithm for passwords
C. Email passwords to users
D. Display detailed login error messages
A. Specifies the form’s action URL
B. Sets the form’s encoding type
C. Defines the HTTP method for form submission
D. Disables form submission
A. Includes an external file
B. Redirects the user to the dashboard page
C. Sets a cookie
D. Outputs a header message
Answers:
B, 2. C, 3. C, 4. B, 5. C, 6. A, 7. D, 8. B, 9. D, 10. C, 11. A, 12. A, 13. B, 14. C, 15. B