Please submit the form to log in with your credentials

Here is the HTML code snippet for a form where users can enter their username and password to log in:

<form Name ="form1" Method ="POST" ACTION = "userlogin.php" id="form1">
    <div id="main_body" class="full-width">
        <label>Username:</label>
        <input type = "text"
               id = "usernameLogin"
               name="pat_username">
        <label>Password:</label>
        <input type = "password"
               id = "passwordLogin"
               name="pat_password">
        <input type="submit" onclick="click_button_login()" value="Login" name="submit" id="submit"/>
    </div>
</form>

The associated PHP file connects to a database to verify user credentials. When testing on an emulator, this error occurs:

Cannot POST /http-services/emulator-webserver/ripple/userapp/x/C/xampp/htdocs/xampp/glove_project_php/www/userlogin.php

<?php
if(isset($_POST["submit"])){
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "dbname";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    //Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }


    $newUsername = mysqli_real_escape_string($conn, $_POST['pat_username']); 
    $newPassword = mysqli_real_escape_string($conn, $_POST['pat_password']);   

    $result = $conn->query("SELECT * FROM tablename WHERE patient_username ='$newUsername' AND patient_password='$newPassword'");

    if (mysqli_num_rows($result)) {
        header("Location: mainmenu.html");       
    } 
    else {    
        header("Location: index.html");
    }
    $conn->close();
}
?>

Is there a specific method to make this PHP file work correctly on an emulator? It functions properly when tested on a localhost server.

Answer №1

Is there a reason for verifying the presence of $_POST["submit"] in the $_POST superglobal? It seems more appropriate to confirm that the variables you transmitted are defined:

replace:

if(isset($_POST["submit"]))

with:

if ((isset($_POST["pat_username"]))&&(isset($_POST["pat_password"])))

and inform me if the issue persists.

Answer №2

  When designing your form, prioritize security and prevent auto submission. Implementing unique SESSION_ID() tokens can help eliminate automatic submissions during web browsing sessions.

    <Form Name ="form1" Method ="POST" ACTION = "userlogin.php" id="form1">
    <div id="main_body" class="full-width">
        <br>
        <br>                      
                    <label>Username:</label>
                    <input type = "text"
                           id = "usernameLogin"
                           name="pat_username"> <br>

                <br>    <label>Password:</label>
                    <input type = "password"
                           id = "passwordLogin"
                           name="pat_password"> <br><button value="<?php echo session_id() ?>" type="submit" name="login_check">Login</button>

   </div>
   </Form>

//If you are dealing with a login check page, it is essential to address security risks. Encrypt passwords using techniques like SALT, hash/md5/sha. Also, for database queries, consider using sprintf as shown in this example:

  ##SPRINTF EXAMPLE CODE
  //$query = sprintf('SELECT * FROM TABLE WHERE username = "%s" AND password = "%s"',mysql_real_escape_string($username),mysql_real_escape_string($password));

  #### EXAMPLE END HERE##

  <?php
  if(isset($_POST["login_check"]) && $_POST['login_check']==session_id()){
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "dbname";

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);

  //Check connection
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }


$newUsername = mysqli_real_escape_string($conn, $_POST['pat_username']); 
$newPassword = mysqli_real_escape_string($conn, $_POST['pat_password']);   

$result = $conn->query("SELECT * FROM tablename WHERE patient_username ='$newUsername' AND patient_password='$newPassword'");



if (mysqli_num_rows($result)) {
    header("Location: mainmenu.html");       
} 
else
{    
    header("Location: index.html");

}
$conn->close();
 }
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Select the send all text option when making a request

Using ajax, I can dynamically fill a drop-down select menu. My next step is to include all the text from the selected options in my request. <select name=".." > <option value="0"> ... </option> <option value="1"> xxx </option ...

How to display and retrieve data from a JSON object using JavaScript

Having trouble retrieving input values from a JSON object and getting 'undefined' when running the code. Any suggestions or ideas would be greatly appreciated as I have tried various approaches. Additionally, I need to utilize JSON for my school ...

What is the best way to design a webpage that adapts to different screen heights instead of widths?

I'm in the process of designing a basic webpage for a game that will be embedded using an iframe. The game and text should always adjust to fit the height of your screen, so when the window is small, only the game is displayed. The game will be e ...

What is the best way to convert items from a foreach loop into a JSON string using the json_encode() function in PHP?

I want to populate a string with all the emails fetched from the database, in order to use JavaScript for checking if the email entered by a user in a form field is already registered. I'm attempting to utilize the json_encode() function. $connec ...

Is it a good idea to relocate the document.ready function into its own JavaScript function?

Can the following code be placed inside a separate JavaScript function within a jQuery document.ready, allowing it to be called like any other JavaScript function? <script type="text/javascript"> $(document).ready(function() { $('div#infoi ...

Looking to use PHP to update the JSON value

Would you like to modify some settings, such as the description? Change the value to "test2" in the JSON form URL below: { "title": "test", "description": "test", "keyword": "test", "ogimage": "test", "radio": "test", "noscript": "test", " ...

Is there a way to change a .pptx document into a base64 string?

Currently, I am working on a project that involves creating an addin for Office. The challenge I am facing is opening other pptx files from within the addin. After some research, I discovered that I need to use base64 for the PowerPoint.createPresentation( ...

The function initFoodModel is missing and causing issues as it tries to read properties of undefined, specifically attempting to read 'findAll'

myWishlist.js const { setupFoodModel } = require("../../model/FoodModel"); const { setupWishlistModel } = require("../../model/myWishlistModel"); const setupMyWishlistModel = async () =\> { try { const sequelizeConnection = awai ...

Tips for verifying conditional input fields in a React component?

As a beginner in React, I attempted to create a SignIn form component that dynamically changes its layout based on a boolean prop toggled between Login and Signup options. In the signup version, there is an additional text field labeled Confirm password, w ...

Leveraging the Checkbox Value from a Custom Option Page on the Frontend

Recently, I created a new admin page with various settings, including a checkbox. My goal is to utilize the value of this checkbox to adjust the CSS on the front end of the home page. Specifically, I want to hide the sidebar when the checkbox is marked. I ...

Elusive Appearance of the Flask Flash Message

I have developed a web application using Flask that allows users to upload files to an S3 storage. However, I would like to enhance the user experience by showing them the progress of their file uploads in real-time. To achieve this, I am utilizing Flash t ...

Guidance on implementing fallback font formats using FontFace API

I am exploring the FontFace API (not @fontface) and wondering if there is an easy way to include multiple font formats, similar to providing multiple sources in @fontface. Alternatively, is there a simple method to identify which font formats are supporte ...

Encountering a npm script error while running on a Windows operating

While using webpack to build my application, I encountered the following error message in the command prompt: [email protected] dev D:\Myprograms\java script\forkify webpack --mode development The error mentioned: Insufficient num ...

Unable to cancel $interval within factory

I created a factory for long-polling, complete with start and stop methods. However, I am struggling to cancel the timer. Any suggestions or ideas? app.controller("AuthCtrl", function($scope, $http, $window, User, Poller) { Poller.start(1, $scope.sess ...

Warning: Unhandled promise rejection occurred while running the test

Currently delving into the world of selenium with a focus on testing the registration page. I've crafted a registration page class equipped with methods for monitoring registrations. However, upon attempting to execute a test within the application cl ...

An issue with Destination-Out Composition in HTML5 Canvas

While working on a canvas, I have encountered an issue with deleting a portion of a curve I have drawn. Specifically, I need to remove the last 25% of the curve after it is complete and keep only the first 75%. However, when attempting to delete the lines ...

Ways to tackle my code's linked dropdown issue without the use of extensions

When I selected the Id Province, I couldn't select the Id City. How can I fix this issue? Controller code snippet to address this: View code snippet for the same: ...

What is the best way to create a more compact Select component in React?

Working on React's Select component has been quite the challenge for me. I'm in the process of creating a simple dropdown button, also known as a ComboBox, similar to what can be seen on GitHub Insights: https://i.stack.imgur.com/J9Bcd.png Belo ...

Django: The Art of Rejuvenating Pages

Consider the following code snippet which updates the timestamp of a database model whenever it is accessed: def update_timestamp(request): entry = Entry.objects.filter(user=request.user) entry.update(timestamp=timezone.now()) return HttpRespo ...

I am having trouble getting the Audio Code (a very basic code) to function properly

<audio id="myAudio" src="Avengers.mp3" type="audio/mpeg"></audio> <script> window.onload = function(){ document.getElementById('myAudio').play() } </script> Recently experimenting with some code in NotePad, a friend had ...