将post数据传递给php函数

Passing post data to php function

本文关键字:php 函数 post 数据      更新时间:2023-11-15

我是这个网站和编程的新手。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login page</title>
<script> //This is the client side form validation with Javascript
//This code is executed on the client's browser
function validateForm()
{
    var x=document.getElementById("username").value;
    if (x==null || x=="") //check that the name field is not blank
    {
        alert("Your username must be filled out");
        return false;
    }
    var y =document.getElementById("password").value;
    if (y==null || y=="") //check that the project field is not blank
    {
        alert("Your password must be filled out");
        return false;
    }
 }
</script>
<?php //This is the server side form validation with PHP
//This code executes on the web server
//Write your server side form validation code here
//checks form is submitted

我正在尝试从用户名和密码中获取数据,以便通过此功能进行处理。我已经折腾了好几个小时了,终于放弃了。任何帮助都会很好。

function checkUserData($inputData) {
$inputData = htmlspecialchars($inputData);
$inputData = trim($inputData);
$username = stripslashes($inputData);
return $inputData;
}
?>  
</head>
<body>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"onsubmit="return validateForm()">
Username: <input type="text" name="uname" id="username" /><br/>
Password: <input type="text" name="pwd" id="password" maxlength="6" /><br/>
<input type="submit" value="Login"/>
<input type="Reset" value="Reset"/>
</form>
</body>
</html>

我不知道你是在帖子中遗漏了什么,还是忘记了添加整个代码。但你根本没有得到任何帖子变量。因此,为了获得数据并进行验证,您需要进行

$username = $_POST['uname'];
checkUserData($username);

从你的帖子中还不能100%清楚你试图做什么

您是否试图返回$uname?

function checkUserData($inputData) {
    return stripslashes(trim(htmlspecialchars($inputData)));
}
echo checkUserData($_POST['uname']);

我不太明白你想用php做什么。让我知道这是否解决了你的问题,我会详细说明我的答案。

我认为您必须使用服务器变量$_POST。

示例:

<?php
   //Check if request is POST
   if($_SERVER['REQUEST_METHOD'] == 'POST'){
      $username = checkUserData($_POST['uname']);
      $password = checkUserData($_POST['pwd']);
   }
   function checkUserData($inputData) {
      $inputData = htmlspecialchars($inputData);
      $inputData = trim($inputData);
      $inputData = stripslashes($inputData); 
      return $inputData;
   }
?>

希望这能帮助

要检查所有已发布的表单字段,可以使用:

foreach($_POST as $key => $val)
{
  checkUserData($val);
}