【发布时间】:2015-04-08 13:55:45
【问题描述】:
我是 PHP 新手,如果未定义用户名和密码,我的 php 表单验证会返回此错误。
注意:未定义变量:D:\hpsp\controller\loginvalidation.inc.php 第 64 行中的用户名
我使用 2 个函数(usernameValidation 和 passwordValidation)来检查 $_POST 输入是否正确,但我不知道是什么以及我必须在哪里放置正确的脚本,提前谢谢你。
<?php
session_start();
require_once('../model/pdo.inc.php');
// function for checking the username validation (not empty & Regex)
function usernameValidation($username) // Username as parameter
{
if ( !empty($_POST['username']) )
{
$username = strtolower(htmlspecialchars($_POST['username'])); // username will be tranform to lowercase before regex matching
if ( preg_match('#^[a-z0-9\.]{5,20}$#', $username) ) // 5 <= username lenght <= 20 in lowercase character to be valid
{
return true; // return true when the username is valid
}
else
{
echo "Invalid username, please re-try" ;
}
}
else
{
echo "Enter your username";
}
}
// function for checking the password validation (not empty & Regex)
function passwordValidation($password) // Password as parameter
{
if ( !empty($_POST['password']) )
{
$password = htmlspecialchars($_POST['password']) ; // Protect the password
if ( preg_match('#^[a-zA-Z0-9\.-_@$()]{6,10}$#', $password) ) // 6 <= password length <= 10 character to be valid
{
return true; // return true when password is valid
}
else
{
echo "Invalid password, please re-try";
}
}
else
{
echo "Enter your password";
}
}
if ( usernameValidation($username) == true AND passwordValidation($password) == true )
{
// PDO Query (SELECT ...)
}
【问题讨论】:
-
要将您的参数设置为可选,您需要这样设置:
functionName($var='default') -
$username您在脚本中哪里定义了这个变量? :) -
尝试回显 $_POST['username'] 并检查它是否有价值?
-
您在 usernameValidation 中初始化 $username。因为这是一个函数,所以不能在该函数之外调用 $username 变量。您需要在函数 usernameValidation() 之外定义 $username 以使其工作。
-
使用 if ( usernameValidation($_POST['username']) == true AND passwordValidation($POST['password']) == true )
标签: php function post undefined function-parameter