0% found this document useful (0 votes)
9 views6 pages

Cheatsheeet Web

PHP (Hypertext Preprocessor) is an open-source server-side scripting language primarily used for web development. It is popular due to its open-source nature, platform independence, ease of learning, database integration capabilities, and strong community support. The document also includes examples of PHP code for form validation, user authentication, session management, and error handling.

Uploaded by

Abhishek Negi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views6 pages

Cheatsheeet Web

PHP (Hypertext Preprocessor) is an open-source server-side scripting language primarily used for web development. It is popular due to its open-source nature, platform independence, ease of learning, database integration capabilities, and strong community support. The document also includes examples of PHP code for form validation, user authentication, session management, and error handling.

Uploaded by

Abhishek Negi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Q. What is PHP? Mention 5 reasons why PHP is so popular.

Display an HTML form to the user


containing Name, Age, and Gender. Write a PHP program to extract these values and perform server-
side validation.

What is PHP? PHP (Hypertext Preprocessor) is an open-source server-side scripting language


designed primarily for web development but also used as a general-purpose programming language. It
is embedded within HTML and is especially suited for creating dynamic and interactive websites.

5 Reasons Why PHP is So Popular:

1. Open Source and Free: PHP is free to use and has a strong open-source community that
continuously supports its development.

2. Platform Independent: PHP runs on various platforms (Windows, Linux, macOS) and is
compatible with almost all servers (Apache, Nginx, IIS).

3. Easy to Learn and Use: PHP has a simple syntax, making it easy for beginners to learn and
implement.

4. Database Integration: PHP supports a wide range of databases like MySQL, PostgreSQL,
Oracle, etc., which makes it powerful for backend development.

5. Large Ecosystem and Community Support: A vast community offers extensive documentation,
frameworks (like Laravel, CodeIgniter), and ready-to-use libraries.

<!DOCTYPE html>
<?php
<html>
if ($_SERVER["REQUEST_METHOD"] == "POST")
<head>
{
<title>PHP Form Validation</title>
$name = trim($_POST["name"]);
</head>
$age = trim($_POST["age"]);
<body>
$gender = trim($_POST["gender"]);
<form action="process.php" method="POST">
$errors = [];
Name: <input type="text" name="name"><br><br>
// Server-side validations
Age: <input type="number" name="age"><br><br>
if (empty($name) || empty($age) ||
Gender:
empty($gender)) {
<select name="gender">
$errors[] = "All fields are mandatory.";
<option value="">Select</option>
}
<option value="Male">Male</option>
if (!is_numeric($age) || $age < 0) {
<option value="Female">Female</option>
$errors[] = "Age must be a non-negative
<option value="Other">Other</option>
number.";
</select><br><br>
}
<input type="submit" value="Submit">
if (count($errors) > 0) {
</form>
foreach ($errors as $error) {
</body>
echo "<p style='color:red;'>$error</p>";
</html>
}
} else {
echo "<h3>Form Submitted
Successfully!</h3>";
echo "Name: " . htmlspecialchars($name) .
"<br>";
echo "Age: " . htmlspecialchars($age) .
"<br>";
echo "Gender: " .
htmlspecialchars($gender);
}}?>
Q. Write a program in PHP which accepts username and password of a user via a form, connects to a
database and checks if the username-password combination is correct. If correct, show a welcome
message to the user, else show an error message along with a clickable link to the login page.

<?php
// Database connection parameters
$servername = "localhost";
$username = "root"; // Default user for local server
$password = ""; // Default password for localhost
$database = "user_db"; // Assume database already created
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from form
$user = $_POST['username'];
$pass = $_POST['password'];

// Sanitize input
$user = $conn->real_escape_string($user);
$pass = $conn->real_escape_string($pass);

// Query to check credentials


$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = $conn->query($sql);

if ($result->num_rows == 1) {
echo "<h3>Welcome, " . htmlspecialchars($user) . "!</h3>";
} else {
echo "<p style='color:red;'>Invalid username or password.</p>";
echo "<a href='login.html'>Click here to try again</a>";
}
$conn->close();
?>
<?php
// Database connection
$conn = new mysqli("localhost", "root", "", "userdata");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get and sanitize POST data
$name = trim($_POST['name']);
$address = trim($_POST['address']);
$email = trim($_POST['email']);
$mobile = trim($_POST['mobile']);
$errors = [];
// Server-side validations
if (empty($name) || empty($address) || empty($email) || empty($mobile)) {
$errors[] = "All fields are required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
if (!preg_match('/^[0-9]{10}$/', $mobile)) {
$errors[] = "Mobile number must be 10 digits.";
}
// Display errors or insert into database
if (!empty($errors)) {
foreach ($errors as $error) {
echo "<p style='color:red;'>$error</p>";
}
echo "<a href='form.html'>Go back to form</a>";
} else {
$sql = "INSERT INTO users (name, address, email, mobile) VALUES ('$name', '$address', '$email',
'$mobile')";
if ($conn->query($sql) === TRUE) {
echo "<h3>Data inserted successfully!</h3>";
} else {
echo "<p style='color:red;'>Error inserting data: " . $conn->error . "</p>";
}
}$conn->close();?>
q.)Explain the concept of sessions in PHP. How are sessions maintained, and how can session
variables be accessed?

Definition of Session in PHP:


A session in PHP is a mechanism used to store data across multiple web pages for a single user.
Sessions are server-side storage, which means the data is stored on the server and linked to a unique
session ID given to the user.
How Sessions Work:
1. Session Initialization:
o A session starts using the session_start() function.
o It must be the first function in the script before any HTML output.
2. Session ID:
o When a session starts, PHP assigns a unique session ID (via a cookie) to the user.
o This ID is used to retrieve stored session data from the server.
3. Session Storage:
o PHP stores session data in files by default (e.g., /tmp/sess_xxx123).
o The data is stored on the server side and associated with the session ID.

Use Cases of Sessions:


• Login/logout systems
• Shopping carts in e-commerce
• Preserving data during multi-step form submissions
• Storing temporary user preferences

Advantages:
• Secure (data not stored on client-side)
• Stores large amounts of data
• Persistent across multiple pages

Disadvantages:
• Uses server memory
• Requires cookie support (for session ID)
Explain the concept of error handling in PHP. How can errors and exceptions be handled effectively in
PHP code?

Definition of Error Handling:


Error handling in PHP is the process of identifying, catching, and responding to errors during script
execution.

You might also like