PHP Security Practice Questions with Solutions

Introduction

PHP security is essential when building websites and web applications that handle user input, forms, sessions, and database records. Cross-Site Scripting (XSS) can allow attackers to inject malicious scripts, while Cross-Site Request Forgery (CSRF) can trick users into performing unwanted actions. In this chapter, you will practise preventing these attacks and writing safer PHP code. PHP Security Practice Questions with Solutions to help you to build concepts.


Question 1: Prevent XSS Attacks Using htmlspecialchars()

Problem Statement

A website allows users to submit their names through a form. Displaying untrusted input directly on a webpage can allow an attacker to inject HTML or JavaScript.

Create a PHP program that safely displays user input using htmlspecialchars().

PHP Solution

<?php

$username = "<script>alert('Hacked!');</script>";

$safeUsername = htmlspecialchars(
    $username,
    ENT_QUOTES,
    'UTF-8'
);

echo "Welcome, " . $safeUsername;

?>

Sample Output

Welcome, &lt;script>alert('Hacked!');&lt;/script>

The browser displays the script as ordinary text instead of executing it.

Explanation

  • $username contains untrusted input.
  • htmlspecialchars() converts special HTML characters into HTML entities.
  • ENT_QUOTES converts both single and double quotation marks.
  • UTF-8 specifies the character encoding.
  • $safeUsername stores the escaped value.

For example, the < character becomes &lt;, and the > character becomes &gt;.

This prevents the browser from interpreting the supplied text as an HTML script element when it is inserted into an HTML text context.

Important: Escape output according to its context. htmlspecialchars() is suitable for HTML text and properly quoted HTML attribute values, but JavaScript, CSS, and URL contexts require their own safe handling.

Concepts Covered

  • Cross-Site Scripting (XSS)
  • htmlspecialchars()
  • Output escaping
  • HTML special characters
  • Safe output handling

Question 2: Prevent XSS in HTML Form Input

Problem Statement

Create a PHP program that accepts a user’s name through an HTML form and displays it safely after form submission.

PHP Solution

<?php

$name = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $name = $_POST['name'] ?? "";

}

?>

<h2>Enter Your Name</h2>

<form method="POST">

    <input
        type="text"
        name="name"
        placeholder="Enter your name"
        required
    >

    <button type="submit">Submit</button>

</form>

<?php

if ($name !== "") {

    echo "<h3>Welcome, " .
        htmlspecialchars($name, ENT_QUOTES, 'UTF-8') .
        "</h3>";

}

?>

Sample Output

When the user enters:

Rahul

The webpage displays:

Welcome, Rahul

When the user enters:

&lt;script>alert('Hacked');&lt;/script>

The browser displays the supplied script as text instead of executing it.

Explanation

  • The form uses the POST method to submit the name.
  • $_SERVER["REQUEST_METHOD"] checks whether the form was submitted.
  • $_POST['name'] retrieves the submitted value.
  • htmlspecialchars() escapes special HTML characters before displaying the name.

Remember that input validation and output escaping have different purposes. Validation checks whether input is acceptable, while escaping makes output safe for its destination.

Concepts Covered

  • HTML forms with PHP Security
  • POST method
  • $_POST
  • XSS prevention
  • Output escaping
  • htmlspecialchars()

Question 3: Prevent SQL Injection Using Prepared Statements

Problem Statement

Create a PHP program that searches for a student using an email address. Use a prepared statement to prevent SQL injection.

Assume the database contains a students table with id, name, and email columns.

PHP Solution

<?php

$conn = new mysqli(
    "localhost",
    "root",
    "",
    "school_db"
);

if ($conn->connect_error) {
    die("Database connection failed.");
}

$email = "rahul@gmail.com";

$sql = "SELECT id, name, email
        FROM students
        WHERE email = ?";

$stmt = $conn->prepare($sql);

$stmt->bind_param("s", $email);

$stmt->execute();

$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {

    echo "Student Name: " .
        htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8');

    echo "<br>Email: " .
        htmlspecialchars($row['email'], ENT_QUOTES, 'UTF-8');

} else {

    echo "Student not found.";
}

$stmt->close();

$conn->close();

?>

Sample Output

Student Name: Rahul
Email: rahul@gmail.com

Explanation

SQL injection happens when an attacker manipulates an SQL query through untrusted input.

For example, directly inserting user input into an SQL query can change the query’s intended meaning.

Prepared statements separate SQL instructions from supplied values.

  • prepare() prepares the SQL query.
  • ? represents a value placeholder.
  • bind_param() supplies the email safely.
  • execute() runs the query.

The supplied email is treated as data rather than SQL instructions.

Important: This example uses MySQLi’s get_result(), which requires the MySQL Native Driver (mysqlnd).

Concepts Covered

  • SQL injection
  • MySQLi prepared statements
  • Parameter binding
  • Database security
  • Safe database search

Question 4: Generate a Secure CSRF Token

Problem Statement

Create a PHP program that generates a random CSRF token and stores it in a session. This token will later be used to verify that a form submission originated from the application.

PHP Solution

<?php

session_start();

if (!isset($_SESSION['csrf_token'])) {

    $_SESSION['csrf_token'] = bin2hex(
        random_bytes(32)
    );

}

echo "CSRF Token Generated Successfully.<br>";

echo htmlspecialchars(
    $_SESSION['csrf_token'],
    ENT_QUOTES,
    'UTF-8'
);

?>

Sample Output

CSRF Token Generated Successfully.

a1b2c3d4e5f6... (random token)

The actual token will be different each time a new session is created.

Explanation

A CSRF token is a random value that helps an application verify whether a submitted request is associated with the user’s session.

  • session_start() starts or resumes the session.
  • random_bytes(32) generates 32 cryptographically secure random bytes.
  • bin2hex() converts the bytes into a hexadecimal string.
  • $_SESSION['csrf_token'] stores the token in the user’s session.

The token should be difficult for an attacker to guess.

Important: Generating a token alone does not prevent CSRF. The application must include it in relevant forms and verify it on the server before performing the requested action.

Concepts Covered

  • CSRF protection
  • Secure random token generation
  • random_bytes()
  • bin2hex()
  • PHP Security sessions

Question 5: Protect an HTML Form Using a CSRF Token

Problem Statement

Create a PHP form that generates a CSRF token, includes it as a hidden form field, and verifies it when the user submits the form.

PHP Solution

<?php

session_start();

if (!isset($_SESSION['csrf_token'])) {

    $_SESSION['csrf_token'] = bin2hex(
        random_bytes(32)
    );

}

$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $submittedToken = $_POST['csrf_token'] ?? "";

    if (
        !is_string($submittedToken) ||
        !hash_equals(
            $_SESSION['csrf_token'],
            $submittedToken
        )
    ) {

        http_response_code(403);

        $message = "Invalid CSRF token. Request rejected.";

    } else {

        $message = "Form submitted successfully.";

        // Generate a new token after successful submission

        $_SESSION['csrf_token'] = bin2hex(
            random_bytes(32)
        );

    }
}

?>

<h2>Secure Contact Form</h2>

<form method="POST">

    <input
        type="hidden"
        name="csrf_token"
        value="<?php echo htmlspecialchars(
            $_SESSION['csrf_token'],
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <input
        type="text"
        name="name"
        placeholder="Enter your name"
        required
    >

    <button type="submit">Submit</button>

</form>

<p><?php echo htmlspecialchars($message); ?></p>

Sample Output

When a valid token is submitted:

Secure Contact Form

Form submitted successfully.

When an invalid token is submitted:

Invalid CSRF token. Request rejected.

The server also returns HTTP status code 403 for an invalid token.

Explanation

1. Generate a token

$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

This creates a random token and stores it in the session.

2. Add the token to the form

<input type="hidden" name="csrf_token">

The hidden field sends the token along with the form data.

3. Retrieve the submitted token

$submittedToken = $_POST['csrf_token'] ?? "";

This reads the token submitted by the browser.

4. Compare the tokens

hash_equals($_SESSION['csrf_token'], $submittedToken)

hash_equals() performs a timing-safe comparison of the two strings.

If the tokens match, the application accepts the request. Otherwise, it rejects the request.

Concepts Covered

  • CSRF token validation
  • Hidden form fields
  • hash_equals()
  • Session-based security
  • POST request protection
  • HTTP 403 response

Question 6: Prevent CSRF in a Password Change Form

Problem Statement

Create a PHP program that allows a logged-in user to change their password securely. Protect the form using a CSRF token and verify the current password before saving the new password.

Assume the users table contains id and password columns and the user is already authenticated.

PHP Solution

<?php

session_start();

if (!isset($_SESSION['user_id'])) {

    http_response_code(401);

    exit("Please log in first.");

}

$conn = new mysqli(
    "localhost",
    "root",
    "",
    "auth_db"
);

if ($conn->connect_error) {
    die("Database connection failed.");
}

if (!isset($_SESSION['csrf_token'])) {

    $_SESSION['csrf_token'] = bin2hex(
        random_bytes(32)
    );

}

$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $token = $_POST['csrf_token'] ?? "";

    if (
        !is_string($token) ||
        !hash_equals($_SESSION['csrf_token'], $token)
    ) {

        http_response_code(403);

        $message = "Invalid CSRF token.";

    } else {

        $currentPassword = $_POST['current_password'] ?? "";

        $newPassword = $_POST['new_password'] ?? "";

        if (strlen($newPassword) < 8) {

            $message = "New password must contain at least 8 characters.";

        } else {

            $sql = "SELECT password
                    FROM users
                    WHERE id = ?";

            $stmt = $conn->prepare($sql);

            $stmt->bind_param("i", $_SESSION['user_id']);

            $stmt->execute();

            $result = $stmt->get_result();

            $user = $result->fetch_assoc();

            $stmt->close();

            if (
                $user &&
                password_verify($currentPassword, $user['password'])
            ) {

                $newHash = password_hash(
                    $newPassword,
                    PASSWORD_DEFAULT
                );

                $updateSql = "UPDATE users
                              SET password = ?
                              WHERE id = ?";

                $updateStmt = $conn->prepare($updateSql);

                $updateStmt->bind_param(
                    "si",
                    $newHash,
                    $_SESSION['user_id']
                );

                if ($updateStmt->execute()) {

                    $message = "Password changed successfully.";

                    $_SESSION['csrf_token'] = bin2hex(
                        random_bytes(32)
                    );

                } else {

                    $message = "Unable to change password.";
                }

                $updateStmt->close();

            } else {

                $message = "Current password is incorrect.";
            }
        }
    }
}

?>

<h2>Change Password</h2>

<form method="POST">

    <input
        type="hidden"
        name="csrf_token"
        value="<?php echo htmlspecialchars(
            $_SESSION['csrf_token'],
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <input
        type="password"
        name="current_password"
        placeholder="Current Password"
        required
    >

    <br><br>

    <input
        type="password"
        name="new_password"
        placeholder="New Password"
        minlength="8"
        required
    >

    <br><br>

    <button type="submit">Change Password</button>

</form>

<p><?php echo htmlspecialchars($message); ?></p>

Sample Output

Change Password

Password changed successfully.

Explanation

This example combines multiple security techniques.

  • The session verifies that the user is logged in.
  • The CSRF token protects the password change form.
  • hash_equals() checks the submitted token.
  • password_verify() checks the current password.
  • password_hash() generates a secure hash for the new password.
  • A prepared UPDATE statement saves the new hash.

The application does not store the new password as plain text.

For a production application, also use password-change rate limiting, invalidate other active sessions when appropriate, and consider requiring reauthentication for sensitive account changes.

Concepts Covered

  • Password change security
  • CSRF protection
  • Session authentication
  • Password verification
  • Password hashing
  • Prepared UPDATE statements

Question 7: Validate and Sanitize User Input Securely

Problem Statement

Create a PHP program that accepts a user’s name and email address through a form. Validate the email address and safely display the submitted information.

PHP Solution

<?php

$message = "";

$name = "";

$email = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $name = trim($_POST['name'] ?? "");

    $email = trim($_POST['email'] ?? "");

    if ($name === "") {

        $message = "Name is required.";

    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

        $message = "Please enter a valid email address.";

    } else {

        $message = "Form submitted successfully.";
    }
}

?>

<h2>User Information Form</h2>

<form method="POST">

    <input
        type="text"
        name="name"
        placeholder="Enter Name"
        required
    >

    <br><br>

    <input
        type="email"
        name="email"
        placeholder="Enter Email"
        required
    >

    <br><br>

    <button type="submit">Submit</button>

</form>

<?php

echo "<p>" . htmlspecialchars($message) . "</p>";

if ($message === "Form submitted successfully.") {

    echo "Name: " .
        htmlspecialchars($name, ENT_QUOTES, 'UTF-8') .
        "<br>";

    echo "Email: " .
        htmlspecialchars($email, ENT_QUOTES, 'UTF-8');
}

?>

Sample Output

Valid input:

Name: Rahul
Email: rahul@gmail.com

Form submitted successfully.

Invalid email:

Please enter a valid email address.

Explanation

Input validation checks whether submitted data follows the expected rules.

  • trim() removes unnecessary spaces from the beginning and end.
  • FILTER_VALIDATE_EMAIL checks the email format.
  • htmlspecialchars() safely displays the submitted values.
  • The program displays user information only when validation succeeds.

Remember these differences:

TechniquePurpose
ValidationChecks whether data is acceptable
SanitizationTransforms or removes unwanted characters
Output escapingMakes data safe for a particular output context

Do not rely on sanitization alone to prevent XSS. Escape untrusted data when displaying it.

Concepts Covered

  • Input validation
  • trim()
  • filter_var()
  • Email validation
  • Output escaping
  • Secure form handling

Question 8: Prevent Unauthorized Access Using Session Checks

Problem Statement

Create a PHP program that protects a dashboard page. Only authenticated users should be able to access the dashboard.

If the user is not logged in, redirect them to the login page.

PHP Solution

<?php

session_start();

if (!isset($_SESSION['user_id'])) {

    header("Location: login.php");

    exit();
}

?>

<h2>User Dashboard</h2>

<p>
    Welcome,
    <?php echo htmlspecialchars(
        $_SESSION['user_name'],
        ENT_QUOTES,
        'UTF-8'
    ); ?>
</p>

<p>You are authorized to access this page.</p>

Sample Output

When a user is logged in:

User Dashboard

Welcome, Rahul

You are authorized to access this page.

When a user is not logged in:

The user is redirected to login.php.

Explanation

  • session_start() starts or resumes the session.
  • isset() checks whether the user ID exists.
  • If the user ID is missing, header() redirects the visitor.
  • exit() stops the remaining PHP Security code.
  • htmlspecialchars() safely displays the session username.

Authentication checks must happen before protected page content is sent to the browser.

Important: A session check protects against unauthenticated visitors, but authorization must also be checked when a page or action requires a particular role or permission.

Concepts Covered

  • PHP Security sessions
  • Authentication checks
  • Protected pages
  • Header redirection
  • Safe session output
  • Access control

Question 9: Secure File Upload Validation

Problem Statement

Create a PHP program that accepts an image upload and checks its file size and actual image type before saving it.

The program should allow JPEG and PNG images only, with a maximum size of 2 MB.

PHP Solution

<?php

$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    if (
        !isset($_FILES['image']) ||
        $_FILES['image']['error'] !== UPLOAD_ERR_OK
    ) {

        $message = "Please select a valid image.";

    } else {

        $file = $_FILES['image'];

        $maximumSize = 2 * 1024 * 1024;

        if ($file['size'] > $maximumSize) {

            $message = "File size must not exceed 2 MB.";

        } else {

            $imageInfo = getimagesize($file['tmp_name']);

            if ($imageInfo === false) {

                $message = "Uploaded file is not a valid image.";

            } else {

                $allowedTypes = [
                    'image/jpeg' => 'jpg',
                    'image/png' => 'png'
                ];

                $mimeType = $imageInfo['mime'];

                if (!isset($allowedTypes[$mimeType])) {

                    $message = "Only JPEG and PNG images are allowed.";

                } else {

                    $uploadDirectory = __DIR__ . "/uploads/";

                    if (
                        !is_dir($uploadDirectory) &&
                        !mkdir($uploadDirectory, 0750, true)
                    ) {

                        $message = "Unable to create upload directory.";

                    } else {

                        $filename = bin2hex(random_bytes(16))
                            . "."
                            . $allowedTypes[$mimeType];

                        $destination = $uploadDirectory . $filename;

                        if (
                            move_uploaded_file(
                                $file['tmp_name'],
                                $destination
                            )
                        ) {

                            $message = "Image uploaded successfully.";

                        } else {

                            $message = "Unable to upload image.";
                        }
                    }
                }
            }
        }
    }
}

?>

<h2>Secure Image Upload</h2>

<form method="POST" enctype="multipart/form-data">

    <input type="file" name="image" accept="image/jpeg,image/png" required>

    <button type="submit">Upload Image</button>

</form>

<p><?php echo htmlspecialchars($message); ?></p>

Sample Output

When a valid JPEG or PNG image is uploaded:

Secure Image Upload

Image uploaded successfully.

When an unsupported file is uploaded:

Only JPEG and PNG images are allowed.

Explanation

File uploads can be dangerous if an application trusts only the file extension or the filename supplied by the user.

This program performs several checks:

  • $_FILES retrieves information about the uploaded file.
  • UPLOAD_ERR_OK checks whether the upload completed successfully.
  • The file size is checked against the 2 MB limit.
  • getimagesize() checks whether the uploaded file is a valid image and provides its detected image type.
  • The MIME type is compared against an allowlist.
  • random_bytes() generates a random filename.
  • move_uploaded_file() moves the validated upload to the destination directory.

Important: For production, store uploads outside the public web directory where possible. Configure the server so uploaded files cannot execute as scripts. Add authentication, authorization, CSRF protection, and additional upload limits.

Concepts Covered

  • Secure file uploads
  • $_FILES
  • File size validation
  • Image type validation
  • getimagesize()
  • Random filenames
  • move_uploaded_file()

Question 10: Build a Secure PHP Contact Form

Problem Statement

Create a PHP contact form that accepts a user’s name, email, and message.

The application must:

  1. Generate and verify a CSRF token.
  2. Validate the submitted email.
  3. Check that required fields are not empty.
  4. Escape user input before displaying it.
  5. Reject invalid requests.

PHP Solution

<?php

session_start();

if (!isset($_SESSION['csrf_token'])) {

    $_SESSION['csrf_token'] = bin2hex(
        random_bytes(32)
    );

}

$message = "";

$name = "";

$email = "";

$userMessage = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $token = $_POST['csrf_token'] ?? "";

    if (
        !is_string($token) ||
        !hash_equals($_SESSION['csrf_token'], $token)
    ) {

        http_response_code(403);

        $message = "Invalid request. Please refresh the page.";

    } else {

        $name = trim($_POST['name'] ?? "");

        $email = trim($_POST['email'] ?? "");

        $userMessage = trim($_POST['message'] ?? "");

        if (
            $name === "" ||
            $email === "" ||
            $userMessage === ""
        ) {

            $message = "All fields are required.";

        } elseif (
            !filter_var($email, FILTER_VALIDATE_EMAIL)
        ) {

            $message = "Please enter a valid email address.";

        } else {

            $message = "Contact form submitted successfully.";

            // Rotate token after successful processing

            $_SESSION['csrf_token'] = bin2hex(
                random_bytes(32)
            );
        }
    }
}

?>

<h2>Secure Contact Form</h2>

<form method="POST">

    <input
        type="hidden"
        name="csrf_token"
        value="<?php echo htmlspecialchars(
            $_SESSION['csrf_token'],
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <input
        type="text"
        name="name"
        placeholder="Enter Name"
        required
    >

    <br><br>

    <input
        type="email"
        name="email"
        placeholder="Enter Email"
        required
    >

    <br><br>

    <textarea
        name="message"
        placeholder="Enter Message"
        required
    ></textarea>

    <br><br>

    <button type="submit">Submit</button>

</form>

<p><?php echo htmlspecialchars($message); ?></p>

<?php

if ($message === "Contact form submitted successfully.") {

    echo "<h3>Submitted Information</h3>";

    echo "Name: " .
        htmlspecialchars($name, ENT_QUOTES, 'UTF-8') .
        "<br>";

    echo "Email: " .
        htmlspecialchars($email, ENT_QUOTES, 'UTF-8') .
        "<br>";

    echo "Message: " .
        nl2br(
            htmlspecialchars(
                $userMessage,
                ENT_QUOTES,
                'UTF-8'
            )
        );
}

?>

Sample Output

When valid information is submitted:

Secure Contact Form

Name: Rahul
Email: rahul@gmail.com
Message: I want to know more about PHP courses.

Contact form submitted successfully.

Submitted Information

Name: Rahul
Email: rahul@gmail.com
Message: I want to know more about PHP courses.

When an invalid email is entered:

Please enter a valid email address.

When an invalid CSRF token is submitted:

Invalid request. Please refresh the page.

Explanation

This contact form combines several important PHP security techniques.

1. CSRF token generation

$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

The application generates a secure random token and stores it in the session.

2. CSRF token verification

hash_equals($_SESSION['csrf_token'], $token)

The application compares the submitted token with the session token.

3. Input validation

filter_var($email, FILTER_VALIDATE_EMAIL)

This checks whether the submitted email address has a valid format.

4. Required field checking

The program checks that the name, email, and message are not empty.

5. Output escaping

htmlspecialchars($userMessage, ENT_QUOTES, 'UTF-8')

This prevents submitted text from being interpreted as HTML or JavaScript.

6. Preserve message line breaks

nl2br(htmlspecialchars($userMessage, ENT_QUOTES, 'UTF-8'))

The message is escaped first, and then line breaks are converted into HTML line-break elements.

Important: This practice application displays the submitted information but does not store it or send an email. A production contact form should also use rate limiting, appropriate spam protection, and secure handling of submitted data.

Concepts Covered

  • Secure contact forms
  • CSRF protection
  • XSS prevention
  • Input validation
  • Email validation
  • Output escaping
  • PHP Security sessions
  • Secure form processing

Key Takeaways

  • XSS allows attackers to inject malicious scripts into webpages.
  • htmlspecialchars() helps prevent XSS when displaying untrusted data in HTML contexts.
  • SQL injection can be prevented by using prepared statements for user-supplied values.
  • CSRF attacks trick authenticated users into submitting unwanted requests.
  • CSRF tokens help verify that sensitive form submissions originate from the application.
  • random_bytes() generates cryptographically secure random data.
  • hash_equals() safely compares CSRF tokens.
  • Input validation checks whether submitted data follows expected rules.
  • Output escaping makes untrusted data safe for its destination context.
  • Secure file uploads require file size and content validation.
  • Protected pages should verify authentication and authorization before performing sensitive actions.
  • Secure coding requires multiple layers of protection rather than relying on a single function.

Frequently Asked Questions (FAQs)

1. What is XSS in PHP?

Cross-Site Scripting (XSS) is a security vulnerability in which an attacker injects malicious scripts into a webpage. PHP applications can help prevent XSS by escaping untrusted output with functions such as htmlspecialchars().

2. How does htmlspecialchars() prevent XSS?

htmlspecialchars() converts special HTML characters into HTML entities. This helps ensure that untrusted text is displayed as text instead of being interpreted as HTML markup.

3. What is CSRF in PHP?

Cross-Site Request Forgery (CSRF) is an attack that tricks an authenticated user’s browser into sending an unwanted request to a website where the user is logged in.

4. What is a CSRF token?

A CSRF token is a random, unpredictable value associated with a user’s session. The application includes it in forms and verifies it before processing sensitive requests.

5. What is the difference between XSS and CSRF?

XSS involves injecting malicious scripts into a website. CSRF tricks a user’s browser into submitting an unwanted request to a website where the user is authenticated.

6. What is the use of random_bytes() in PHP?

random_bytes() generates cryptographically secure random bytes. It can be used to generate CSRF tokens, random identifiers, and other security-related values.

7. Why should we use prepared statements in PHP?

Prepared statements separate SQL instructions from user-supplied values. They help prevent SQL injection attacks and make database queries safer.

8. What is the difference between validation and sanitization?

Validation checks whether input follows expected rules. Sanitization transforms or removes unwanted characters. Output escaping is a separate process used to display data safely.

9. Is input validation enough to prevent XSS?

No. Input validation alone is not sufficient. Applications should escape untrusted data according to the context in which it is displayed.

10. How can we secure file uploads in PHP?

Validate the upload error, file size, and actual file content. Use an allowlist of permitted file types, generate random filenames, and store uploaded files in a location where they cannot execute as scripts.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top