通过 XML HTTP 请求帖子发送密码(启用 HTTPS)

时间:2021-04-17 03:36:48

标签: javascript php xmlhttprequest

可以使用一些帮助来整理在 XML 请求中发送密码的最佳实践。我需要从 HTML 表单中收集输入,如果提供的密码与服务器上的密码匹配,则将表单中的数据插入到数据库中。我想通过 Javascript/XML 请求执行此操作,以便我可以使用 innerHTMLresponseText 在适当位置显示确认消息,而无需导航到新页面。这是我所拥有的一个例子。此服务器已启用 HTTPS。

HTML 片段:

<form  enctype='multipart/form-data' action='javascript:insert_and_confirm_data()'>
<input type='text' id='variable_1'>
<input type='text' id='variable_2>
<input type='password' id='password'>
<input type='submit'>

<div id='confirmation'></div>

Javascript 函数:

function insert_and_confirm_data() {
    if (this.readyState == 4 && this.status == 200) {
        document.getElementById("confirmation").innerHTML = this.responseText;
    }
    var password = document.getElementById("password").value;
    var variable_1 = document.getElementById("variable_1 ").value;
    var variable_2 = document.getElementById("variable_2").value;
    url = 'process_data.php?password=' + password + '&variable_1=' + variable_1 + '&variable_2=' + variable_2;
    xmlhttp.open("POST", url, true);
    xmlhttp.send();
}

PHP 代码段 (process_data.php):

$password = $_POST["password"];
if (password_verify($password, $uploadPass)) {
    // Get the other variables, insert them to a table, echo a confirmation message
} else {
    echo "<p>Incorrect password</p>";
}

这是一种“有效”且安全的发送密码以在服务器上进行验证的方式吗?我的直觉说,即使启用了 HTTPS 并使用 POST 而不是 GET,在 XML URL 中包含密码也是不允许的。我知道如何修改它以直接调用 PHP 脚本,但我真的不想失去在同一页面上显示结果的能力。但我不知道如何在此设置中执行此操作的最佳做​​法。

1 个答案:

答案 0 :(得分:2)

由于您使用的是 POST,因此没有理由也使用 GET 参数。相反,您可以使用 FormData 创建表单编码的有效负载并将其发布。您可能希望为表单提供一个 ID 以供选择。

const formData = new FormData(document.querySelector('form'));
xmlhttp.open("POST", "process_data.php", true);
xmlhttp.send(formData);

Retrieving a FormData object from an HTML form