注册表 - 拒绝某些条件并向用户返回消息

我正在尝试实现它,如果用户试图创建一个帐户,他们必须满足特定的字符串长度 ETC。如果他们不这样做,那么页面应该向他们吐出一条消息。


我仅针对用户名尝试了以下操作作为测试,但它并不成功。我只用了几天 PHP,谢天谢地,我是新手,我已经在谷歌、youtube 和 stackoverflow 上搜索过,但似乎无法让它适用于我的具体情况。


<?php 

include_once 'config.php';

$_SESSION['message'] = "Initiating Account Creation.";


$mysqli = sqlsrv_connect($serverName, $conn_array) or die ($_SESSION['message'] = "No connection to the database.");


if (isset($_POST['register'])) {

    session_start();

    // No crazy special characters in user or email because it can mess with SQL query + inputs.

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

    $email = ($_POST['email']);

    //VERIFY TWO PASSWORDS ARE EQUAL.

    $password = ($_POST['password']);

    $password2 = ($_POST['confirmpassword']);


    $str_len1 = strlen(($_POST['username']));



    if ($str_len1 < 6)

    {

        $_SESSION['message'] = "Registration Failed. Unable to add $username to the database!";

        // exit(); using this completely erases the form even after refreshing the page.

    }


    if ($password == $password2) {

    //md5 hashed password for basic security.

    $password = md5($password);

    $sql = "

    SET ANSI_NULLS ON

    SET QUOTED_IDENTIFIER ON

    SET CONCAT_NULL_YIELDS_NULL ON

    SET ANSI_WARNINGS ON

    SET ANSI_PADDING ON

    exec dnmembership.dbo.__NX__CreateAccount '$username','$password','$email'

    ";

    sqlsrv_query ($mysqli, $sql);


    $_SESSION['message'] = "Registration Successful. Added $username to the database!";

    header("location: welcome.php");



}else{

    $_SESSION['message'] = "Registration error. Try a valid username, password, or email.";


    }


    }


?>


江户川乱折腾
浏览 100回答 1
1回答

绝地无双

首先,你的代码很乱。我试图清理它;请以我的代码为例,并尝试练习编写干净的代码。其次,永远不要用它$_SESSION['']来声明消息。最好是使用 simple echo。更好的是,我添加了一个功能。退出()函数方法:session_start();include('config.php');// For error or success messages place the following functions in your functions.php file and include the file here.// The following functions are based on bootstrap classes for error and success message. If you are not using bootstrap you can stylize your own.function alertSuccess($msg){&nbsp; $alert = "<div class='alert alert-success'>".$msg."</div>";&nbsp; return $alert;}function alertError($msg){&nbsp; $alert = "<div class='alert alert-danger'>".$msg."</div>";&nbsp; return $alert;}function alertInfo($msg){&nbsp; $alert = "<div class='alert alert-info'>".$msg."</div>";&nbsp; return $alert;}// Storing Form Inputs$username = (!empty($_POST['username']))?mysqli_real_escape_string($_POST['username']):null;$email = (!empty($_POST['email']))?mysqli_real_escape_string($_POST['email']):null;$password = (!empty($_POST['password']))?$_POST['password']:null;$password2 = (!empty($_POST['confirmpassword']))?$_POST['confirmpassword']:null;if(isset($_POST['register'])) {&nbsp; // Set "Creating Account" message. This is unnecessary but if you want it then okay.&nbsp; echo alertInfo("Initiating Account Creation...");&nbsp; // If username is null then rest of the code will not be executed&nbsp; if($username == null){&nbsp; &nbsp; echo alertError("Invalid username!");&nbsp; &nbsp; exit();&nbsp; }&nbsp; // If password is not equal then rest of the code will not be executed&nbsp; if($password != $password2){&nbsp; &nbsp; echo alertError("Password mismatch");&nbsp; &nbsp; exit();&nbsp; }&nbsp; // If username is less than 6 characters long then rest of the code will not be executed&nbsp; if(strlen($username) < 6){&nbsp; &nbsp; echo alertError("Username must contain at least 6 characters.");&nbsp; &nbsp; exit();&nbsp; }&nbsp; // All checks done already (including password check). Now process the query.&nbsp; $password = md5($password);&nbsp; $sql = "SET ANSI_NULLS ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SET QUOTED_IDENTIFIER ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SET CONCAT_NULL_YIELDS_NULL ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SET ANSI_WARNINGS ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SET ANSI_PADDING ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; exec dnmembership.dbo.__NX__CreateAccount '$username','$password','$email'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";&nbsp; if(sqlsrv_query($mysqli, $sql)){&nbsp; &nbsp; echo alertSuccess("Registration Successful! Please wait....");&nbsp; &nbsp; header("Location: welcome.php");&nbsp; &nbsp; exit();&nbsp; }else{&nbsp; &nbsp; echo alertError("Sorry, something went wrong! Please refresh the page and try again.");&nbsp; }}If...Else 函数方法:同样可以使用 If...Else 方法实现。if($username == null){&nbsp; echo alertError("Invalid username!");}else if($password != $password2){&nbsp; echo alertError("Password mismatch");}else if(strlen($username) < 6){&nbsp; echo alertError("Username must contain at least 6 characters.");}else{&nbsp; // All checks done already (including password check). Now process the query.&nbsp; $password = md5($password);&nbsp; $sql = "SET ANSI_NULLS ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SET QUOTED_IDENTIFIER ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SET CONCAT_NULL_YIELDS_NULL ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SET ANSI_WARNINGS ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SET ANSI_PADDING ON&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; exec dnmembership.dbo.__NX__CreateAccount '$username','$password','$email'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ";&nbsp; if(sqlsrv_query($mysqli, $sql)){&nbsp; &nbsp; echo alertError("Registration Successful! Please wait....");&nbsp; &nbsp; header("Location: welcome.php");&nbsp; &nbsp; exit();&nbsp; }else{&nbsp; &nbsp; echo alertError("Sorry, something went wrong! Please refresh the page and try again.");&nbsp; }}使用您喜欢的任何方法。两者都很完美。请注意,我不确切知道如何在 SQL SERVER 中工作,因此,我没有研究您的$sql部分。休息是 100% 正确的。如果您使用的是 PDO,我也会检查 SQL。请从合适的人那里确认您正在为您的任务使用正确的 SQL。此外,以前,您的代码无法正常工作的一个原因可能是用户名输入可能为空,或者简单地说,PHP 没有收到用户名的表单输入。因此,我也添加了对用户名是否为空的检查。如果它返回“无效的用户名!” 然后检查您的表单字段name=""部分的用户名字段。另请注意,您的代码$_SESSION['message']在页面顶部声明,而session_start()在下方声明。现在告诉我将如何$_SESSION['message']识别是否有会话开始?除非你开始一个会话,否则你不能声明$_SESSION变量。这将导致错误。因此,这就是为什么我要求您session_start()在页面顶部声明这是必需且有效的 PHP 实践的原因。
打开App,查看更多内容
随时随地看视频慕课网APP