Consider you have a login form having password, login and cancel button.
Now write a PHP
program for implementing login form. The login form should redirect to home php
successful login and cancel should clear form field value upon submission.
To implement a login form using PHP, we will create two separate files:
1. [Link]: This will display the login form with a "Login" and "Cancel" button.
2. [Link]: This will display a welcome message after a successful login.
The login functionality will be simple: if the user enters the correct password, they will be
redirected to [Link]. If they press "Cancel", the form fields will be cleared.
1. [Link]
<?php
// Start a session to track login status
session_start();
// Check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['login'])) {
// Dummy login credentials (for demonstration)
$correct_password = 'password123';
// Get the entered password
$password = $_POST['password'];
// Validate the password
if ($password === $correct_password) {
// Set session variable for successful login
$_SESSION['logged_in'] = true;
// Redirect to [Link] after successful login
header('Location: [Link]');
exit();
} else {
$error = "Invalid password. Please try again.";
if (isset($_POST['cancel'])) {
// Clear the form field values
$_POST['password'] = '';
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<!-- Display error message if the password is wrong -->
<?php if (isset($error)): ?>
<p style="color:red;"><?php echo $error; ?></p>
<?php endif; ?>
<!-- Login form -->
<form method="post" action="">
<label for="password">Password:</label>
<input type="password" id="password" name="password" value="<?php echo
isset($_POST['password']) ? htmlspecialchars($_POST['password']) : ''; ?>"><br><br>
<input type="submit" name="login" value="Login">
<input type="submit" name="cancel" value="Cancel">
</form>
</body>
</html>
3. [Link]
4. <?php
5. // Start session to check login status
6. session_start();
7.
8. // Check if the user is logged in, if not redirect to [Link]
9. if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
10. header('Location: [Link]');
11. exit();
12. }
13. ?>
14.
15. <!DOCTYPE html>
16. <html>
17. <head>
18. <title>Home Page</title>
19. </head>
20. <body>
21. <h2>Welcome to the Home Page</h2>
22. <p>You have successfully logged in!</p>
23. <a href="[Link]">Logout</a>
24. </body>
25. </html>
[Link] a PHP program to parse a CSV file (web technology)
<?php
// Path to the CSV file
$csvFile = '[Link]';
// Open the file in read mode
if (($handle = fopen($csvFile, 'r')) !== false) {
echo "<table border='1'>";
// Fetch each row of the CSV file
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
echo "<tr>";
// Loop through the fields in each row and display them in table cells
foreach ($data as $field) {
echo "<td>" . htmlspecialchars($field) . "</td>";
}
echo "</tr>";
}
echo "</table>";
// Close the file
fclose($handle);
} else {
// Handle error if file cannot be opened
echo "Error: Unable to open the CSV file.";
}
?>
[Link] a PHP program to connect data base and retrieve data from a table and
display in a page (in web)
To connect to a database and retrieve data from a table in PHP, you'll typically use either
MySQLi (for MySQL databases) or PDO. Below is an example of how to do this using
MySQLi.
Steps:
1. Create a Database: First, you need a MySQL database.
CREATE DATABASE sample_db;
[Link] a Table: Then, create a table (e.g., users table) with some sample data.
USE sample_db;
CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
age INT NOT NULL
);
INSERT INTO users (name, email, age) VALUES
('John Doe', 'john@[Link]', 30),
('Jane Smith', 'jane@[Link]', 25),
('David Miller', 'david@[Link]', 40);
1. PHP Program to Connect to Database and Retrieve Data:
PHP Program (fetch_data.php):
<?php
// Database connection settings
$servername = "localhost";
$username = "root"; // Change this to your MySQL username
$password = ""; // Change this to your MySQL password
$dbname = "sample_db"; // Your database name
// Create connection using MySQLi
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to retrieve data from the 'users' table
$sql = "SELECT id, name, email, age FROM users";
$result = $conn->query($sql);
// Check if there are results
if ($result->num_rows > 0) {
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>";
// Output data for each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row["id"] . "</td>
<td>" . htmlspecialchars($row["name"]) . "</td>
<td>" . htmlspecialchars($row["email"]) . "</td>
<td>" . $row["age"] . "</td>
</tr>";
}
echo "</table>";
} else {
echo "No results found.";
}
// Close the connection
$conn->close();
?>
[Link] a PHP program to illustrate string pattern using regular expression.
PHP Program to Illustrate String Pattern Using Regular Expression
This example demonstrates checking if an email address is in the correct format using a regular
expression.
<?php
// Define a string to test
$string = "[Link]@[Link]";
// Define the pattern for a valid email using regular expression
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
// Use preg_match() to check if the string matches the pattern
if (preg_match($pattern, $string)) {
echo "The string '$string' is a valid email address.";
} else {
echo "The string '$string' is NOT a valid email address.";
}
?>
[Link] a PHP program to extract sunset of any array using array slice() function.
The array_slice() function in PHP allows you to extract a portion of an array. To simulate
extracting the "sunset" of an array, we can interpret it as retrieving the last few elements of an
array, much like how the sunset is at the end of the day.
Here’s a PHP program to extract the "sunset" (last elements) of any array using the
array_slice() function.
PHP Program to Extract the "Sunset" of an Array
<?php
// Define an array
$array = array("Morning", "Noon", "Afternoon", "Evening", "Sunset", "Night");
// Number of elements to extract as the "sunset"
$sunset_elements_count = 2; // You can adjust this number based on what you
define as "sunset"
// Extract the last 'n' elements from the array using array_slice()
// Use negative offset to get the last part of the array
$sunset = array_slice($array, -$sunset_elements_count);
// Display the original array
echo "Original Array: <br>";
print_r($array);
echo "<br><br>";
// Display the "sunset" of the array
echo "Sunset (last $sunset_elements_count elements) of the array: <br>";
print_r($sunset);
?>
[Link] a PHP program that will read two input string in variable fname and iname
and display concatenation of fname and iname
PHP Program to Concatenate fname and lname
<!DOCTYPE html>
<html>
<head>
<title>Concatenate Two Strings</title>
</head>
<body>
<!-- HTML form to take user input -->
<form method="post" action="">
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Concatenate">
</form>
<?php
// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get the input values from the form
$fname = $_POST['fname'];
$lname = $_POST['lname'];
// Concatenate the two strings
$full_name = $fname . " " . $lname;
// Display the concatenated result
echo "<h3>Full Name: " . htmlspecialchars($full_name) . "</h3>";
}
?>
</body>
</html>
[Link] is error handler? Write a PHP program to show use of error handler to
format and print errors
An Error Handler in PHP is a user-defined function that handles errors when they occur in a
script. By default, PHP provides its own error handling system, but developers can override this
and define their custom error handling function using set_error_handler().
A custom error handler allows you to:
• Format error messages.
• Log errors.
• Display user-friendly messages.
• Control what actions should happen when an error occurs.
PHP Error Levels:
PHP categorizes errors into different levels, such as:
• E_NOTICE: Notices that don't halt the script (like using an undefined variable).
• E_WARNING: Warnings that don't halt the script.
• E_ERROR: Fatal runtime errors that halt the script.
PHP Program: Using a Custom Error Handler
The following PHP program demonstrates the use of a custom error handler to format and print
errors:
<?php
// Custom error handler function
function customErrorHandler($errno, $errstr, $errfile, $errline) {
echo "<h3>Custom Error:</h3>";
echo "<b>Error Number:</b> [$errno] <br>";
echo "<b>Error Message:</b> $errstr <br>";
echo "<b>Error in File:</b> $errfile <br>";
echo "<b>On Line:</b> $errline <br>";
echo "<hr>";
}
// Set the custom error handler
set_error_handler("customErrorHandler");
// Trigger some errors for demonstration
// Undefined variable (E_NOTICE level error)
echo $undefined_variable;
// Division by zero (Warning level error)
echo 10 / 0;
// Manually trigger an error (User-defined error)
trigger_error("A custom user error has occurred!", E_USER_WARNING);
?>