PHP code error displaying code on login screen

How do i fix PHP code not fully Executing.

Current behavior:
Puts the PHP code on my projects login screen

Desired behavior
To become fully functioning and not put PHP on my login scewn and sends a message when ir scans my database and the user is incorrect

Repl link:

code snippet
// Include MongoDB library
require_once 'vendor/autoload.php';

// MongoDB connection URI
$uri = 'mongodb+srv://';

// Initialize error message variable
$errorMessage = "";

// Check if the form has been submitted
    // Retrieve form data
    $username = $_POST['username'];
    $password = $_POST['password'];

    try {
        // Connect to MongoDB server
        $client = new MongoDB\Client($uri);

        // Select database and collection
        $collection = $client->selectDatabase('userdatabase')->selectCollection('users');

        // Query the database
        $query = ['username' => $username, 'password' => $password];
        $user = $collection->findOne($query);

        if ($user) {
            // If user is found, redirect to dashboard or another page
            header("Location: dashboard.php");
        } else {
            // If user is not found, set an error message
            $errorMessage = "Invalid username or password. Please try again.";
    } catch (Exception $e) {
        // If an exception occurs, set an error message
        $errorMessage = "An error occurred while processing your request. Please try again later.";
        // You can also log the error message or exception for further investigation

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
        <h1>Login to My Sound Portal</h1>
        <form action="login.php" method="post" class="form">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" required>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
            <button type="submit" name="submit">Login</button>
            // Display error message if it's not empty
            if (!empty($errorMessage)) {
                echo "<p class='error'>$errorMessage</p>";

Try to use the PHP template, the server must not recognizing your php files. Or you can try change the extension of the files, like index.php and not index.html . The server will look for an index.php file to serve as the starting point.
Also, in your index.html remember to insert the <?php ..... ?> at the top of your code and after your html code.

1 Like

Yep, PHP is run server-side, so just statically serving a PHP file (HTML template will statically serve all files) on the front-end will not work.

You also only need <?php ... ?> where ever you want to embed PHP code in a PHP file (and this could even be multiple times).