在HTML之前运行PHP

在HTML之前运行PHP,php,Php,从我的网站开始,我一直在构建我的网站,但是当我在PHP代码下面添加HTML表单(我以前构建为一个单独的文件)时,我遇到了一个问题,当我在PHP代码下面包含HTML代码时,PHP代码优先于HTML代码,我的意思是“死”(“请填写登记表!”);“正在通话中 <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post"> <input type="text" name=

从我的网站开始,我一直在构建我的网站,但是当我在PHP代码下面添加HTML表单(我以前构建为一个单独的文件)时,我遇到了一个问题,当我在PHP代码下面包含HTML代码时,PHP代码优先于HTML代码,我的意思是“死”(“请填写登记表!”);“正在通话中

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="email" name="email" placeholder="Email">
<input type="submit" value="Register">
</form>

假设您上一个问题中的代码仍然相关。如果您制作了mods,您将必须检查此项,因为我没有检查答案,以防您没有完全按照他们的建议执行

您必须始终进行一些测试,以检查表单是否确实已提交。请记住,第一次加载页面时,从单击链接或直接在浏览器中输入URL,表单尚未提交,因此没有任何表单字段将填充到
$\u POST
$\u GET
数组中供您创建使用

现在我使用的是
$\u服务器['REQUEST\u METHOD']
如果您只是运行页面,则不会设置,但如果表单提交按钮实际按下,则将包含
POST
GET
。一旦您知道可以继续检查所有字段是否已正确输入,并对这些字段执行可能需要的任何清理

session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Change this to your connection info.
$DB_HOST = 'localhost';
$DB_USER = '';
$DB_PASS = '';
$DB_NAME = '';

// Try and connect using the info above.
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
    // If there is an error with the connection, stop the script and display the error.
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}


// before doing anything with the posted field value
// check to see if the form was actually posted
// or is this the first time the page has been laoded


if($_SERVER['REQUEST_METHOD'] == 'POST'){

    // Now we check if the data was submitted, isset will check if the data exists.
    if ( !isset($_POST['username'], $_POST['password'], $_POST['email'])) {
        // Could not get the data that should have been sent.
        die ('Please complete the registration form!');
    }

    // Also check if the submitted values are empty
    if ( empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])) {
        // One or more values are empty...
        die ('Please complete the registration form!');
    }
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        die ('Email is not valid!');
    }
    if (preg_match('^[0-9A-Za-z_]+$^', username) == 0) {
        die ('Invalid username!');
    }
    if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
        die ('Password must be between 5 and 20 characters long.');
    }
    // We need to check if the account with that username exists
    if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
        // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
        $stmt->bind_param('s', $_POST['username']);
        $stmt->execute(); 
        $stmt->store_result(); 
        // Store the result so we can check if the account exists in the database.
        if ($stmt->num_rows > 0) {
            // Username already exists
            echo 'Username exists, please choose another!';
        } else {
            // Username doesnt exists, insert new account
            if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {
                $stmt->bind_param('sss', $_POST['username'], password_hash($_POST['password'], PASSWORD_DEFAULT), $_POST['email']);
                $stmt->execute();
                echo 'You have successfully registered, you can now login!';
            } else {
                echo 'Could not prepare statement!';
            }
        }
        $stmt->close();
    } else {
        echo 'Could not prepare statement!';
    }

// HTML CODE TO FOLLOW after the `?>`
?>
session_start();
ini设置(“显示错误”,1);
ini设置(“显示启动错误”,1);
错误报告(E_全部);
//将此更改为您的连接信息。
$DB_HOST='localhost';
$DB_USER='';
$DB_PASS='';
$DB_NAME='';
//尝试使用上面的信息进行连接。
$con=mysqli\u connect($DB\u HOST、$DB\u USER、$DB\u PASS、$DB\u NAME);
if(mysqli\u connect\u errno()){
//如果连接有错误,请停止脚本并显示错误。
die('未能连接到MySQL:'。mysqli_connect_error());
}
//在使用已发布的字段值执行任何操作之前
//检查表单是否已实际发布
//还是这是第一次对页面进行修改
如果($\u服务器['REQUEST\u METHOD']=='POST'){
//现在我们检查数据是否已提交,isset将检查数据是否存在。
如果(!isset($\u POST['username'],$\u POST['password'],$\u POST['email'])){
//无法获取本应发送的数据。
死亡('请填写登记表!');
}
//还要检查提交的值是否为空
如果(空($_POST['username'])空($_POST['password'])空($_POST['email'])){
//一个或多个值为空。。。
死亡('请填写登记表!');
}
如果(!filter_var($_POST['email'],filter_VALIDATE_email)){
死亡('电子邮件无效!');
}
如果(preg_match('^[0-9A-Za-z_]+$^',用户名)=0){
die('无效用户名!');
}
如果(strlen($_POST['password'])>20 | | strlen($_POST['password'])<5){
die('密码长度必须在5到20个字符之间');
}
//我们需要检查具有该用户名的帐户是否存在
if($stmt=$con->prepare('SELECT id,password FROM accounts WHERE username=?')){
//绑定参数(s=string、i=int、b=blob等),使用PHP password\u散列函数散列密码。
$stmt->bind_param('s',$_POST['username']);
$stmt->execute();
$stmt->store_result();
//存储结果,以便我们可以检查数据库中是否存在该帐户。
如果($stmt->num_rows>0){
//用户名已存在
echo'用户名存在,请选择其他!';
}否则{
//用户名不存在,请插入新帐户
如果($stmt=$con->prepare($INSERT-INTO-accounts(用户名、密码、电子邮件)值(?,?)){
$stmt->bind_-param('sss',$_-POST['username'],password_-hash($_-POST['password'],password_-DEFAULT),$_-POST['email']);
$stmt->execute();
echo“您已成功注册,现在可以登录!”;
}否则{
echo“无法准备语句!”;
}
}
$stmt->close();
}否则{
echo“无法准备语句!”;
}
//“?>`
?>

这是因为你没有检查你的表单是否真的提交了。你必须记住,第一次加载时的页面还没有提交,因此表单字段中不存在数据。因此,如果你需要帮助,请向我们显示所有页面代码,或者至少这里几乎没有php。至于你的“y,我指的是行”死了(“请填写登记表!”);“正在通话。”-那是什么?欢迎,为了提高你的体验,请阅读如何提问,以及如何创建和@Funk四十九:这是我在帖子中提到的后续问题,我不想因为重新发布相同的代码而遇到麻烦,前一篇帖子在第一篇帖子中链接。感谢你回复我的帖子,我真的很感激,你的回复帮助我澄清了哪里出了问题,我真的很感激,PHP可以被包装在if($\u服务器['REQUEST\u METHOD']='POST')中。它需要是有效的HTML,带有所有的'`和
标记等等。是的,我的错,谢谢,它正在工作,非常感谢。